Access Patterns, Single-Table Design and Indexes

Article · 6:00

Writing the access pattern list, deriving a key schema, single-table design with overloaded keys, Query against Scan, GSIs and LSIs, and pagination.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

The method, in order, and the order is the point:

  1. List every access pattern. In a file, numbered, in plain language: "get a user's active cart with its items", "list a user's orders newest first", "get one order by id", "list all orders in pending status for the fulfilment screen".
  2. For each, write the key condition it will use. This is where you discover a pattern no key schema can serve cheaply.
  3. Derive the key schema - the table's keys and the smallest set of indexes - that serves the list.
  4. Only then create the table.

Doing this out of order is the source of most DynamoDB disappointment. A schema designed from an entity model will serve some patterns beautifully and leave others requiring a Scan.

Single-table design. Several entity types share one table, with generic key names and key overloading - PK holds USER#1234 for one item type and ORDER#5678 for another; SK holds META, ITEM#SKU-001, ORDER#2026-11-30#001. The payoffs are real: related entities of different types live in one item collection and come back in one request, and you pay for one table's indexes rather than five tables' worth.

The honest costs: the table is harder to read, generic attribute names resist tooling, analytics over it requires an export, and it demands that you got the access patterns right. The pragmatic position taken in this course: single-table design is the idiomatic approach and worth learning properly; using two or three tables where the entities genuinely do not interact is not a sin, and a team that cannot maintain a single-table schema will do worse with it than without.

Query against Scan is the cost distinction that matters most. A Query requires a partition key and reads only that partition - its cost is proportional to the data it returns. A Scan reads every item in the table and costs accordingly, then applies any filter. A FilterExpression does not reduce cost - it is applied after the read, so you pay to read everything and then discard most of it. That one sentence prevents more DynamoDB bill surprises than any other.

Secondary indexes. A GSI has its own partition and sort key, can be created and deleted at any time, has its own capacity, and is eventually consistent - always, with no option for a strongly consistent read. An LSI shares the table's partition key with a different sort key, must be created with the table and can never be added, supports strongly consistent reads, and imposes the 10 GB item collection limit. The practical guidance: use GSIs, and treat LSIs as a special case for when you genuinely need a strongly consistent alternative sort within a partition and are certain the collections stay small.

Index projections determine which attributes the index holds - KEYS_ONLY, INCLUDE, or ALL. A narrower projection means a smaller, cheaper index; but an attribute not projected requires a second fetch from the base table, so an index that does not cover its query loses much of its value.

The sparse index is the technique worth knowing: a GSI only contains items that have its key attributes. So setting a gsi1pk attribute only on items in pending status gives you an index containing only pending orders - a small, cheap index that answers "all pending orders" directly, where the alternative is a Scan with a filter.

Laboratory exercise 2 - two models, measured in capacity units.

Write the access pattern list for the capstone's cart and order service - at least ten patterns, numbered, each with its key condition.

Design two schemas that serve it: one single-table with overloaded keys and GSIs, and one with separate tables per entity type and client-side joins.

Implement both. Implement every access pattern on both. For any pattern that requires a Scan in either model, implement it and measure what it costs.

Measure both models in consumed capacity units, with ReturnConsumedCapacity: "INDEXES". Capacity is the billable unit and the honest comparison; record the RCUs and WCUs for each pattern in each model, and the write amplification from indexes.

Build a sparse GSI for "all pending orders" and compare it with the Scan-plus-filter alternative on both capacity and latency.

Then demonstrate that a filter does not reduce cost: a Scan with a filter returning 10 items from 200,000, with its consumed capacity.

Deliverable: the numbered access pattern list, both schemas with the key design for each pattern stated, all patterns implemented in both, the capacity comparison table, the sparse index comparison, the filter cost demonstration, and a page arguing for one model.

JS Example 1 178 lines
// ==================================================================
// STEP 1: THE ACCESS PATTERN LIST. In a file. Numbered. FIRST.
// ==================================================================
//  #  pattern                            key condition
//  1  get a user's profile               PK=USER#id, SK=META
//  2  get a user's active cart + items   PK=CART#uid
//  3  get only the cart's line items     PK=CART#uid, begins_with(SK,'ITEM#')
//  4  list a user's orders, newest first PK=USER#id,
//                                        begins_with(SK,'ORDER#'), desc
//  5  get one order + its lines          PK=ORDER#id
//  6  list orders in a status            GSI1: PK=STATUS#pending (SPARSE)
//  7  list orders in a date range        GSI2: PK=USER#id,
//                                        SK between dates
//  8  get a product by sku               PK=PRODUCT#sku, SK=META
//  9  list order lines for a product     GSI3: PK=PRODUCT#sku
// 10  get order status history           PK=ORDER#id,
//                                        begins_with(SK,'EVENT#')
//
// Doing this AFTER creating the table is the source of most DynamoDB
// disappointment. Pattern 6 is where you discover you need a sparse
// index rather than a Scan.

// ==================================================================
// STEP 2-3: SINGLE-TABLE DESIGN with KEY OVERLOADING.
// ==================================================================
// One table, several entity types, generic key names:
//
//  PK              SK                      entityType   gsi1pk
//  USER#u-1234     META                    User
//  USER#u-1234     ORDER#2026-11-30#o-55   OrderSummary
//  CART#u-1234     META                    Cart
//  CART#u-1234     ITEM#SKU-001            CartItem
//  ORDER#o-55      META                    Order        STATUS#pending
//  ORDER#o-55      ITEM#SKU-001            OrderItem
//  ORDER#o-55      EVENT#2026-11-30T09:14Z OrderEvent
//  PRODUCT#SKU-001 META                    Product
//
// Patterns 1, 4, 5, 10 need NO INDEX AT ALL - the base table's
// key schema serves them. That is the win.

// Pattern 4 - a user's orders, newest first, from the base table:
const orders = await db.send(new QueryCommand({
  TableName: "Commerce",
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :p)",
  ExpressionAttributeValues: { ":pk": "USER#u-1234", ":p": "ORDER#" },
  ScanIndexForward: false,          // DESCENDING: newest first
  Limit: 20,
  ReturnConsumedCapacity: "INDEXES" // <- ALWAYS, while learning
}));
orders.ConsumedCapacity;
// { TableName:'Commerce', CapacityUnits:2.5 }
// Capacity is the BILLABLE UNIT and the honest comparison between
// designs. Measure in RCUs, not milliseconds.

// ==================================================================
// QUERY vs SCAN: the cost distinction that matters most.
// ==================================================================
// QUERY: requires a partition key, reads ONLY that partition. Cost is
// proportional to what it RETURNS.
// SCAN: reads EVERY ITEM IN THE TABLE, then filters. Cost is
// proportional to the TABLE.

const bad = await db.send(new ScanCommand({
  TableName: "Commerce",
  FilterExpression: "entityType = :t AND #st = :s",
  ExpressionAttributeNames: { "#st": "status" },
  ExpressionAttributeValues: { ":t": "Order", ":s": "pending" },
  ReturnConsumedCapacity: "TOTAL"
}));
bad.Items.length;            // 10
bad.ScannedCount;            // 200,000
bad.ConsumedCapacity;        // { CapacityUnits: 12,847 }
//
// A FilterExpression DOES NOT REDUCE COST. It is applied AFTER the
// read. You paid to read 200,000 items and then discarded 199,990.
// That one sentence prevents more DynamoDB bill surprises than any
// other in this course.

// ==================================================================
// THE SPARSE INDEX: the technique worth knowing.
// ==================================================================
// A GSI contains ONLY items that HAVE its key attributes. So set
// gsi1pk only on PENDING orders:
await db.send(new UpdateCommand({
  TableName: "Commerce",
  Key: { PK: "ORDER#o-55", SK: "META" },
  UpdateExpression: "SET #st = :s, gsi1pk = :g, gsi1sk = :t",
  ExpressionAttributeNames: { "#st": "status" },
  ExpressionAttributeValues: {
    ":s": "pending", ":g": "STATUS#pending", ":t": "2026-11-30T09:14:00Z" }
}));

// When the order ships, REMOVE the attribute and it LEAVES the index:
await db.send(new UpdateCommand({
  TableName: "Commerce",
  Key: { PK: "ORDER#o-55", SK: "META" },
  UpdateExpression: "SET #st = :s REMOVE gsi1pk, gsi1sk",
  ExpressionAttributeNames: { "#st": "status" },
  ExpressionAttributeValues: { ":s": "shipped" }
}));

const good = await db.send(new QueryCommand({
  TableName: "Commerce", IndexName: "GSI1",
  KeyConditionExpression: "gsi1pk = :g",
  ExpressionAttributeValues: { ":g": "STATUS#pending" },
  ReturnConsumedCapacity: "INDEXES"
}));
good.ConsumedCapacity;       // { CapacityUnits: 1.5 }
//
//   Scan + filter:     12,847 RCU,  1,400 ms
//   sparse GSI:             1.5 RCU,    8 ms
// The index holds 10 items, not 200,000, because the other 199,990
// do not have its key attribute. This is the single most useful
// DynamoDB modelling technique.

// ==================================================================
// GSI vs LSI. Use GSIs.
// ==================================================================
//   GSI                             LSI
//   own PK and SK                   shares the table's PK
//   add/remove ANY TIME             MUST be created WITH the table,
//                                   NEVER addable afterwards
//   own capacity                    shares the table's capacity
//   ALWAYS EVENTUALLY CONSISTENT    supports STRONGLY consistent
//   no collection size limit        IMPOSES A 10 GB ITEM COLLECTION
//                                   LIMIT ON THE WHOLE TABLE
//   20 per table                    5 per table
//
// Use GSIs. Treat an LSI as a special case: you genuinely need a
// strongly consistent alternative sort WITHIN a partition AND you
// are certain the collections stay small. Getting that wrong means
// recreating the table.

// PROJECTIONS: what the index holds.
//   KEYS_ONLY  smallest and cheapest; every read needs a second
//              fetch from the base table
//   INCLUDE    the keys plus named attributes <- usually right
//   ALL        everything; a full second copy of the data
//
//   --global-secondary-indexes '[{
//     "IndexName": "GSI1",
//     "KeySchema": [{"AttributeName":"gsi1pk","KeyType":"HASH"},
//                   {"AttributeName":"gsi1sk","KeyType":"RANGE"}],
//     "Projection": {"ProjectionType":"INCLUDE",
//                    "NonKeyAttributes":["status","total","userId"]}
//   }]'
// An index that does not COVER its query loses most of its value -
// so project what the query selects, and no more.

// WRITE AMPLIFICATION: every GSI an item matches is ALSO WRITTEN.
// One item + 3 matching GSIs = 4 writes billed. Measure it:
const w = await db.send(new PutCommand({
  TableName: "Commerce", Item: {...}, ReturnConsumedCapacity: "INDEXES"
}));
w.ConsumedCapacity;
// { CapacityUnits: 4,
//   Table: {CapacityUnits: 1},
//   GlobalSecondaryIndexes: {GSI1:{CapacityUnits:1}, GSI2:{...}, GSI3:{...}} }
// An index added "just in case" is a write cost on every matching item,
// forever. Sparse indexes limit the blast radius.

// ==================================================================
// PAGINATION. Cursor-based, and there is no alternative.
// ==================================================================
async function* pages(params) {
  let key;
  do {
    const r = await db.send(new QueryCommand({...params, ExclusiveStartKey: key}));
    yield r;
    key = r.LastEvaluatedKey;
  } while (key);
}
// THE TRAP: Limit applies BEFORE the filter. A Query with Limit 20
// and a FilterExpression can return 3 items AND a LastEvaluatedKey.
// Code that stops when it has "fewer than Limit" results is wrong -
// stop when LastEvaluatedKey is absent, never on the count.
// Pass LastEvaluatedKey to the client as an opaque cursor; there is
// no offset, and no page number.

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.