feat(dynamodb): opt-in TransactionConflict emulation for contending transactions (#9179)

With floci.services.dynamodb.transaction-conflicts-enabled on, a
TransactWriteItems keeps its items busy from the moment its conditions
hold until 10 ms after it commits, and answers when that time is up.
While an item is busy, a PutItem, UpdateItem, DeleteItem or single-item
PartiQL write on it fails with TransactionConflictException, and another
TransactWriteItems or a TransactGetItems that reaches it is cancelled
with the reason TransactionConflict, as the developer guide describes.
GetItem, Query, Scan and BatchWriteItem are unaffected, and a
transaction that is cancelled holds nothing.

The busy mark is a deadline kept beside the item, so no item lock is
held during the wait. Off, the default, transactions keep serializing on
their item locks as before. The switch is refused at startup on the
local backend.

Closes #4523
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 01:03:17 -04:00
1 parent df43df43f6
commit 11b66161cd
12 files changed
+680 -15

No files matched your search

@@ -1732,6 +1732,16 @@ public interface EmulatorConfig {
@WithDefault("1000")
int streamMaxRecords();
/**
* Emulates the transaction conflicts DynamoDB reports under contention: a TransactWriteItems keeps its
* items busy for a few milliseconds, so a PutItem, UpdateItem or DeleteItem on one fails with
* TransactionConflictException and another TransactWriteItems or a TransactGetItems is cancelled with
* TransactionConflict. Off, overlapping transactions serialize instead. The native backend only.
* Env: FLOCI_SERVICES_DYNAMODB_TRANSACTION_CONFLICTS_ENABLED.
*/
@WithDefault("false")
boolean transactionConflictsEnabled();
/** The engine behind the DynamoDB API: {@code native} or {@code local}. Env: FLOCI_SERVICES_DYNAMODB_BACKEND. */
@WithDefault("native")
String backend();
@@ -184,6 +184,7 @@ public class DynamoDbService {
private DynamoDbStreamService streamService;
private KinesisStreamingForwarder kinesisForwarder;
private S3Service s3Service;
private DynamoDbTransactionConflicts transactionConflicts = DynamoDbTransactionConflicts.OFF;
private final int vectorIndexAllocationSeconds;
private final int vectorIndexBackfillSeconds;
private static final long MAX_DYNAMODB_LIST_INDEX = 4_294_967_294L;
@@ -210,6 +211,13 @@ public class DynamoDbService {
config.services().dynamodb().vectorIndexAllocationSeconds(),
config.services().dynamodb().vectorIndexBackfillSeconds(),
config.services().dynamodb().latestRestorableLagSeconds(), Clock.systemUTC());
this.transactionConflicts = DynamoDbTransactionConflicts.of(
config.services().dynamodb().transactionConflictsEnabled());
}
/** Package-private for tests: the transaction conflict emulation this service applies. */
void useTransactionConflicts(DynamoDbTransactionConflicts transactionConflicts) {
this.transactionConflicts = transactionConflicts;
}
/** The item store the configured {@code item-layout} selects; package-private for tests. */
@@ -354,6 +362,7 @@ public class DynamoDbService {
/** Emulator reset: drops the in-process item cache, locks and idempotency tokens, and stream state. */
public void clearProcessState() {
itemsByTable.clear();
transactionConflicts.clear();
itemLocks.clear();
txIdempotency.clear();
pointInTimeRecovery.clear();
@@ -1166,7 +1175,7 @@ public class DynamoDbService {
String canonicalTableName = canonicalTableName(region, tableName);
requireActiveTable(regionKey(region, canonicalTableName));
return putItemInternal(tableName, item, conditionExpression, exprAttrNames, exprAttrValues,
region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck);
region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck, true);
}
private JsonNode putItemInternal(String tableName, JsonNode item,
@@ -1185,7 +1194,7 @@ public class DynamoDbService {
boolean shouldPersist,
Consumer<Runnable> deferredStreamEvents) {
return putItemInternal(tableName, item, conditionExpression, exprAttrNames, exprAttrValues,
region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null);
region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null, false);
}
private JsonNode putItemInternal(String tableName, JsonNode item,
@@ -1195,7 +1204,8 @@ public class DynamoDbService {
boolean shouldPersist,
Consumer<Runnable> deferredStreamEvents,
Map<String, ConcurrentSkipListMap<String, JsonNode>> stagedItems,
Consumer<JsonNode> existingItemCheck) {
Consumer<JsonNode> existingItemCheck,
boolean singleItemWrite) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
@@ -1208,6 +1218,9 @@ public class DynamoDbService {
validateIndexKeyTypes(table, normalizedItem, false);
return withItemLock(storageKey, itemKey, () -> {
if (singleItemWrite) {
transactionConflicts.rejectSingleItemWrite(scopedItemsKey(storageKey), itemKey);
}
ConcurrentSkipListMap<String, JsonNode> tableItems = itemsFor(storageKey, stagedItems, true);
JsonNode existing = tableItems.get(itemKey);
@@ -1290,7 +1303,7 @@ public class DynamoDbService {
String region, String returnValuesOnConditionCheckFailure,
Consumer<JsonNode> existingItemCheck) {
return deleteItemInternal(tableName, key, conditionExpression, exprAttrNames, exprAttrValues,
region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck);
region, returnValuesOnConditionCheckFailure, true, null, null, existingItemCheck, true);
}
private JsonNode deleteItemInternal(String tableName, JsonNode key,
@@ -1309,7 +1322,7 @@ public class DynamoDbService {
boolean shouldPersist,
Consumer<Runnable> deferredStreamEvents) {
return deleteItemInternal(tableName, key, conditionExpression, exprAttrNames, exprAttrValues,
region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null);
region, returnValuesOnConditionCheckFailure, shouldPersist, deferredStreamEvents, null, null, false);
}
private JsonNode deleteItemInternal(String tableName, JsonNode key,
@@ -1319,7 +1332,8 @@ public class DynamoDbService {
boolean shouldPersist,
Consumer<Runnable> deferredStreamEvents,
Map<String, ConcurrentSkipListMap<String, JsonNode>> stagedItems,
Consumer<JsonNode> existingItemCheck) {
Consumer<JsonNode> existingItemCheck,
boolean singleItemWrite) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = requireActiveTable(storageKey);
@@ -1327,6 +1341,9 @@ public class DynamoDbService {
String itemKey = buildItemKey(table, key, true);
return withItemLock(storageKey, itemKey, () -> {
if (singleItemWrite) {
transactionConflicts.rejectSingleItemWrite(scopedItemsKey(storageKey), itemKey);
}
ConcurrentSkipListMap<String, JsonNode> items = itemsFor(storageKey, stagedItems, false);
if (existingItemCheck != null) {
existingItemCheck.accept(items == null ? null : items.get(itemKey));
@@ -1404,7 +1421,7 @@ public class DynamoDbService {
return updateItemInternal(tableName, key, attributeUpdates, updateExpression,
expressionAttrNames, expressionAttrValues, returnValues,
conditionExpression, region, returnValuesOnConditionCheckFailure, true, null, null,
UpdateSizeRule.UPDATE_ITEM, existingItemCheck);
UpdateSizeRule.UPDATE_ITEM, existingItemCheck, true);
}
UpdateResult updateItem(String tableName, JsonNode key, JsonNode attributeUpdates,
@@ -1415,7 +1432,8 @@ public class DynamoDbService {
UpdateSizeRule sizeRule) {
return updateItemInternal(tableName, key, attributeUpdates, updateExpression,
expressionAttrNames, expressionAttrValues, returnValues,
conditionExpression, region, returnValuesOnConditionCheckFailure, true, sizeRule);
conditionExpression, region, returnValuesOnConditionCheckFailure, true, null, null, sizeRule,
null, true);
}
private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates,
@@ -1442,7 +1460,7 @@ public class DynamoDbService {
return updateItemInternal(tableName, key, attributeUpdates, updateExpression,
expressionAttrNames, expressionAttrValues, returnValues,
conditionExpression, region, returnValuesOnConditionCheckFailure, shouldPersist,
deferredStreamEvents, null, sizeRule, null);
deferredStreamEvents, null, sizeRule, null, false);
}
private UpdateResult updateItemInternal(String tableName, JsonNode key, JsonNode attributeUpdates,
@@ -1454,7 +1472,8 @@ public class DynamoDbService {
Consumer<Runnable> deferredStreamEvents,
Map<String, ConcurrentSkipListMap<String, JsonNode>> stagedItems,
UpdateSizeRule sizeRule,
Consumer<JsonNode> existingItemCheck) {
Consumer<JsonNode> existingItemCheck,
boolean singleItemWrite) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = requireActiveTable(storageKey);
@@ -1468,6 +1487,9 @@ public class DynamoDbService {
}
return withItemLock(storageKey, itemKey, () -> {
if (singleItemWrite) {
transactionConflicts.rejectSingleItemWrite(scopedItemsKey(storageKey), itemKey);
}
ConcurrentSkipListMap<String, JsonNode> items = itemsFor(storageKey, stagedItems, true);
// Get existing item or create new one from key
@@ -2170,11 +2192,15 @@ public class DynamoDbService {
}
List<ReentrantLock> acquired = new ArrayList<>(toAcquire.size());
List<DynamoDbTransactionConflicts.Item> held = List.of();
long holdDeadline = 0;
boolean committed = false;
try {
for (ReentrantLock lock : toAcquire.values()) {
lock.lock();
acquired.add(lock);
}
rejectHeldParticipants(memberParticipants);
List<Runnable> pendingStreamEvents = new ArrayList<>();
Set<String> affectedStorageKeys = new LinkedHashSet<>();
@@ -2209,6 +2235,10 @@ public class DynamoDbService {
if (hasFailed) {
throw new TransactionCanceledException(cancellationReasons);
}
held = toAcquire.keySet().stream()
.map(p -> new DynamoDbTransactionConflicts.Item(scopedItemsKey(p.storageKey()), p.itemKey()))
.toList();
holdDeadline = transactionConflicts.hold(held);
List<JsonNode> oldImages = stagedImages(memberParticipants, staged);
for (JsonNode transactItem : transactItems) {
if (transactItem.has("Put")) {
@@ -2216,14 +2246,14 @@ public class DynamoDbService {
String tableName = put.path("TableName").asText();
String storageKey = regionKey(region, canonicalTableName(region, tableName));
putItemInternal(tableName, put.get("Item"), null, null, null, region, "NONE", false,
pendingStreamEvents::add, staged, null);
pendingStreamEvents::add, staged, null, false);
affectedStorageKeys.add(storageKey);
} else if (transactItem.has("Delete")) {
JsonNode del = transactItem.get("Delete");
String tableName = del.path("TableName").asText();
String storageKey = regionKey(region, canonicalTableName(region, tableName));
deleteItemInternal(tableName, del.get("Key"), null, null, null, region, "NONE", false,
pendingStreamEvents::add, staged, null);
pendingStreamEvents::add, staged, null, false);
affectedStorageKeys.add(storageKey);
} else if (transactItem.has("Update")) {
JsonNode upd = transactItem.get("Update");
@@ -2234,7 +2264,7 @@ public class DynamoDbService {
upd.has("ExpressionAttributeNames") ? upd.get("ExpressionAttributeNames") : null,
upd.has("ExpressionAttributeValues") ? upd.get("ExpressionAttributeValues") : null,
"NONE", null, region, "NONE", false, pendingStreamEvents::add, staged,
UpdateSizeRule.FINISHED_ITEM, null);
UpdateSizeRule.FINISHED_ITEM, null, false);
affectedStorageKeys.add(storageKey);
}
}
@@ -2272,11 +2302,39 @@ public class DynamoDbService {
for (Runnable streamEvent : pendingStreamEvents) {
streamEvent.run();
}
holdDeadline = transactionConflicts.settle(held, holdDeadline);
committed = true;
return new AppliedTransactWrite(writeCapacity, replayCapacity);
} finally {
for (int i = acquired.size() - 1; i >= 0; i--) {
acquired.get(i).unlock();
}
transactionConflicts.release(held, holdDeadline, committed);
}
}
/**
* With transaction conflicts emulated, cancels a write transaction one of whose items another write
* transaction holds, with {@code TransactionConflict} at that item, before any condition is evaluated.
*/
private void rejectHeldParticipants(List<TransactParticipant> memberParticipants) {
if (!transactionConflicts.enabled()) {
return;
}
List<TransactionCanceledException.CancellationReason> reasons = new ArrayList<>();
boolean conflicted = false;
for (TransactParticipant participant : memberParticipants) {
if (participant != null
&& transactionConflicts.busy(scopedItemsKey(participant.storageKey()), participant.itemKey())) {
conflicted = true;
reasons.add(new TransactionCanceledException.CancellationReason(
DynamoDbTransactionConflicts.REASON, null, DynamoDbTransactionConflicts.MESSAGE));
} else {
reasons.add(new TransactionCanceledException.CancellationReason("", null));
}
}
if (conflicted) {
throw new TransactionCanceledException(reasons);
}
}
@@ -2578,9 +2636,18 @@ public class DynamoDbService {
JsonNode key = get.get("Key");
try {
JsonNode item = getItem(tableName, key, region);
TableDefinition table = requireTableForItemCall(tableName, region);
String itemsKey = scopedItemsKey(regionKey(region, canonicalTableName(region, tableName)));
if (transactionConflicts.busy(itemsKey, buildItemKey(table, key, true))) {
hasCancelled = true;
results.add(null);
cancelReasons.add(new TransactionCanceledException.CancellationReason(
DynamoDbTransactionConflicts.REASON, null, DynamoDbTransactionConflicts.MESSAGE));
continue;
}
results.add(projectTransactGet(item, get));
capacity.merge(canonicalTableName(region, tableName),
DynamoDbTransactCapacity.read(requireTableForItemCall(tableName, region), item, null),
DynamoDbTransactCapacity.read(table, item, null),
DynamoDbWriteCapacity.Cost::plus);
cancelReasons.add(new TransactionCanceledException.CancellationReason("", null));
} catch (AwsException e) {
@@ -0,0 +1,169 @@
package io.floci.aws.services.dynamodb;
import io.floci.aws.core.common.AwsException;
import java.time.Duration;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.LockSupport;
import java.util.function.LongSupplier;
/**
* Opt-in emulation of the transaction conflicts DynamoDB reports under contention, switched on by
* {@code floci.services.dynamodb.transaction-conflicts-enabled}.
*
* <p>On AWS a TransactWriteItems keeps each of its items busy from the moment the item accepts the
* transaction until the transaction commits. The developer guide rejects a PutItem, UpdateItem or
* DeleteItem on a busy item with {@code TransactionConflictException}, and cancels another
* TransactWriteItems, or a TransactGetItems, that reaches one with the reason {@code TransactionConflict};
* a GetItem is not affected. Floci applies a transaction in microseconds, so with the switch on a write
* transaction marks its items busy from the moment they accept it until {@link #HOLD} after it commits, and
* answers only when that time is up: a caller that waits for one transaction before it sends the next never
* sees a conflict, callers that overlap do. The mark is a deadline kept beside the item, so no item lock is
* held while a transaction waits.
*
* <p>Off, the default, every method is a no-op and overlapping transactions keep serializing on their
* item locks.
*/
final class DynamoDbTransactionConflicts {
/**
* How long a write transaction keeps its items busy. DynamoDB answers in single-digit milliseconds, and
* a write transaction takes about four times as long as a PutItem ("Distributed Transactions at Scale in
* Amazon DynamoDB", USENIX ATC 2023).
*/
static final Duration HOLD = Duration.ofMillis(10);
static final String REASON = "TransactionConflict";
/** The message AWS gives the {@code TransactionConflict} reason and {@code TransactionConflictException}. */
static final String MESSAGE = "Transaction is ongoing for the item";
/** How far ahead a mark is dated while its transaction still commits, so it cannot lapse before {@link #settle}. */
private static final long WHILE_COMMITTING_NANOS = Long.MAX_VALUE / 4;
static final DynamoDbTransactionConflicts OFF = new DynamoDbTransactionConflicts(false, HOLD, System::nanoTime,
DynamoDbTransactionConflicts::park);
/** One item of one table: the table's account-scoped items key and the item key. */
record Item(String table, String itemKey) {}
/** Waits until {@code deadlineNanos} on the clock {@code nanoTime} reads. */
@FunctionalInterface
interface Waiter {
void awaitDeadline(long deadlineNanos, LongSupplier nanoTime);
}
private final boolean enabled;
private final long holdNanos;
private final LongSupplier nanoTime;
private final Waiter waiter;
private final ConcurrentHashMap<Item, Long> busyUntil = new ConcurrentHashMap<>();
DynamoDbTransactionConflicts(boolean enabled, Duration hold, LongSupplier nanoTime, Waiter waiter) {
this.enabled = enabled;
this.holdNanos = hold.toNanos();
this.nanoTime = nanoTime;
this.waiter = waiter;
}
/** The emulation the configuration asks for. */
static DynamoDbTransactionConflicts of(boolean enabled) {
return enabled ? new DynamoDbTransactionConflicts(true, HOLD, System::nanoTime,
DynamoDbTransactionConflicts::park) : OFF;
}
boolean enabled() {
return enabled;
}
/** Whether a write transaction in flight holds the item now. */
boolean busy(String table, String itemKey) {
if (!enabled) {
return false;
}
Long until = busyUntil.get(new Item(table, itemKey));
return until != null && until - nanoTime.getAsLong() > 0;
}
/** Rejects a single-item write, a PutItem, UpdateItem, DeleteItem or PartiQL statement, on a held item. */
void rejectSingleItemWrite(String table, String itemKey) {
if (busy(table, itemKey)) {
throw new AwsException("TransactionConflictException", MESSAGE, 400);
}
}
/**
* Marks a write transaction's items busy, called while it holds their locks and after its conditions
* held. The marks last until {@link #settle} dates them, however long the commit takes. Returns the
* value the marks carry, or 0 when the emulation is off.
*/
long hold(Collection<Item> items) {
if (!enabled || items.isEmpty()) {
return 0;
}
long mark = nanoTime.getAsLong() + WHILE_COMMITTING_NANOS;
for (Item item : items) {
busyUntil.put(item, mark);
}
return mark;
}
/**
* Starts the {@link #HOLD} of a transaction that has committed, called while it still holds its item locks,
* so the window counts from the moment it would answer. Returns the deadline its marks now carry, for
* {@link #release}, or 0 when nothing was held.
*/
long settle(Collection<Item> items, long mark) {
if (mark == 0) {
return 0;
}
long deadline = nanoTime.getAsLong() + holdNanos;
for (Item item : items) {
busyUntil.replace(item, mark, deadline);
}
return deadline;
}
/**
* Ends a transaction's hold, called once it has released its item locks: a committed transaction first
* waits out the hold, as it would still be running on AWS, and one that failed does not. Only marks
* this transaction set are removed.
*/
void release(Collection<Item> items, long deadline, boolean committed) {
if (deadline == 0) {
return;
}
try {
if (committed) {
waiter.awaitDeadline(deadline, nanoTime);
}
} finally {
for (Item item : items) {
busyUntil.remove(item, deadline);
}
}
}
/** Emulator reset: forgets every mark. */
void clear() {
busyUntil.clear();
}
/**
* Waits until the deadline. An interrupt does not cut the hold short, since overlapping requests would then
* get through while the transaction is still meant to be running: the wait goes on, and the interrupt
* status is restored once it ends.
*/
static void park(long deadlineNanos, LongSupplier nanoTime) {
boolean interrupted = false;
long remaining;
while ((remaining = deadlineNanos - nanoTime.getAsLong()) > 0) {
LockSupport.parkNanos(remaining);
interrupted |= Thread.interrupted();
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
@@ -3365,7 +3365,7 @@ public class NativeDynamoDbJsonHandler {
ObjectNode r = objectMapper.createObjectNode();
r.put("Code", reason.code().isEmpty() ? "None" : reason.code());
if (!reason.code().isEmpty()) {
r.put("Message", "");
r.put("Message", reason.message() != null ? reason.message() : "");
}
if (reason.item() != null) {
r.set("Item", reason.item());
@@ -32,6 +32,11 @@ public class DynamoDbBackendSelector {
default -> throw new IllegalStateException(
"floci.services.dynamodb.backend must be 'native' or 'local', got '" + configured + "'");
};
// DynamoDB Local applies its own transactions, so Floci has nothing to emulate the conflicts in.
if ("local".equals(selected) && config.services().dynamodb().transactionConflictsEnabled()) {
throw new IllegalStateException("floci.services.dynamodb.transaction-conflicts-enabled needs the native "
+ "backend; floci.services.dynamodb.backend is 'local'");
}
}
/** The selected engine name, {@code native} or {@code local}. */