Conditional writes are DynamoDB's main concurrency primitive and they are excellent. A ConditionExpression on a PutItem, UpdateItem or DeleteItem is evaluated atomically with the write: if it is false, the write does not happen and you get a ConditionalCheckFailedException. That gives you, in one request:
- Create-if-absent:
attribute_not_exists(PK). - Optimistic locking:
version = :expectedVersion, with the write incrementing it. - Business rules enforced in the database:
stock >= :qty,#st = :expectedStatus. - Idempotency: a condition on a request id attribute.
Two related features: atomic counters (SET n = n + :inc) are applied server-side without a read, so they are safe under concurrency but not idempotent on retry; and ReturnValuesOnConditionCheckFailure gives you the item that failed the condition, saving a follow-up read.
Idempotency matters more here than in most databases because the SDK retries automatically on throttling and network errors. A timed-out request may have succeeded. So any non-idempotent operation - an atomic counter increment, an append to a list - needs a request-id condition or a design that makes retrying harmless.
Eventual against strong consistency. By default a GetItem or Query is eventually consistent: it may be served by a replica that has not yet applied the latest write, so a read immediately after a write can return the old value. ConsistentRead: true gives you the latest committed value and costs twice the read capacity, with slightly higher latency. GSIs are always eventually consistent and cannot be read strongly - which is a design constraint, not a setting, and it means a workflow that writes an item and immediately queries a GSI for it may not find it.
Transactions. TransactWriteItems applies up to 100 operations atomically, across tables, with per-item conditions, and includes a ConditionCheck action that asserts something about an item without writing it. TransactGetItems reads a consistent snapshot. The costs, which must be stated: a transaction consumes twice the capacity of the equivalent non-transactional operations, because of the two-phase protocol; it fails entirely if any condition fails or if two transactions conflict on an item (TransactionCanceledException, whose CancellationReasons names the item and the cause); and the same item may not appear twice in one transaction.
The guidance: use a conditional write first and a transaction only when the invariant genuinely spans items. Many apparent transaction needs disappear when related items share a partition key and a single conditional update can maintain the invariant.
Streams are a change log: every item-level modification, in order per partition key, retained 24 hours, with StreamViewType controlling whether you see the new image, the old image, both, or just the keys. Consumed by Lambda (with batching, retries and a configurable failure destination) or the Kinesis Adapter. Streams are how you maintain denormalised copies, update a search index, emit events and build audit trails. The consumer rules: it must be idempotent, because delivery is at-least-once; it must handle out-of-order across different partition keys; and a failing Lambda batch retries until it succeeds or the records expire, so a poison record can stall a shard - which is what BisectBatchOnFunctionError and a failure destination are for.
Laboratory exercise 3 - correctness under concurrency.
Build a cart and order service and run at least 100 concurrent clients.
Implement "add to cart" three ways and compare: an unconditional PutItem, an optimistic-locking UpdateItem with a version attribute, and a TransactWriteItems updating the cart total and the line item together. Measure throughput, failure rate and consumed capacity for each - the capacity difference for the transaction is the point.
Demonstrate the lost update: two concurrent unconditional writes to the same cart, with one overwriting the other. Then show the conditional version refusing.
Demonstrate the consistency gap: write an item, immediately read it eventually-consistently in a loop, and record how often you get the stale value. Then do the same against a GSI and record how long the index took to catch up.
Implement inventory reservation with stock >= :qty as a condition and show it refusing to go negative under 100 concurrent orders.
Enable Streams and build a Lambda consumer that maintains a denormalised order count on the user item. Make it idempotent and prove it, by replaying the same batch twice and showing the count unchanged. Then introduce a poison record and show the retry behaviour, and fix it with bisection and a failure destination.
Deliverable: the service, the three-way comparison including capacity, the lost update demonstrated and fixed, the eventual consistency measurements for both the table and the GSI, the inventory invariant under load, the idempotent stream consumer with the replay proof, and the poison record handling.
// ==================================================================
// CONDITIONAL WRITES: the main concurrency primitive, and it is good.
// The condition is evaluated ATOMICALLY with the write.
// ==================================================================
import { TransactWriteCommand, TransactGetCommand } from "@aws-sdk/lib-dynamodb";
// CREATE IF ABSENT:
await db.send(new PutCommand({
TableName: "Commerce",
Item: { PK: "CART#u-1234", SK: "META", status: "active", version: 1 },
ConditionExpression: "attribute_not_exists(PK)"
}));
// -> ConditionalCheckFailedException if it already exists.
// OPTIMISTIC LOCKING. The fix for the lost update:
try {
await db.send(new UpdateCommand({
TableName: "Commerce",
Key: { PK: "CART#u-1234", SK: "META" },
UpdateExpression: "SET #t = :t, version = :new, updatedAt = :now",
ConditionExpression: "version = :expected",
ExpressionAttributeNames: { "#t": "total" },
ExpressionAttributeValues: {
":t": 179.96, ":new": 5, ":expected": 4,
":now": new Date().toISOString() },
// Saves a follow-up read on failure:
ReturnValuesOnConditionCheckFailure: "ALL_OLD"
}));
} catch (e) {
if (e.name === "ConditionalCheckFailedException") {
e.Item; // the item as it actually is. Re-read and retry.
} else throw e;
}
// A BUSINESS RULE, ENFORCED IN THE DATABASE. No read, no race:
await db.send(new UpdateCommand({
TableName: "Commerce",
Key: { PK: "PRODUCT#SKU-001", SK: "META" },
UpdateExpression: "SET stock = stock - :q",
ConditionExpression: "stock >= :q",
ExpressionAttributeValues: { ":q": 2 }
}));
// Cannot go negative under ANY concurrency. ConditionalCheckFailed
// means "out of stock" - a business answer, not an error to retry.
// ATOMIC COUNTERS: safe under concurrency, NOT idempotent on retry.
await db.send(new UpdateCommand({
TableName: "Commerce", Key: { PK: "USER#u-1234", SK: "META" },
UpdateExpression: "SET orderCount = if_not_exists(orderCount, :z) + :one",
ExpressionAttributeValues: { ":z": 0, ":one": 1 }
}));
// THE SDK RETRIES AUTOMATICALLY on throttling and network errors, so
// a timed-out request MAY HAVE SUCCEEDED. This increment can be
// applied twice. Guard it:
await db.send(new TransactWriteCommand({ TransactItems: [
{ Put: { TableName: "Commerce",
Item: { PK: "REQUEST#req-abc123", SK: "META",
ttl: Math.floor(Date.now()/1000) + 86400 },
ConditionExpression: "attribute_not_exists(PK)" }},
{ Update: { TableName: "Commerce", Key: {PK:"USER#u-1234", SK:"META"},
UpdateExpression: "SET orderCount = orderCount + :one",
ExpressionAttributeValues: {":one": 1} }}
]}));
// A repeat fails on the request-id condition and nothing is applied.
// ==================================================================
// EVENTUAL vs STRONG consistency.
// ==================================================================
await db.send(new GetCommand({
TableName: "Commerce", Key: { PK: "CART#u-1234", SK: "META" }
}));
// DEFAULT: EVENTUALLY consistent. A read right after a write CAN
// return the old value. 0.5 RCU per 4 KB.
await db.send(new GetCommand({
TableName: "Commerce", Key: { PK: "CART#u-1234", SK: "META" },
ConsistentRead: true
}));
// The latest committed value. 1.0 RCU per 4 KB - TWICE THE COST -
// and slightly higher latency.
// GSIs ARE ALWAYS EVENTUALLY CONSISTENT. There is no option:
await db.send(new QueryCommand({
TableName: "Commerce", IndexName: "GSI1",
KeyConditionExpression: "gsi1pk = :g",
ExpressionAttributeValues: { ":g": "STATUS#pending" }
// ConsistentRead: true -> ValidationException. Not permitted.
}));
// A DESIGN CONSTRAINT, not a setting. A workflow that writes an item
// and IMMEDIATELY queries a GSI for it MAY NOT FIND IT. Measure the
// lag in the lab; design around it (read the base table by key for
// read-your-writes, use the GSI for listing).
// ==================================================================
// TRANSACTIONS: up to 100 items, atomic, and TWICE THE CAPACITY.
// ==================================================================
try {
const r = await db.send(new TransactWriteCommand({
ClientRequestToken: "checkout-u1234-20261130-0914", // idempotency,
// 10-minute window, same params required
ReturnConsumedCapacity: "INDEXES",
TransactItems: [
// ConditionCheck: ASSERT something without writing it.
{ ConditionCheck: {
TableName: "Commerce", Key: {PK:"USER#u-1234", SK:"META"},
ConditionExpression: "#st = :active",
ExpressionAttributeNames: {"#st": "status"},
ExpressionAttributeValues: {":active": "active"} }},
{ Update: {
TableName: "Commerce", Key: {PK:"PRODUCT#SKU-001", SK:"META"},
UpdateExpression: "SET stock = stock - :q",
ConditionExpression: "stock >= :q",
ExpressionAttributeValues: {":q": 1} }},
{ Put: {
TableName: "Commerce",
Item: {PK:"ORDER#o-55", SK:"META", status:"pending",
gsi1pk:"STATUS#pending", total: 89.99},
ConditionExpression: "attribute_not_exists(PK)" }},
{ Update: {
TableName: "Commerce", Key: {PK:"CART#u-1234", SK:"META"},
UpdateExpression: "SET #st = :done",
ExpressionAttributeNames: {"#st": "status"},
ExpressionAttributeValues: {":done": "checked_out"} }}
]
}));
r.ConsumedCapacity; // roughly 2x the non-transactional equivalent
} catch (e) {
if (e.name === "TransactionCanceledException") {
e.CancellationReasons;
// [ {Code:'None'},
// {Code:'ConditionalCheckFailed', Message:'...'}, <- out of stock
// {Code:'None'}, {Code:'None'} ]
// POSITIONAL, matching TransactItems. This is how you tell WHICH
// condition failed - and it is the only way.
}
}
// THE COSTS, stated:
// * 2x capacity, from the two-phase protocol
// * all or nothing: any failed condition cancels everything
// * two transactions conflicting on an item -> TransactionConflict
// * the SAME ITEM may not appear TWICE in one transaction
//
// USE A CONDITIONAL WRITE FIRST. A transaction only when the
// invariant GENUINELY SPANS ITEMS. Many apparent transaction needs
// disappear when related items share a partition key.
// ==================================================================
// STREAMS: the change log. 24 hours, ordered PER PARTITION KEY.
// ==================================================================
// aws dynamodb update-table --table-name Commerce \
// --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
//
// KEYS_ONLY | NEW_IMAGE | OLD_IMAGE | NEW_AND_OLD_IMAGES
export const handler = async (event) => {
const failures = [];
for (const record of event.Records) {
try {
// record.eventName: INSERT | MODIFY | REMOVE
// record.dynamodb.NewImage / .OldImage / .Keys
// record.dynamodb.SequenceNumber - ordered WITHIN a partition key
const img = record.dynamodb.NewImage;
if (record.eventName === "INSERT" && img?.entityType?.S === "Order") {
// IDEMPOTENT: conditioned on the sequence number, so a replay
// is a no-op. Delivery is AT-LEAST-ONCE - prove this by
// replaying the same batch and showing the count unchanged.
await db.send(new UpdateCommand({
TableName: "Commerce",
Key: { PK: `USER#${img.userId.S}`, SK: "META" },
UpdateExpression:
"SET orderCount = if_not_exists(orderCount,:z) + :one, " +
"lastSeq = :seq",
ConditionExpression:
"attribute_not_exists(lastSeq) OR lastSeq < :seq",
ExpressionAttributeValues: {
":z": 0, ":one": 1, ":seq": record.dynamodb.SequenceNumber }
}));
}
} catch (e) {
if (e.name !== "ConditionalCheckFailedException") {
// PARTIAL BATCH RESPONSE: report only the failures, so the
// successful records are not reprocessed.
failures.push({ itemIdentifier: record.dynamodb.SequenceNumber });
}
}
}
return { batchItemFailures: failures };
};
// THE CONSUMER RULES:
// 1. IDEMPOTENT - delivery is at-least-once
// 2. ORDER IS GUARANTEED ONLY WITHIN A PARTITION KEY, never across
// 3. A FAILING BATCH RETRIES UNTIL IT SUCCEEDS OR THE RECORDS
// EXPIRE (24 h), so ONE POISON RECORD CAN STALL A SHARD.
// Configure: BisectBatchOnFunctionError, MaximumRetryAttempts,
// a DestinationConfig failure destination, and return
// batchItemFailures. Demonstrate the stall in the lab first.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.