The system. A shopping cart and order service: carts with line items, checkout to an order, inventory that must not go negative, order status history, and a fulfilment view listing pending orders. Stream consumers maintain denormalised counts.
Three invariants must hold:
- An order's total equals the sum of its line items.
- Inventory never goes negative under concurrent checkout - including under SDK retries.
- Every order appears exactly once in the fulfilment view while pending, and not at all once shipped.
Invariant 2 is where the SDK's automatic retries matter: a timed-out checkout may have succeeded, so the design needs either a ClientRequestToken on the transaction or a request-id condition. Invariant 3 is the sparse index working correctly, including the attribute being removed on status change.
What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone.
An access pattern list, and a schema demonstrably derived from it. The numbered list comes first in the document, and for each pattern you state the key condition and the index used - or state that it requires a Scan and why that is acceptable. A schema presented without the list it serves has skipped the method this course teaches.
Measured capacity and a cost model against a declared baseline. Declare it first: item sizes, capacity mode, access pattern mix, p50/p95/p99, and consumed capacity per pattern. Then a projected monthly bill at three traffic levels, including index writes, storage, streams and PITR. A DynamoDB design you cannot price is a design you have not finished, and this is the criterion that most distinguishes a capstone that would survive a real architecture review.
A defensible account of failure modes, operational limits and cost. Throttling must be addressed with the right diagnosis. The eventual consistency of GSIs must be handled, not ignored. And the recovery runbook must enumerate what a PITR restore does not bring back.
Deliverables: architecture diagram; the numbered access pattern list; the single-table schema with each pattern mapped to its key condition; source code including conditional writes, retry handling and the stream consumer; infrastructure as code with retention policies; reproducible test dataset; benchmark report with capacity per pattern; cost model with three projections; security review including the IAM policies; recovery runbook with measured RPO and RTO; and a short design defence.
// ================= THE ACCESS PATTERN LIST COMES FIRST =============
// In the document, numbered, before the schema. A schema presented
// without the list it serves has skipped the method.
//
// # pattern key condition index
// 1 get cart + items PK=CART#uid base
// 2 add/update a line item PK=CART#uid, SK=ITEM#sku base
// 3 checkout transaction over 4 items base
// 4 get order + items + events PK=ORDER#oid base
// 5 list a user's orders desc PK=USER#uid, begins_with base
// 6 LIST PENDING ORDERS gsi1pk=STATUS#pending GSI1 sparse
// 7 order status history PK=ORDER#oid, EVENT# base
// 8 get a product PK=PRODUCT#sku base
// 9 reserve stock conditional update base
// 10 user order count PK=USER#uid (stream-fed) base
//
// Patterns 1,2,4,5,7,8,9,10 need NO INDEX. One sparse GSI serves 6.
// That is the design, and the list is why.
// ================= Invariants, as runnable assertions ==============
// 1. Order total == sum of line items.
async function checkTotals(orderId) {
const r = await db.send(new QueryCommand({
TableName: "Commerce",
KeyConditionExpression: "PK = :pk",
ExpressionAttributeValues: { ":pk": `ORDER#${orderId}` }
}));
const meta = r.Items.find(i => i.SK === "META");
const lines = r.Items.filter(i => i.SK.startsWith("ITEM#"));
const derived = lines.reduce((s,l) => s + l.unitPrice * l.quantity, 0);
return Math.abs(meta.total - derived) < 0.005; // must be true
}
// 2. Inventory never negative. Enforced by the condition, verified by
// a scheduled export-based check (NOT a production Scan):
// stock < 0 -> must be empty
// 3. The fulfilment view is exactly right: every pending order in
// GSI1, no shipped order in it.
// Query GSI1 STATUS#pending == the set of orders with
// status == 'pending'
// This is the sparse index working, INCLUDING the REMOVE on
// status change. A design that sets gsi1pk and never removes it
// fails invariant 3 and the index grows forever.
// ================= Checkout: the capstone's real problem ===========
// A timed-out checkout MAY HAVE SUCCEEDED - the SDK retries on
// throttling and network errors. Two layers of protection:
async function checkout(userId, orderId, lines, requestId) {
return db.send(new TransactWriteCommand({
// LAYER 1: idempotency at the transaction level. Same token and
// same parameters within 10 minutes = the same result, applied
// once.
ClientRequestToken: requestId,
ReturnConsumedCapacity: "INDEXES",
TransactItems: [
// LAYER 2: a request-id item, so a repeat beyond the token
// window still cannot double-apply.
{ Put: { TableName: "Commerce",
Item: { PK: `REQUEST#${requestId}`, SK: "META",
orderId,
ttl: Math.floor(Date.now()/1000) + 604800 },
ConditionExpression: "attribute_not_exists(PK)" }},
// Stock, conditionally. Cannot go negative under ANY
// concurrency; ConditionalCheckFailed means "out of stock",
// which is a business answer, not an error to retry.
...lines.map(l => ({ Update: {
TableName: "Commerce",
Key: { PK: `PRODUCT#${l.sku}`, SK: "META" },
UpdateExpression: "SET stock = stock - :q",
ConditionExpression: "stock >= :q",
ExpressionAttributeValues: { ":q": l.quantity } }})),
// The order, WITH the sparse index attribute set:
{ Put: { TableName: "Commerce",
Item: { PK: `ORDER#${orderId}`, SK: "META",
entityType: "Order", userId,
status: "pending",
gsi1pk: "STATUS#pending", // <- invariant 3
gsi1sk: new Date().toISOString(),
total: lines.reduce((s,l)=>s+l.unitPrice*l.quantity,0) },
ConditionExpression: "attribute_not_exists(PK)" }},
{ Update: { TableName: "Commerce",
Key: { PK: `CART#${userId}`, SK: "META" },
UpdateExpression: "SET #st = :done",
ConditionExpression: "#st = :active",
ExpressionAttributeNames: { "#st": "status" },
ExpressionAttributeValues: {
":done": "checked_out", ":active": "active" } }}
]
}));
}
// Max 100 items per transaction, so a cart with more than ~24 lines
// needs a different approach. Say so in the design.
// Shipping: REMOVE the sparse attribute, or invariant 3 fails:
await db.send(new UpdateCommand({
TableName: "Commerce", Key: { PK: `ORDER#${orderId}`, SK: "META" },
UpdateExpression: "SET #st = :s REMOVE gsi1pk, gsi1sk",
ConditionExpression: "#st = :pending",
ExpressionAttributeNames: { "#st": "status" },
ExpressionAttributeValues: { ":s": "shipped", ":pending": "pending" }
}));
// ================= Declare the baseline BEFORE measuring ===========
//
// Mode: on-demand for the test; provisioned projection too
// Items: cart META ~0.4 KB, line ~0.3 KB, order META ~0.6 KB
// (MEASURED distribution, from Module 1)
// Indexes: 1 sparse GSI, INCLUDE projection
// Dataset: 500,000 users, 2,000,000 orders, 8,000,000 items
// Mix: 50% cart read, 20% cart write, 5% checkout,
// 20% order read, 5% fulfilment list
//
// Claim - latency AND CAPACITY, per pattern:
// get cart + items p99 < 10 ms 1.0 RCU
// add line item p99 < 10 ms 2.0 WCU (1 table + 1 GSI)
// checkout (txn) p99 < 40 ms ~16 WCU (2x, 4 items)
// list pending (GSI) p99 < 15 ms 1.5 RCU
// list user orders p99 < 12 ms 2.5 RCU
//
// AND THE COST MODEL, at three levels:
// 10k orders/day 100k/day 1M/day
// write units ______ ______ ______
// INDEX writes ______ ______ ______
// read units ______ ______ ______
// storage GB ______ ______ ______
// streams ______ ______ ______
// PITR ______ ______ ______
// est. monthly $_____ $_____ $_____
//
// A DynamoDB design you cannot price is a design you have not
// finished. This is the criterion that most distinguishes a
// capstone that would survive a real architecture review.
// ================= Failure modes ==================================
// throttling, table has headroom A HOT PARTITION. Raising capacity
// does NOT help. Contributor
// Insights names the key; shard it.
// throttling, at provisioned genuinely too low. Raise it, or
// go on-demand.
// GSI throttled THROTTLES BASE TABLE WRITES.
// Surprising, and real.
// write then query the GSI GSIs are ALWAYS eventually
// consistent. Read the base table
// by key for read-your-writes.
// timed-out checkout may have SUCCEEDED. The SDK
// retries. ClientRequestToken plus
// a request-id item. Invariant 2.
// unretried UnprocessedItems BatchWrite SILENTLY LOSES WRITES.
// Retry with backoff, always.
// ignored LastEvaluatedKey silently PARTIAL results. No
// error. Works until the data grows.
// gsi1pk never removed the fulfilment view grows
// forever. Invariant 3.
// Scan with a filter bills for the WHOLE TABLE. Deny
// dynamodb:Scan in IAM.
// PITR restore NEW table, and WITHOUT TTL,
// streams, auto scaling or tags.
// Enumerate the reapplication.
// TTL expiry up to 48 h late expired items still returned.
// Filter on the attribute.
// poison stream record stalls the shard for up to 24 h.
// Bisection + failure destination.
//
// Verify after every recovery with the three assertions above.
// DescribeTable's ItemCount updates roughly every six hours, so it
// is useless right after a restore. Count properly.
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.