Tables, Keys, Items and the Local Emulator

Article · 7:00

DynamoDB Local, tables and items, partition and sort keys, the attribute type system, the limits that bound a design, and basic CRUD.

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

The primary key is the whole addressing scheme. A table has either a partition key alone (a simple key - every item's key value must be unique) or a partition key and a sort key (a composite key - the combination must be unique, and many items may share a partition key). That second form is what makes DynamoDB useful, because items sharing a partition key form an item collection, stored together and sorted by the sort key, and a single Query can return all or part of one.

The partition key determines physical placement. DynamoDB hashes it to choose a partition. Even distribution of traffic across partition key values is therefore a requirement, not an optimisation - and a partition key with a few hot values is the characteristic DynamoDB performance failure.

The sort key determines what a range query can do. Within one partition key you can query the sort key with =, <, >, between and - importantly - begins_with. That last one is why composite sort keys built from strings (ORDER#2026-11-30#001) are everywhere in DynamoDB schemas: a hierarchy encoded into a string gives you range queries over any prefix of it.

The limits bound every design and must be known in Module 1:

  • An item may not exceed 400 KB, attribute names included. There is no large-object option; big payloads go to S3 with a pointer in the item.
  • An item collection - all items sharing a partition key - is unlimited unless the table has a local secondary index, in which case it is capped at 10 GB. This is the single strongest argument against LSIs.
  • A Query or Scan returns at most 1 MB per call. Everything must paginate; code that does not is code that silently returns partial results.
  • A transaction may touch at most 100 items.
  • 20 global secondary indexes and 5 local secondary indexes per table.

Types. Scalars S, N, B, BOOL, NULL; documents M (map) and L (list); sets SS, NS, BS. Two things to note: N is a string-encoded decimal with 38 digits of precision, so it is exact and correct for money, and JavaScript's number cannot hold all of it - which is why the SDK offers a BigInt/wrapNumbers option. And an empty string is allowed as an attribute value but not as a key value, which is a specific and memorable gotcha.

Laboratory exercise 1 - provision and verify.

Run DynamoDB Local, and create a table in it with a composite key. Then create the same table in a real AWS account and confirm your code works against both by configuration alone - this matters, because every later laboratory develops locally and verifies in the cloud.

Load at least 200,000 items with BatchWriteItem, modelling the capstone's carts and orders. Record the item sizes you actually produced with a distribution, because Module 4 needs them.

Then demonstrate each limit, with evidence: build an item over 400 KB and capture the error; run a Query that returns more than 1 MB and show LastEvaluatedKey present with a partial result; attempt a transaction over 100 items; and attempt to write an item whose key attribute is an empty string.

Finally, demonstrate the item collection: a single Query returning a cart and its line items together.

Deliverable: an idempotent table creation script (CLI or CloudFormation), a loader, a README covering both local and cloud, the item size distribution, the four limit demonstrations with their actual errors, and the item collection query with its output.

JS Example 1 160 lines
// ------------------------------------------------------------------
// DynamoDB Local: free, offline, instant reset, full API.
// ------------------------------------------------------------------
//   docker run -d -p 8000:8000 amazon/dynamodb-local
//   aws dynamodb list-tables --endpoint-url http://localhost:8000
//
// What it does NOT give you: real latency, real throttling, adaptive
// capacity, Streams-to-Lambda, or a bill. Modules 4-6 need real AWS.

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, GetCommand,
         UpdateCommand, DeleteCommand, QueryCommand, ScanCommand,
         BatchWriteCommand, BatchGetCommand } from "@aws-sdk/lib-dynamodb";

const base = new DynamoDBClient(
  process.env.LOCAL
    ? { endpoint: "http://localhost:8000", region: "local",
        credentials: {accessKeyId: "x", secretAccessKey: "x"} }
    : { region: "eu-west-2" }
);
// One switch, local or cloud. Every lab develops locally and verifies
// in the cloud, so this must work by configuration alone.
const db = DynamoDBDocumentClient.from(base, {
  marshallOptions: { removeUndefinedValues: true }
});

// ------------------------------------------------------------------
// The key schema IS the addressing scheme.
// ------------------------------------------------------------------
//   aws dynamodb create-table --table-name Commerce \
//     --attribute-definitions AttributeName=PK,AttributeType=S \
//                             AttributeName=SK,AttributeType=S \
//     --key-schema AttributeName=PK,KeyType=HASH \
//                  AttributeName=SK,KeyType=RANGE \
//     --billing-mode PAY_PER_REQUEST \
//     --endpoint-url http://localhost:8000
//
//   PK (HASH)  = PARTITION key -> determines PHYSICAL PLACEMENT.
//                Even traffic distribution across its values is a
//                REQUIREMENT, not an optimisation.
//   SK (RANGE) = SORT key -> determines what a RANGE QUERY can do.
//
// Generic names PK and SK because several entity types share the
// table. This is single-table design and it looks wrong until it
// clicks (Module 2).

// ------------------------------------------------------------------
// An ITEM COLLECTION: items sharing a partition key, stored together
// and sorted by the sort key. ONE Query returns all of it.
// ------------------------------------------------------------------
await db.send(new BatchWriteCommand({ RequestItems: { Commerce: [
  { PutRequest: { Item: {
      PK: "CART#u-1234", SK: "META",
      entityType: "Cart", status: "active",
      // N is a STRING-ENCODED DECIMAL, 38 digits, EXACT. Correct for
      // money. JavaScript's number cannot hold all of it - hence the
      // SDK's wrapNumbers option when you need the full range.
      total: 149.97, itemCount: 2,
      updatedAt: "2026-11-30T09:14:00Z" }}},
  { PutRequest: { Item: {
      PK: "CART#u-1234", SK: "ITEM#SKU-001",
      entityType: "CartItem", sku: "SKU-001",
      name: "Mechanical keyboard", unitPrice: 89.99, quantity: 1 }}},
  { PutRequest: { Item: {
      PK: "CART#u-1234", SK: "ITEM#SKU-044",
      entityType: "CartItem", sku: "SKU-044",
      name: "USB cable", unitPrice: 29.99, quantity: 2 }}}
]}}));
// BatchWriteItem: 25 items per call, max. It does NOT support
// conditions or updates, and it can return UnprocessedItems - which
// you MUST retry with backoff, or you silently lose writes.

const cart = await db.send(new QueryCommand({
  TableName: "Commerce",
  KeyConditionExpression: "PK = :pk",
  ExpressionAttributeValues: { ":pk": "CART#u-1234" }
}));
// -> the cart META and both line items, in ONE request, sorted by SK.
// In SQL that is a join. Here it is the physical layout.

// begins_with on the sort key - just the line items:
const lines = await db.send(new QueryCommand({
  TableName: "Commerce",
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :prefix)",
  ExpressionAttributeValues: { ":pk": "CART#u-1234", ":prefix": "ITEM#" }
}));
// THIS is why composite sort keys built from strings are everywhere:
// a hierarchy encoded into a string gives range queries over any
// prefix of it. ORDER#2026-11-30#001 lets you query a day, a month,
// or a year with the same index.

// ------------------------------------------------------------------
// CRUD, with the expressions that matter.
// ------------------------------------------------------------------
await db.send(new UpdateCommand({
  TableName: "Commerce",
  Key: { PK: "CART#u-1234", SK: "ITEM#SKU-001" },
  UpdateExpression: "SET quantity = :q, updatedAt = :now",
  // A CONDITION makes this safe to call concurrently. Module 3.
  ConditionExpression: "attribute_exists(PK) AND quantity <> :q",
  ExpressionAttributeValues: { ":q": 3, ":now": new Date().toISOString() },
  ReturnValues: "ALL_NEW"
}));

// Reserved words are many (NAME, STATUS, SIZE, ORDER, TYPE, VALUE...)
// and the error is confusing. Alias them with # always:
await db.send(new UpdateCommand({
  TableName: "Commerce",
  Key: { PK: "CART#u-1234", SK: "META" },
  UpdateExpression: "SET #st = :s, #nm = :n",
  ExpressionAttributeNames: { "#st": "status", "#nm": "name" },
  ExpressionAttributeValues: { ":s": "checked_out", ":n": "Cart" }
}));

// ------------------------------------------------------------------
// THE LIMITS. Not trivia - they bound every design.
// ------------------------------------------------------------------
// 1. AN ITEM MAY NOT EXCEED 400 KB, attribute NAMES included.
try {
  await db.send(new PutCommand({ TableName: "Commerce", Item: {
    PK: "LIMIT#1", SK: "BIG", blob: "x".repeat(410000) }}));
} catch (e) {
  // ValidationException: Item size has exceeded the maximum allowed size
}
// There is no large-object option. Big payloads go to S3 with a
// pointer in the item.

// 2. AN ITEM COLLECTION IS UNLIMITED - UNLESS THE TABLE HAS AN LSI,
//    in which case it is capped at 10 GB. This is the single
//    strongest argument against LSIs (Module 2).

// 3. A Query or Scan returns AT MOST 1 MB per call.
let key, all = [];
do {
  const page = await db.send(new QueryCommand({
    TableName: "Commerce",
    KeyConditionExpression: "PK = :pk",
    ExpressionAttributeValues: { ":pk": "CART#u-1234" },
    ExclusiveStartKey: key
  }));
  all.push(...page.Items);
  key = page.LastEvaluatedKey;     // <- present means MORE REMAINS
} while (key);
// CODE THAT DOES NOT CHECK LastEvaluatedKey SILENTLY RETURNS PARTIAL
// RESULTS. No error, no warning, just missing rows - and it works
// fine until the data grows past 1 MB. Paginate from the first line.

// 4. A transaction may touch at most 100 items.
// 5. 20 GSIs and 5 LSIs per table.

// AND THE MEMORABLE GOTCHA: an empty string is a valid ATTRIBUTE
// value and NOT a valid KEY value:
try {
  await db.send(new PutCommand({ TableName: "Commerce",
    Item: { PK: "", SK: "META" }}));
} catch (e) {
  // ValidationException: One or more parameter values are not valid.
  // The AttributeValue for a key attribute cannot contain an empty
  // string value.
}

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.