Skip to content

Amazon DynamoDB in Practice

Intermediate 49 min read Part 15 of 18

DynamoDB in practice: partition/sort keys, GSIs and LSIs, single-table design, capacity modes, consistency, transactions, Streams, DAX, global tables, hot keys.

Summary#

Amazon DynamoDB is AWS's fully managed, serverless key-value and document database. You create a table, choose a partition key (and optionally a sort key), and start reading and writing. There are no servers to size, no clusters to patch, no replicas to configure and no failovers to rehearse. AWS hashes the partition key to place each item on one of many internal partitions. Each partition is replicated three ways across Availability Zones with Multi-Paxos, and it splits automatically as data or traffic grows. Within a partition, items with the same partition key are kept sorted by the sort key, so "all orders of customer 42, newest first" is one efficient Query.

DynamoDB gives you single-digit-millisecond latency at essentially any scale, provided every hot access pattern is a key lookup or a sorted range within one partition key. Everything else is a deliberate add-on:

  • Global and local secondary indexes for other access patterns.
  • Strongly consistent reads (per request, at double the read cost).
  • ACID transactions across up to 100 items.
  • DynamoDB Streams for change data capture.
  • DAX, an in-memory, write-through cache with microsecond reads.
  • Global tables for multi-region, multi-active replication.
  • TTL, for free expiry.

You pay per request (on-demand) or per provisioned capacity unit, plus storage. The pricing model is also the performance model: one write capacity unit is one 1 KB write per second, and one read capacity unit is one 4 KB strongly consistent read per second. Each physical partition tops out around 3,000 RCU and 1,000 WCU.

This page covers the data model, keys and indexes, single-table design, capacity modes and the arithmetic behind them, consistency and replication, transactions, Streams, DAX, global tables, hot partitions and limits, and when to choose DynamoDB over Cassandra, PostgreSQL or others. It's assembled from AWS documentation and the two DynamoDB papers.

Why It Exists#

In the early 2000s, Amazon's retail site ran on large relational databases. During peak holiday traffic, outages and scaling bottlenecks hit exactly when revenue was highest. Amazon's engineers observed that most of their services accessed data by primary key only: shopping carts, session state, product catalogue lookups, best-seller lists. They didn't need joins or complex queries, but they did need to stay always writable, even when servers, disks or whole data centres failed.

That led to Dynamo ("Dynamo: Amazon's Highly Available Key-value Store", DeCandia et al., SOSP 2007), an internal, leaderless key-value store built from consistent hashing, sloppy quorums, hinted handoff, vector clocks and Merkle-tree anti-entropy. Its ideas spread widely: Cassandra, Riak and Voldemort all borrowed from it (Quorums and Leaderless Replication).

Dynamo had a practical problem, though: each team had to run its own Dynamo cluster, and operating it was hard. Many teams chose the simpler managed SimpleDB instead, despite its limits.

DynamoDB (launched in 2012) combined the two lessons. It keeps Dynamo's scale and availability goals, but offers them as a fully managed service, with a simpler, more predictable model:

  • Leader-based replication per partition (Multi-Paxos) instead of leaderless sloppy quorums, so strongly consistent reads are possible and conflict resolution isn't pushed onto applications.
  • A central partition map and request routers instead of a peer-to-peer ring, so the service can split, move and rebalance partitions invisibly.
  • Predictable performance as the product. Single-digit-millisecond latency for any table size, enforced by capacity accounting and admission control.

The 2022 paper "Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service" (Elhemali et al., USENIX ATC 2022) describes this design. AWS has reported that, during Prime Day 2022, DynamoDB peaked at over 100 million requests per second for Amazon's own services, with single-digit-millisecond latency. The headline isn't raw speed. It's that latency stays flat as load rises by orders of magnitude.

The problems DynamoDB solves:

  1. Operational burden. No provisioning, patching, replication setup, backups (point-in-time recovery is a switch) or failover. A small team can run a table that serves millions of users.
  2. Elastic scale. Storage is effectively unbounded, and throughput scales by adding partitions behind the scenes.
  3. Predictable latency at any size, because every operation touches a bounded amount of data on a known partition.
  4. Serverless economics. On-demand mode costs nothing when idle, and it pairs naturally with Lambda, API Gateway and Step Functions.

How It Works#

Architecture#

DynamoDB is a regional service. A request goes through these layers:

  1. Request routers. A stateless fleet that authenticates each request (IAM), looks up which partition owns the key in the partition metadata service (heavily cached), and forwards the request to the right storage node. Routers also enforce throughput limits through global admission control: token buckets that track each table's consumption across the whole router fleet.
  2. Storage nodes. These hold partitions. Each partition is a replication group of three replicas in three different Availability Zones. One replica is the leader, elected by Multi-Paxos (Consensus). The leader serves all writes and strongly consistent reads.
  3. Write path. The leader writes a write-ahead log entry, sends it to its peers, and acknowledges the client once 2 of 3 replicas have persisted the log record. Each replica stores data in a B-tree keyed by partition and sort key, plus its replication log.
  4. Log replicas. When a storage replica fails, the group can quickly add a lightweight log replica, which stores only the recent write-ahead log. That keeps write quorums healthy while a full replica is rebuilt, which takes longer.
  5. Background services. These include:
    • partition splitting and moving;
    • continuous archival of the logs to S3, which powers point-in-time recovery and backups without touching foreground capacity;
    • index propagation to GSIs;
    • Streams;
    • TTL deletion.

Why leader-based Paxos instead of Dynamo's leaderless quorums? A single leader per partition orders all writes, so there are no conflicting versions to reconcile. That means no vector clocks or sibling values returned to clients. It also allows conditional writes and transactions, and makes strongly consistent reads simple: read from the leader. Leader leases ensure that a deposed leader can't serve stale strong reads. The availability cost is small. A partition is unavailable for writes only between the leader failing and a new one being elected, typically a few seconds, and only for that partition.

Data model: tables, items, attributes#

  • A table is a collection of items with a mandatory primary key. Apart from the key attributes (and any index keys), DynamoDB is schemaless. Items in one table can have completely different attributes, and adding an attribute requires no migration. The flip side is that the application must validate the shape of its data, because the database won't.
  • An item is a record: a set of attributes, at most 400 KB in total (attribute names count towards the size).
  • Attributes are typed:
    • scalars: String, Number (up to 38 digits of precision), Binary, Boolean and Null;
    • documents: List and Map, nestable up to 32 levels;
    • sets: String Set, Number Set and Binary Set.

Over the wire, the API uses JSON with type descriptors ({"S": "Smith"}, {"N": "101"}). Storage uses an internal format.

A small Users table shows the schemaless shape. Every item has PersonID, but only some have Address, and only one has FavoriteColor:

PersonID (PK)LastNameFirstNameOther attributes
101SmithFredPhone = "555-4321"
102JonesMaryAddress = {Street, City: "Anytown", State: "OH", ZIP}
103StephensHowardAddress = {Street, City: "London", PostalCode}, FavoriteColor = "Blue"

Because you're billed by item size (reads in 4 KB units, writes in 1 KB units), and reads always load the whole item from storage, item size is a design variable:

  • ProjectionExpression trims the response, but you still pay for reading the full item.
  • Keep large, rarely needed attributes, such as a business's 2,000 reviews, out of the hot item. Put them in separate items or tables, or in S3 with a pointer.

In a Yelp-like design, the Business item holds name, address and rating, and reviews are their own items under the business's partition key. Reading the business card then costs 1 RCU instead of dozens.

Partition key and sort key#

The primary key is either:

  • Simple: a partition key only. For example, user_id in a Users table, where each item is addressed by one value.
  • Composite: a partition key plus a sort key. For example, in a chat app, chat_id (partition) plus message_id (sort). All items sharing a partition key form an item collection, stored together and ordered by the sort key.

How the two keys are used:

  • Partition key to partition. DynamoDB hashes the partition key value. The hash space is divided into contiguous ranges, each owned by one partition, and the metadata service maps ranges to replication groups. This works like consistent hashing in spirit, but placement is decided centrally rather than by a peer-to-peer ring, so AWS can split a range, or move a partition to a less-loaded node, without clients noticing.
  • Sort key within a partition. Items are kept in a B-tree ordered by (partition key, sort key). A Query with chat_id = X AND message_id BETWEEN a AND b hashes once to find the partition, then does one B-tree seek plus a sequential read. The cost is proportional to the data returned, not to the table size.

Choosing the sort key: why not just a timestamp? Two messages can share a millisecond, and items with the same primary key overwrite each other. Use an ID that's both unique and time-ordered, so the sort order is chronological, and there are no collisions:

  • Snowflake-style IDs;
  • ULIDs;
  • UUIDv7. Its timestamp comes first, so it sorts correctly as a string. UUIDv1 also contains a timestamp, but its layout doesn't sort, and it exposes the host's MAC address.
  • per-partition counters.

(Unique ID Generation). Another option is a composite sort key like 2026-12-02T10:15:00.123Z#<random>.

Sort key conventions make one key serve several query shapes:

  • Hierarchical prefixes: SK = "COUNTRY#US#STATE#WA#CITY#Seattle". begins_with(SK, "COUNTRY#US#STATE#WA") returns all of Washington.
  • Typed prefixes: SK = "ORDER#2026-11-30#o-9182" and SK = "PROFILE" in the same item collection. begins_with(SK, "ORDER#") returns orders only.
  • Zero-padded numbers: sort keys compare lexicographically if they're strings. Pad numbers inside strings (RANK#0007), or use a Number-type sort key.
  • Reverse order: ScanIndexForward = false reads newest-first, so there's no need to store inverted timestamps.

Reading data: GetItem, Query, Scan#

  • GetItem fetches one item by full primary key. BatchGetItem fetches up to 100 items (16 MB), in parallel across partitions.
  • Query reads a single item collection, one partition key value, with an optional key condition on the sort key: =, <, <=, >, >=, BETWEEN or begins_with. Results come back in sort order, at most 1 MB per page. The response's LastEvaluatedKey is passed back as ExclusiveStartKey to get the next page, which is natural cursor pagination (API Design).
  • Scan reads every item in a table or index, 1 MB per page. Parallel scan (Segment, TotalSegments) splits the work across workers. Scans are for exports, migrations and small tables, never for user-facing hot paths. A 1 TB table scanned at eventual consistency consumes ~1.3 × 10⁸ read units.
  • FilterExpression is applied after items are read. You're charged for everything read, not for what's returned. A Query that reads 1 MB, and filters down to 3 items, costs 1 MB of reads. Filters reduce network transfer, not cost. If you filter heavily on an attribute, model it into a key or an index.
  • Writes: PutItem (create or replace), UpdateItem (modify attributes in place: SET, REMOVE, ADD for atomic counters and sets, DELETE from sets), DeleteItem, and BatchWriteItem (up to 25 puts or deletes, not atomic).
  • ConditionExpression makes any write conditional, checked atomically at the partition leader: attribute_not_exists(PK) (create only if absent), version = :expected (optimistic locking), balance >= :amount. This is DynamoDB's most important correctness tool. Conditions run within the item's partition leader, so they're linearizable for that item.
  • PartiQL offers SQL-compatible SELECT, INSERT, UPDATE and DELETE syntax over the same operations. A SELECT without a key condition silently becomes a Scan, so it's a convenience, not a query planner.

SQL SELECT * FROM users WHERE user_id = 101 corresponds to a Query (or GetItem) with KeyConditionExpression: "user_id = :id". SQL SELECT * FROM users corresponds to a Scan. There's no equivalent of WHERE last_name = 'Smith' that doesn't scan, unless you add an index on last_name.

Secondary indexes: GSIs and LSIs#

Your table's primary key supports one access pattern well. Secondary indexes give you more.

Global secondary index (GSI). An index with a different partition key, and optionally a different sort key.

  • It's physically a separate table, with its own partitions and replicas. DynamoDB maintains it asynchronously from the base table's change log.
  • Reads from a GSI are eventually consistent only. Typical propagation is well under a second, but it isn't bounded.
  • GSI keys need not be unique. Many base items can share the same GSI partition and sort key.
  • A GSI has its own capacity. In provisioned mode, if a GSI can't keep up with writes, the base table's writes are throttled (back-pressure), so under-provisioned GSIs are a classic outage cause.
  • You can add or delete GSIs at any time. Adding one backfills from existing data.
  • There's a default quota of 20 GSIs per table.

Local secondary index (LSI). The same partition key, with a different sort key.

  • It's stored alongside the base items in the same partition, and updated synchronously with each write, so it supports strongly consistent reads.
  • An LSI shares the base table's capacity.
  • LSIs must be defined at table creation, and can't be added or dropped later.
  • At most 5 per table.
  • They impose a hard 10 GB limit per item collection: the base items plus all their LSI entries for one partition key value. They also stop DynamoDB from splitting a single item collection across partitions.

Because of these restrictions, most designs use GSIs, and add an LSI only for a strongly consistent alternate sort order within a small partition.

AspectGlobal secondary index (GSI)Local secondary index (LSI)
KeysAny partition key and optional sort keySame partition key, different sort key
Physical storageSeparate partitions and replicasCo-located in the base partition
ConsistencyEventually consistent reads onlyEventual or strong
CapacityIts own RCU/WCU (on-demand: billed separately)Shares the base table's
When createdAny time; backfilledOnly at table creation
Size limitNone per key10 GB per partition-key value (item collection)
Max per table20 (default quota)5
Typical useLook up users by email; all messages by author across chatsWithin a customer's orders, sort by total instead of date

Chat example. The base table has PK = chat_id, SK = message_id, which serves "messages in this chat". The other two access patterns are served by indexes:

  • "All messages a user sent, across chats": a GSI with PK = sender_id, SK = message_id.
  • "Messages in this chat with the most attachments": an LSI with PK = chat_id, SK = num_attachments. That had to be planned at table creation, which is a real constraint.

Projections decide which attributes are copied into the index:

  • KEYS_ONLY: the smallest and cheapest; you fetch the rest from the base table.
  • INCLUDE: chosen attributes.
  • ALL: every attribute, so no second read is needed, but every base write is copied.

Every write that changes an indexed attribute costs index writes too. An update that changes a GSI key costs a delete and a put in that GSI. A table with 5 ALL-projected GSIs can cost about 6× the write capacity of the base table alone.

Sparse indexes. An item appears in a GSI only if it has the GSI key attributes. Example: set GSI1PK = "OPEN" only on open support tickets, and remove it when the ticket closes. The index then contains only open tickets: tiny, cheap, and a perfect work queue for "list open tickets". This is one of the most useful DynamoDB idioms.

Index overloading. Use generic attribute names (GSI1PK, GSI1SK) whose meaning depends on the item type. User items put email there, order items put status#date, and so on, so one GSI serves several access patterns. This keeps the GSI count low, and is a core technique of single-table design.

Under the hood:

  • A GSI is maintained from the base table's replication log. After a base write commits, an asynchronous process computes the index delta (old key removed, new key inserted) and applies it to the GSI's own partitions.
  • An LSI is a second B-tree inside the same partition, updated in the same local write as the base item.

That's why one is eventually consistent, and the other is strongly consistent and size-limited.

Single-table design#

In a relational database, you normalise: one table per entity, joined at query time. DynamoDB has no joins, and each request reaches one table. So for a set of related entities that are read together, the idiomatic approach is often single-table design: store multiple entity types in one table, with keys chosen so that one Query returns an entity and its related items in one round trip. The idea was popularised by Rick Houlihan's AWS re:Invent talks and Alex DeBrie's The DynamoDB Book (2020).

The method:

  1. List every access pattern with its parameters and frequency, before designing anything. For example:
    • get customer profile;
    • list a customer's orders, newest first;
    • get an order with its line items;
    • find a customer by email;
    • list open orders by warehouse.
  2. Draw the entity-relationship model to understand the data (Data Modeling), then design keys for the access patterns, not for the entities.
  3. Use generic key names (PK, SK, GSI1PK, GSI1SK) and typed, prefixed values (CUSTOMER#c1, ORDER#2026-11-30#o9), so different item types share key attributes.
  4. Pre-join with item collections. Put a parent and its children under the same partition key, so Query PK = CUSTOMER#c1 returns the profile plus orders, sorted by SK.
  5. Use GSIs (overloaded and sparse) for the remaining patterns, including inverted indexes (a GSI with PK and SK swapped) for many-to-many relationships.
  6. Handle one-to-many relationships by:
    • denormalising into a map or list when the child set is small and bounded;
    • item collections when it's large;
    • duplicating attributes when they're immutable.
  7. Write it down as a table of access pattern to (index, key condition), and review it before writing code.

The resulting item layout, all in one table:

PKSKTypeOther attributesGSI1PK / GSI1SK
CUSTOMER#c1PROFILECustomername, emailEMAIL#ann@x.com / CUSTOMER#c1
CUSTOMER#c1ORDER#2026-11-28#o7Ordertotal, statusORDER#o7 / ORDER#o7
CUSTOMER#c1ORDER#2026-11-30#o9Ordertotal, statusORDER#o9 / ORDER#o9
ORDER#o9ITEM#p55OrderItemqty 2, priceORDER#o9 / ITEM#p55
ORDER#o9ITEM#p81OrderItemqty 1, priceORDER#o9 / ITEM#p81

Access patterns, each served by one request:

Access patternRequest
Customer profile plus 10 newest ordersQuery PK = CUSTOMER#c1, ScanIndexForward = false, Limit = 11: "PROFILE" sorts after "ORDER#..." so, read backwards, it comes first, followed by the newest orders
One customer's orders in NovemberQuery PK = CUSTOMER#c1 AND begins_with(SK, "ORDER#2026-11")
Order with line itemsQuery GSI1 PK = ORDER#o9: the order item and its line items share the GSI1 partition
Find customer by emailQuery GSI1 PK = EMAIL#ann@x.com
Open orders for a warehouseQuery GSI2 PK = WH#w3#OPEN: sparse, removed when shipped

Why bother? Fewer round trips: one Query instead of N requests. One table to provision, monitor, back up and stream. And co-located items are reachable in one partition read.

When not to use single-table design:

  • Your access patterns are still changing quickly; re-keying a single table is painful.
  • Entities are unrelated, and never read together.
  • You need per-entity Streams, backups or capacity controls.
  • You serve a GraphQL API whose resolvers fetch one entity type at a time anyway.
  • You want analysts to export and understand the data easily.

DeBrie himself has noted that single-table design is a tool for specific performance needs, not dogma. Many teams use a few well-designed tables, with item collections where they matter.

Capacity modes and the arithmetic of throughput#

All throughput is measured in capacity units:

OperationUnit cost
Write, standard1 WCU per 1 KB of item size, rounded up. A 3.2 KB item costs 4 WCU.
Write, transactional2 WCU per 1 KB
Read, strongly consistent1 RCU per 4 KB, rounded up
Read, eventually consistent0.5 RCU per 4 KB
Read, transactional2 RCU per 4 KB
QuerySum of item sizes read (not per item), rounded up to 4 KB: a Query returning 100 items of 200 B (~20 KB) costs 5 RCU strong or 2.5 eventual
GSI writeAdditional WCU for each GSI whose projected item changes

Provisioned mode. You declare RCU and WCU per table and per GSI. You pay per capacity-unit-hour whether you use it or not. Order of magnitude in us-east-1: about $0.00065 per WCU-hour and $0.00013 per RCU-hour; check current pricing.

  • Auto scaling (target tracking, for example 70% utilisation) adjusts provisioned capacity within minutes. It can't absorb sudden spikes: scaling reacts to CloudWatch metrics with a lag of a few minutes.
  • Burst capacity: DynamoDB retains up to about 5 minutes (300 seconds) of unused capacity per partition, to absorb short bursts.
  • Reserved capacity (1- or 3-year commitments) cuts the price further for steady baselines.
  • Best for predictable, steady traffic with high utilisation.

On-demand mode. You pay per request (read and write request units), with no capacity planning.

  • A table instantly accommodates up to double its previous peak traffic. Beyond that, it scales by adding partitions, which takes time, and a sudden 10× jump can still throttle.
  • A newly created on-demand table starts with capacity for a few thousand writes per second, and grows from there. The warm throughput feature (2024) lets you pre-warm a table before a known launch.
  • Per-request prices dropped about 50% in November 2024. At steady, fully utilised load, on-demand is still several times more expensive per request than well-utilised provisioned capacity. But for spiky or unpredictable traffic, or for tables idle most of the time, it's often cheaper overall, and always simpler.
  • Best for new workloads, spiky traffic, development tables and serverless apps.
  • Switching between modes is allowed, but only a limited number of times per day.

Per-partition limits. Each partition supports at most 3,000 RCU and 1,000 WCU, or about 12 MB/s of strong reads and 1 MB/s of writes, and holds about 10 GB. When a partition exceeds either limit sustainably, DynamoDB splits it: by key range for size, and by observed load for heat. A table's capacity is spread across its partitions, which is why key distribution matters as much as total capacity.

Worked example: counting views. A video platform records 10 million views per second, each a small write (rounded up to 1 WCU).

  • Naive: 10M WCU means at least 10,000 partitions' worth of write throughput. Provisioned at about $0.00065 per WCU-hour, that's 10M × 0.00065 × 24 ≈ $156,000 per day in write capacity alone, before storage and indexes. On-demand costs more.
  • Better: aggregate in a stream processor first (Batch and Stream Processing). Kafka plus Flink can sum views per video per 10 seconds, and write one item update per active video per window. With 2 million active videos, that's 200,000 writes/s. With top-N plus approximate counters for the long tail, it's far less. The cost drops by over an order of magnitude.
  • Lesson: DynamoDB's pricing makes write amplification visible. Multiply every design's writes/s by item size in KB, by (1 + number of affected GSIs), and by 2 if transactional, before committing to it.

Worked example: a session store. 50,000 logins/s at peak, sessions of 1.5 KB, written once (2 WCU each) and read about 20 times (1 RCU eventual per 2 reads, 0.5 RCU each).

  • Writes need 100,000 WCU. Reads, at 1M reads/s, need 500,000 RCU.
  • At ≤1,000 WCU and ≤3,000 RCU per partition, that's at least about 170 partitions of throughput.
  • Partitioning by a random session ID spreads load perfectly.
  • TTL expires sessions for free.
  • A DAX cluster, or a client-side cache, could absorb most of the reads.

Consistency options and replication#

Reads choose their consistency per request, using ConsistentRead = true or false. There's no table-level setting:

  • Eventually consistent (the default). Any of the 3 replicas may serve the read, so it may miss a write acknowledged a moment ago, typically by milliseconds. It costs half as much, and has slightly lower latency.
  • Strongly consistent. Routed to the partition leader, which has every acknowledged write, so it returns the latest committed value. It costs 1 RCU per 4 KB, may have higher latency, and isn't available on GSIs, or across regions in global tables (except with the multi-region strong consistency mode; see global tables).
  • Transactional reads (TransactGetItems): serializable snapshots across up to 100 items.

Writes are always durable on 2 of 3 replicas before they're acknowledged, and they're ordered per item by the leader. Conditional writes and atomic counters are therefore linearizable per item.

So in CAP and PACELC terms, DynamoDB isn't simply "an AP database", as candidates often claim. Within a region, a partition is CP for writes and strong reads: a minority replica can't accept writes. The defaults (eventual reads, GSIs, global tables with last-writer-wins) give it AP-like behaviour where you choose them. Pick per access pattern. A booking flow uses strong reads, conditional writes and transactions. A product page uses eventual reads plus DAX.

Transactions#

Since 2018, DynamoDB supports ACID transactions:

  • TransactWriteItems: up to 100 actions (Put, Update, Delete, ConditionCheck) on items in one or more tables, in the same account and region, up to 4 MB in total. Either all succeed, or none do.
  • TransactGetItems: up to 100 Gets, returning a consistent snapshot.
  • Isolation: serializable with respect to other transactions and single-item writes.
  • Cost: 2× the normal capacity, because of the prepare and commit phases.
  • Idempotency: ClientRequestToken makes a retried transaction idempotent for 10 minutes. A retry after a timeout won't apply twice.
  • Failure: a transaction fails with TransactionCanceledException if any condition fails, or if it conflicts with a concurrent transaction on the same items. The response lists per-item reasons. Retry conflicts with backoff.

How they work. The paper "Distributed Transactions at Scale in Amazon DynamoDB" (Idziorek et al., USENIX ATC 2023) describes the design.

  • A fleet of transaction coordinators runs a two-phase protocol over the items' partition leaders: prepare checks conditions and records the pending transaction on each item, then commit applies the writes (Distributed Transactions).
  • Transactions are ordered using timestamps, not locks held across round trips, so non-transactional reads and writes keep their usual latency.
  • Coordinator state is durably logged, so a recovery process can finish or cancel a transaction whose coordinator dies.

The design goal was "transactions without hurting the non-transactional path". That's why the scope is capped at 100 items, one region, and no interactive (multi-round-trip) transactions. You can't read, compute in the application, and write inside one transaction. You express preconditions as ConditionChecks instead.

When to use which tool:

NeedTool
Create only if absent; optimistic locking on one itemConditional PutItem or UpdateItem (1× cost)
Increment a counterUpdateItem ADD (atomic per item)
Move money between two accounts; reserve a seat and create a booking; maintain a uniqueness constraint (claim EMAIL#x item and create user)TransactWriteItems with conditions
Read several items consistently, e.g. an order and its paymentTransactGetItems
Saga across services or regionsStep Functions or a workflow engine (Multi-Step Processes)

Uniqueness constraints illustrate the pattern well. DynamoDB has no unique index, so to enforce unique emails, write two items in one transaction:

  • the user (PK = USER#u1);
  • a marker (PK = EMAIL#ann@x.com).

Both carry the condition attribute_not_exists(PK). A second signup with the same email fails the marker's condition, so the whole transaction is cancelled.

Worked example: the dating-app "match" race. This comes from the swipe-consistency deep dive in the Dating App case study. Alice and Bob swipe right on each other at the same moment. A naive design:

  1. Alice's request checks whether Bob liked Alice (no).
  2. Bob's request checks whether Alice liked Bob (no).
  3. Alice's like is saved.
  4. Bob's like is saved.

Both requests checked before either saved, so neither notices the match. The fix is to make "record my swipe and see the other's" atomic, and to put both swipes in one place so this needs no distributed transaction:

  • Key both directions together. PK = PAIR#<smaller_id>#<larger_id>. Sorting the IDs means Alice→Bob and Bob→Alice compute the same key.
  • Use one item per pair, with attributes likes_from_<id>. Each swipe is a single UpdateItem SET likes_from_alice = :t with ReturnValues = ALL_NEW. Updates to one item are serialized by its partition leader, so whichever swipe is applied second is guaranteed to see the first in its returned item. It then declares the match.
  • Exactly one notification: a follow-up conditional update SET matched_at = :now with ConditionExpression: attribute_not_exists(matched_at). If both requests race, only one condition succeeds, and that one sends the push.

This is the DynamoDB analogue of the "same partition, single-partition atomicity" trick in Cassandra (where an LWT on one partition plays the role of the item update). It needs no transaction at all, just an access-pattern-aware key.

Two trade-offs to raise:

  • Pair items accumulate, at about 2 billion swipes per day for 20 million daily users making 100 swipes each. Use TTL or archive old non-matches.
  • An alternative is to accept eventual consistency, and run a reconciliation job that finds unmatched mutual likes and notifies both users later. That's simpler, but the notification is late.

DynamoDB Streams and change data capture#

DynamoDB Streams is a time-ordered log of item-level changes. Every insert, update and delete, including TTL deletions, appears exactly once, in order per item, retained for 24 hours.

  • View types: KEYS_ONLY, NEW_IMAGE, OLD_IMAGE or NEW_AND_OLD_IMAGES.

  • Shards: a stream is split into shards that follow the table's partitions. Shards split as partitions split, and consumers process parent shards before children, to keep per-item order.

  • Consumers:

    • AWS Lambda event source mappings, which manage polling, checkpointing, batching, retries, bisect-on-error and failure destinations;
    • the Kinesis Client Library, via an adapter.

    AWS recommends at most about two concurrent readers per shard. For wider fan-out, use one Lambda that republishes to SNS, EventBridge or Kinesis.

  • Kinesis Data Streams for DynamoDB is an alternative destination, with longer retention (up to a year), more consumers, and Firehose integration. Records may be duplicated or out of order, so consumers must deduplicate, for example by sequence or by the approximate creation timestamp.

Typical uses (Change Data Capture):

  1. Search index sync. Lambda reads each change and upserts or deletes the document in Elasticsearch or OpenSearch. AWS also offers zero-ETL integrations into OpenSearch and Redshift that do this without custom code. The search index is then eventually consistent with the table, and rebuildable from an export plus the stream.
  2. Materialised aggregates. Maintain counters or leaderboards in another item or table as orders arrive.
  3. Event-driven workflows. "Order created" triggers payment, email and analytics (Event-Driven Architecture). This is the transactional-outbox pattern for free, because the event is emitted only if the write committed.
  4. Cache invalidation. Delete or refresh Redis entries when items change.
  5. Analytics. Kinesis Data Streams to Firehose to S3 or Redshift. Firehose can't read DynamoDB Streams directly, so it needs Kinesis Data Streams, or a Lambda, in between.
  6. Cross-account or cross-region replication, and auditing via old/new images.

Watch out for two things. Stream processing must be idempotent, because Lambda retries batches. And a failing record blocks its shard: use bisect-on-error, maximum retry attempts and an on-failure destination (DLQ) so one bad record can't stall the pipeline for 24 hours and lose data on expiry.

DAX: DynamoDB Accelerator#

DAX is a managed, in-memory cache cluster that sits in your VPC and speaks the DynamoDB API. You swap the SDK client for the DAX client. The API is compatible, but the swap isn't transparent: you need the DAX client library, available for Java, .NET, Node.js, Python and Go, and network access to the cluster.

  • Latency: cache hits return in microseconds (on the order of hundreds of µs, including the network), against single-digit milliseconds from DynamoDB.
  • Item cache: caches GetItem and BatchGetItem results by primary key. Write-through: writes sent through DAX go to DynamoDB first, then update the item cache.
  • Query cache: caches Query and Scan results by their exact parameters. These entries are not invalidated by writes. They expire only by TTL (5 minutes by default) or eviction. So a query result can stay stale even after a write through DAX.
  • Bypassing DAX: writes made directly to DynamoDB (another service, a Lambda or a Streams consumer) don't update DAX at all. Cached items stay stale until their TTL expires.
  • Strongly consistent reads pass straight through to DynamoDB, and aren't cached. Transactional calls pass through as well.
  • Cluster: up to 11 nodes (one primary plus read replicas), across AZs. The primary handles writes, and reads are load-balanced.

When DAX fits: read-heavy, eventually consistent workloads where the same items are read repeatedly. For example, product catalogue pages during a sale, or a celebrity profile read millions of times. In these cases DAX absorbs hot-key reads that would otherwise hit one partition's 3,000-RCU limit. It also turns a Prime-Day-style read spike into cache hits.

When it doesn't: write-heavy workloads, mostly unique keys, strongly consistent reads, or when you already run Redis for richer structures such as sorted sets, rate limiters and pub/sub (Caching Strategies, Redis). In an interview, saying "DAX in front of DynamoDB for the hot read path" avoids adding a separate cache tier and its invalidation code. Be ready to explain the staleness rules above.

Global tables#

Global tables replicate a table to multiple AWS regions as multi-active replicas. Every region accepts reads and writes locally, with single-digit-millisecond latency, and changes propagate asynchronously to the other regions, typically within about a second.

  • Conflict resolution: concurrent writes to the same item in different regions are resolved with last writer wins, based on timestamps. The losing write silently disappears. There's no merge, and no conflict callback.
  • Consistency: with the default (multi-region eventual consistency) mode, a strongly consistent read is only "strong" in the region where the write happened. Transactions are atomic only in the region that ran them. Other regions see the individual item changes as they replicate, and may briefly observe part of a transaction.
  • Multi-region strong consistency (MRSC): a newer mode, announced by AWS at re:Invent 2024. Writes are synchronously replicated across a set of regions, so strongly consistent reads in any of those regions see the latest write. Writes are slower, because they wait for cross-region acknowledgement, and the mode has configuration constraints. Check the current documentation before relying on it.
  • Operations: you add a region with a few clicks. Throughput settings, TTL and streams are managed per replica. You pay for replicated write units in each region, plus cross-region data transfer.

Design patterns (Multi-Region Data):

  • Home region per user. Route each user's writes to one region (by geo or user setting) to avoid LWW conflicts. Every region can still read, and serve as failover.
  • Commutative updates. Model counters as per-region items that are summed on read, so concurrent increments don't overwrite each other.
  • Idempotent, versioned writes, so replays after failover are harmless.
  • Disaster recovery: global tables give an RPO of about seconds (whatever hasn't replicated yet) and an RTO of about the time to shift traffic. That's the "multi-site active-active" strategy in Disaster Recovery.

TTL, backups and security#

Time to live (TTL). Designate a Number attribute (for example expires_at) holding an epoch-seconds timestamp. After that time, DynamoDB deletes the item in the background.

  • Cost: TTL deletes consume no write capacity.
  • Timing: they typically happen within a few days of expiry, not instantly. Reads should filter out expires_at < now, if expired items must never be visible.
  • Events: TTL deletes appear in Streams marked as system deletions, so a consumer can archive expired items to S3.
  • Uses: sessions, idempotency keys, rate-limit windows, temporary reservations (for example, a 10-minute ticket hold), and old swipe or notification records.

Backups:

  • Point-in-time recovery (PITR): continuous backups, with restore to any second in the last 35 days, into a new table.
  • On-demand backups: full snapshots kept until deleted.
  • Export to S3: a full or incremental export, from the PITR data without consuming table capacity, for analytics in Athena, Glue or Spark.
  • Import from S3: creates a new table from CSV, JSON or Ion files.

All of these come from DynamoDB's continuously archived logs and snapshots, so they don't affect live traffic.

Security:

  • Encryption at rest is always on: AWS-owned, AWS-managed or customer-managed KMS keys.
  • TLS is required for every API call.
  • IAM policies control access per table, per index, and even per item or attribute. For example, the dynamodb:LeadingKeys condition restricts a user to items whose partition key equals their user ID, which suits multi-tenant apps where each tenant's data shares a table.
  • VPC gateway endpoints keep traffic off the public internet.
  • CloudTrail logs control-plane and (optionally) data-plane calls.

In an interview, "encrypted at rest by default, TLS in transit, IAM least privilege, VPC endpoint" is usually enough (Security Fundamentals).

Hot partitions and limits#

DynamoDB scales tables. It can't make a single key faster than one partition. A hot partition happens when a disproportionate share of traffic targets one partition key, or a few adjacent ones. Typical examples:

  • a celebrity's profile;
  • a viral post's like counter;
  • "today's date" used as the partition key of an event log;
  • status used as a GSI partition key.

Sequential IDs as partition keys are not a problem, because hashing scatters them. The real culprits are low-cardinality, time-based or skewed-popularity keys. Requests over a partition's limit get ProvisionedThroughputExceededException (or ThrottlingException in on-demand mode), even if the table as a whole has spare capacity.

DynamoDB has two automatic defences:

  • Adaptive capacity. In provisioned mode, a table's capacity is shared across its partitions. If one partition needs more than an even share, DynamoDB instantly lets it borrow unused capacity from the table's total, up to the partition's hard maximum.
    • Example: a table provisioned at 4,000 WCU has 8 partitions. An even split would allow each one 500 WCU. With adaptive capacity, one hot partition can use up to 1,000 WCU while the others are quiet.
    • Early DynamoDB had no such borrowing. Over-provisioning then created many partitions, which diluted each one's share. That old "throughput dilution" folklore is why the per-partition figures still matter.
  • Split for heat. A partition that's persistently hot is split into two, by key range, so each half gets its own 3,000/1,000 limits. DynamoDB can even split a single item collection by sort key. Splitting has three limits:
    • It can't split one item.
    • It doesn't help when hot traffic always targets the newest end of an ever-increasing sort key.
    • It isn't available when the table has an LSI.

So a single item is capped at roughly 1,000 writes/s and 3,000 strong reads/s (6,000 eventual).

When the data itself is hot, design around it (Scaling Writes, Scaling Reads):

  1. Write sharding. Append a suffix to the partition key: LIKES#post9#0 … LIKES#post9#19. Writers pick a random shard (or hash(user) mod 20), and readers sum all 20 with parallel GetItems or a BatchGetItem. Twenty shards give up to about 20,000 increments per second for one post. Choose the shard count from the peak rate ÷ 1,000.
  2. Aggregate before writing. Buffer increments in memory, Kinesis or Kafka, and write a summed delta once per second.
  3. Cache hot reads. DAX or Redis for items read thousands of times per second. A CDN for public, cacheable responses.
  4. Avoid time as the partition key. For time-ordered events, use PK = device_id, SK = timestamp (spread across devices). If you must index by day, use a GSI with PK = date#shard, where shard runs 0..N-1, and query the N shards in parallel.
  5. Spread GSIs too. A GSI with PK = status (only "OPEN", "CLOSED") is a hot partition waiting to happen, and its throttling back-pressures the base table. Add a shard suffix, or make it sparse and high-cardinality.

Limits to know:

LimitValueDesign consequence
Item size400 KB, names includedLarge blobs go in S3 with a pointer; split big items
Partition throughput3,000 RCU and 1,000 WCUSpread keys; shard hot items; cache reads
Partition size~10 GB, then splitsInvisible, except for LSI tables (10 GB item-collection cap)
Query / Scan page1 MB per callPaginate with LastEvaluatedKey
BatchGetItem / BatchWriteItem100 items / 16 MB; 25 items / 16 MBRetry UnprocessedItems with backoff
Transaction100 items, 4 MB, single regionLarger workflows become sagas
GSIs / LSIs20 (default quota) / 5Overload GSIs; plan LSIs at creation
Streams retention24 hoursConsumers must not fall behind; use Kinesis for longer
PITR window35 daysUse exports for longer-term archives
LatencySingle-digit ms p99 for GetItem/PutItem in-region; DAX hits in µsPlan about 5–10 ms per call in latency budgets

Worked example: sales rank by category#

This classic problem appears in the "design Amazon's sales rank by category" exercise:

  • 10 million products and 1,000 categories;
  • 1 billion purchases per month (about 400/s on average);
  • 100 billion reads per month (about 40,000/s on average, more at peak);
  • results refreshed hourly, from a rolling week of sales.

Data flow:

  1. Ingest: sales events of about 40 bytes each go to S3 (about 40 GB per month) and/or a stream.
  2. Compute: an hourly batch job (Spark on EMR, or Glue) runs two steps over the last 7 days. First it maps each sale to (category, product) → quantity and reduces by summing. Then it sorts by (category, total), which is the multi-step MapReduce of the original exercise (Data Pipelines and Analytics). A product in several categories is emitted once per category.
  3. Publish into DynamoDB: one table SalesRank, with PK = CAT#<category>#<version> and SK = RANK#0001 … RANK#0100, holding product_id, units sold, and denormalised title and price. Each hourly run writes a new version: 1,000 categories × 100 ranks = 100,000 items, about 100,000 WCU-seconds, which takes seconds. A tiny pointer item, PK = CAT#<category>, SK = CURRENT, is then flipped to the new version, so readers never see a half-written ranking. Old versions expire via TTL.
  4. Serve: GET /popular?category_id=1234 reads the pointer, then Query PK = CAT#1234#v2026120214, Limit 20. At 40,000 reads/s, spread over 1,000 categories, hot categories (electronics during a sale) can exceed a partition's 3,000 RCU. Put DAX or a CDN in front (the rankings change hourly, so a 60-second cache is invisible to users), or replicate the hottest categories' rankings into N copies.
  5. Fresher ranks for hot products: a stream (Kinesis, or DynamoDB Streams on an orders table) into Flink keeps near-real-time counts for the top items, and the hourly batch corrects them (lambda architecture).

Why DynamoDB here, rather than SQL? Reads are simple key-range lookups at high QPS with no joins, writes are bulk and periodic, and the data is small (100,000 items). A relational sales_rank table with an index on (category_id, total_sold) behind read replicas and a cache would also work at this scale. Choose based on the rest of the stack.

When to Use It#

Choose DynamoDB when most of these are true:

  • You're on AWS, and want zero database operations. There are no instances, versions, vacuum, replication or failover to manage. This fits small teams, and serverless stacks (Lambda, API Gateway, Step Functions).

  • Access patterns are known, and key-based:

    • get a user, session or cart by ID;
    • list a user's orders by date;
    • look up by a few alternate keys, via GSIs.

    Each hot request should be a GetItem or a Query on one partition key.

  • Scale is large or unpredictable. From zero to hundreds of thousands of requests per second, with flat single-digit-millisecond latency, and without re-architecting. On-demand mode handles spiky or unknown traffic.

  • Simple, strong per-item correctness is enough. Conditional writes, atomic counters, and small ACID transactions cover inventory holds, idempotency keys, uniqueness and seat reservations.

  • Event-driven designs. Streams give you a reliable change feed for search indexing, notifications and aggregates.

  • Multi-region, active-active apps. Global tables, with LWW and home-region writes, give the simplest path to low-latency, multi-region reads and writes on AWS.

Typical fits:

  • user profiles, sessions, carts and shopping-cart-like state (Dynamo's original use case);
  • metadata stores (file metadata for an object store, a URL shortener's mappings);
  • leaderboards per game, keyed by game and score bucket;
  • IoT device state;
  • feature flags and configuration;
  • job and idempotency tables;
  • chat messages for moderate-scale apps.

Pick something else instead when:

  • You need flexible queries, joins, aggregations or ad-hoc reporting. Use PostgreSQL (or Aurora), and use a warehouse for analytics. If you find yourself adding a GSI for every new screen, that's the signal.
  • You need sustained, very high write throughput at the lowest cost, i.e. hundreds of thousands to millions of writes/s around the clock. Self-managed Cassandra or ScyllaDB can be much cheaper per write at that scale, at the cost of operations work. Or aggregate the writes first.
  • You need to stay cloud-neutral, or run on-premises. DynamoDB is AWS-only. Cassandra-compatible options (including Amazon Keyspaces), MongoDB and PostgreSQL are portable.
  • Full-text search, geo queries or vector search. Pair DynamoDB with Elasticsearch/OpenSearch via Streams, or with a vector database.
  • Items over 400 KB, or blob storage. Use S3, with metadata in DynamoDB.
  • Complex multi-item transactions with high contention, or interactive transactions. Use a relational or distributed SQL database (Dealing with Contention).
  • Time-series analytics with downsampling and rollups. Use a time-series database (Timestream, InfluxDB, TimescaleDB).

When NOT to Use It#

  • Access patterns are unknown or still being discovered. Early prototypes change their queries weekly, and each change can mean new keys, GSIs and backfills. Start with Postgres, and move hot, stable paths to DynamoDB later.
  • The interviewer asks for vendor-neutral designs. Ask first. Many interviewers allow DynamoDB, and some want open-source alternatives.
  • Workloads that scan everything. Reporting over the whole table costs a full read of the table every time. Export to S3, and query with Athena or Redshift instead.
  • Strict multi-region serializability, unless MRSC fits your latency and constraints.
  • Hot single items above about 1,000 writes/s that you can't shard or aggregate.
  • Very large relational graphs needing multi-hop traversals. Use a graph database, or Postgres with recursive CTEs.

How to Implement It#

  1. Write the access-pattern list. For each pattern, give the parameters, frequency (QPS), latency target, consistency need (strong or eventual), result size and sort order.
  2. Choose partition keys with high cardinality and even traffic: user, device or order IDs. Check the top 1% of keys: will any exceed 1,000 writes/s or 3,000 reads/s per key? If so, plan sharding, aggregation or caching now.
  3. Choose sort keys for range queries and pagination: time-ordered unique IDs (ULID, UUIDv7 or Snowflake), or typed and hierarchical prefixes.
  4. Add indexes deliberately.
    • Use GSIs for alternate lookups (sparse where possible, overloaded to save indexes), with KEYS_ONLY or INCLUDE projections to limit write amplification.
    • Use LSIs only for strongly consistent alternate sorts within small item collections, and decide on them before creating the table.
  5. Decide on single-table or multi-table. Use single-table when entities are fetched together and patterns are stable. Use separate tables when they're independent.
  6. Size and cost it: writes/s × ⌈item KB⌉ × (1 + affected GSIs) × (2 if transactional), and reads/s × ⌈item KB ÷ 4⌉ × (0.5 eventual or 1 strong). Pick on-demand for unknown or spiky traffic, and provisioned with auto scaling (plus reserved capacity) for steady, high utilisation.
  7. Correctness:
    • Use conditional writes for create-if-absent and optimistic locking (a version attribute).
    • Use transactions for multi-item invariants, with ClientRequestToken for idempotent retries.
    • Use strong reads only where they're needed.
  8. Add the ecosystem:
    • Streams to Lambda, for search, aggregates and events;
    • TTL for ephemeral data;
    • PITR on;
    • DAX for hot, eventually consistent reads;
    • global tables, if multi-region.
  9. Operate it. Watch these CloudWatch metrics: ThrottledRequests, consumed versus provisioned capacity, SuccessfulRequestLatency, GSI OnlineIndexThrottleEvents, and ReplicationLatency for global tables. Use CloudWatch Contributor Insights to find the most-accessed and most-throttled keys. The SDKs retry throttles with exponential backoff; tune the retry count and jitter (Resilience Patterns).
// Optimistic locking + idempotent order placement with the AWS SDK v3 (sketch)
import { DynamoDBClient, TransactWriteItemsCommand } from "@aws-sdk/client-dynamodb";
const db = new DynamoDBClient({});
 
export async function placeOrder(o: { id: string; userId: string; sku: string; qty: number; requestId: string }) {
  await db.send(new TransactWriteItemsCommand({
    ClientRequestToken: o.requestId,            // retries within 10 min are idempotent
    TransactItems: [
      { Update: {                               // decrement stock only if enough remains
          TableName: "Shop",
          Key: { PK: { S: `SKU#${o.sku}` }, SK: { S: "STOCK" } },
          UpdateExpression: "SET available = available - :q",
          ConditionExpression: "available >= :q",
          ExpressionAttributeValues: { ":q": { N: String(o.qty) } } } },
      { Put: {                                  // create the order once
          TableName: "Shop",
          Item: {
            PK: { S: `USER#${o.userId}` }, SK: { S: `ORDER#${o.id}` },
            GSI1PK: { S: `ORDER#${o.id}` }, GSI1SK: { S: "META" },
            status: { S: "PLACED" }, sku: { S: o.sku }, qty: { N: String(o.qty) } },
          ConditionExpression: "attribute_not_exists(PK)" } },
    ],
  }));
  // On TransactionCanceledException inspect CancellationReasons:
  // ConditionalCheckFailed on stock -> sold out; on order -> duplicate; TransactionConflict -> retry with backoff
}
TechnologyFits when
DynamoDB on-demandNew, spiky or unknown workloads; serverless apps; no capacity planning
DynamoDB provisioned + auto scaling + reservedSteady, high-utilisation traffic where cost matters
DAXMicrosecond, eventually consistent reads of hot items inside a VPC
DynamoDB Streams + LambdaChange-driven processing: search sync, aggregates, events, cache invalidation
Kinesis Data Streams for DynamoDBLonger retention, more consumers, Firehose to S3 or Redshift
Global tables (MREC / MRSC)Multi-region active-active with LWW, or strongly consistent multi-region with higher write latency
ElectroDB, DynamoDB Toolbox, PynamoDB, the Enhanced Client (Java)Typed single-table modelling helpers on top of the raw SDK
NoSQL Workbench, DynamoDB LocalVisual data modelling and local testing
Amazon Keyspaces / ScyllaDB AlternatorA Cassandra-compatible managed service on AWS / a DynamoDB-compatible API on ScyllaDB, for portability

Trade-offs#

OptionProsConsPick when
DynamoDBZero operations, elastic, flat ms latency, transactions, Streams, DAX, global tablesAWS lock-in, key-first modelling, 400 KB items, per-partition limits, cost at sustained high write volume, eventual GSIsAWS stack with known key-based patterns at any scale
Cassandra / ScyllaDBOpen source, multi-cloud, very high write throughput per dollar, tunable consistencyYou operate it (repair, compaction, upgrades); weaker transactions (LWT); same modelling disciplineMassive write-heavy workloads, multi-cloud or on-prem
PostgreSQL / AuroraSQL, joins, rich indexes, full ACID, mature toolingSingle-writer scaling limits; sharding is work; failover takes seconds to a minuteRelational data, evolving queries, moderate scale
MongoDB (Atlas)Flexible documents, rich queries and secondary indexes, aggregation pipeline, multi-cloudShard-key choice still matters; costs and operations if self-runDocument data with ad-hoc queries, outside AWS lock-in
Spanner / CockroachDBGlobal serializable SQL transactionsHigher write latency, cost, operational or vendor considerationsGlobal ACID with SQL
Redis / ElastiCacheSub-ms latency, rich data structuresMemory-bound cost; durability trade-offsCaching, leaderboards, rate limits next to DynamoDB

Common Pitfalls#

  • Relational modelling in DynamoDB: one table per entity and "joins" done in the application with N requests. Model item collections, or pre-join instead.
  • Scans or FilterExpressions on hot paths. You pay for everything read. If you filter often, it belongs in a key.
  • Low-cardinality or time-based partition keys (status, date, tenant with one giant tenant), and the same mistake in GSIs.
  • Under-provisioned GSIs that throttle base-table writes, or ALL projections that multiply write cost.
  • Believing GSIs are strongly consistent: reading your own write from a GSI immediately after writing it can return nothing.
  • Large items: storing reviews, logs or images inside the parent item, so every read pays for the whole item.
  • Relying on DAX for freshness: query-cache entries ignore writes, and direct writes bypass DAX entirely.
  • Assuming TTL deletes instantly: expired items can linger for days. Filter them on reads.
  • Hot counters: a single "global count" item updated thousands of times per second. Shard it, or aggregate.
  • Unbounded retries of throttled requests without jitter, which amplifies the overload.
  • LWW surprises in global tables: concurrent edits in two regions silently drop one. Use home regions, or commutative designs.
  • Forgetting the 1 MB page and the 100-item batch limits. Always handle LastEvaluatedKey and UnprocessedItems.

Real-World Examples#

  • Amazon retail. Many of Amazon's own services run on DynamoDB. AWS has publicly reported Prime Day peaks of over 100 million requests per second, with single-digit-millisecond latency (Prime Day 2022). Amazon also described migrating many internal databases off Oracle by 2019, with key-value-style workloads moving to DynamoDB.
  • The papers. The 2007 Dynamo paper describes the shopping cart as the canonical always-writable use case. The 2022 ATC paper describes DynamoDB's evolution: request routers, Multi-Paxos partitions, log replicas, adaptive capacity, global admission control, and continuous backups. The 2023 ATC paper covers transactions.
  • Zoom. AWS has published that Zoom used DynamoDB as it scaled through its rapid growth in 2020.
  • Many other companies, including gaming, ad tech and mobile backends, publish DynamoDB case studies. Treat specific numbers as belonging to those write-ups, and cite them only when you know them.

Case studies that use this pattern#

  • Dating App: swipe and match consistency with pair-keyed items and conditional updates.
  • URL Shortener: short code to URL mapping, with conditional create for collision-free codes, and DAX or caching for hot links.
  • Ticket Booking: seat holds with TTL, plus a conditional or transactional booking.
  • Notification System: user preferences, device tokens and idempotency keys with TTL.
  • Top-K: precomputed rankings served by key (the sales-rank pattern above).
  • Job Scheduler: job definitions, plus a time-bucketed GSI for due jobs.
  • Food Delivery and Chat System: orders and messages partitioned by owner, with sort-key ranges.

In the Interview#

Deep Dive: Inside DynamoDB: partitions, Multi-Paxos, admission control and durabilityShow

The 2022 USENIX ATC paper by Elhemali et al. describes how DynamoDB delivers predictable performance in a multi-tenant service. The main ideas follow.

Partitions as replication groups. A table is split into partitions by contiguous ranges of the hashed partition key.

  • Each partition is a Multi-Paxos group of storage replicas in different AZs.
  • The leader holds a lease, renewed by heartbeats. Only the lease-holder serves writes and strongly consistent reads, which prevents a partitioned old leader from serving stale "strong" reads.
  • If the leader fails or is cut off, a replica whose lease checks show the leader is gone starts an election. A new leader is ready after the old lease expires, typically within seconds.
  • The paper notes that false failure detection is a real risk. A replica that merely can't reach the leader asks its peers whether they can before triggering an election, to avoid needless failovers during "gray" network failures.

Each replica has two components: a B-tree of the partition's items, and the replication log, a write-ahead log.

  • Writes commit when a quorum of replicas have the log record.
  • Log replicas store only the recent log, with no B-tree. When a storage replica fails, the system can add a log replica in seconds, restoring a full write quorum quickly. Rebuilding a full B-tree replica means copying gigabytes, which takes minutes.
  • This decoupling of durability (log on a quorum) from materialisation (the B-tree) is a recurring theme of cloud databases, compare Aurora's "the log is the database".

Request routing and metadata.

  • Request routers must find a partition's leader on every request, and the fleet is huge. Routers keep a local cache of the partition map, which nearly all requests hit.
  • On a miss, they ask MemDS, a distributed, in-memory metadata store that holds the authoritative mapping. The paper describes having routers refresh from MemDS asynchronously, even on cache hits, so load on the metadata system stays constant whether caches are warm or cold.
  • That's a lesson in avoiding bimodal behaviour. A metabase that's fine when caches are warm, and overwhelmed when they're cold (after a deployment, say), turns a small event into an outage.

From per-partition quotas to global admission control.

  • Original design: a table's provisioned throughput was divided evenly across its partitions, and each partition enforced its share with a token bucket. Skewed workloads throttled on hot partitions while cold partitions wasted capacity. Splitting partitions as tables grew made each share smaller ("throughput dilution").

  • Fixes, in order:

    1. Bursting: partitions bank unused tokens, about 300 seconds' worth, when the node has spare capacity.
    2. Adaptive capacity: hot partitions get boosted shares, within the table's total.
    3. Global admission control (GAC): a separate service tracks consumption for the whole table, and hands token batches to the routers.

    With GAC, a table can consume its full capacity on whichever partitions need it, as long as each partition stays within its physical maximum. The storage nodes still enforce per-partition limits, to protect co-tenants on the same machine.

  • On-demand mode builds on the same machinery. The system watches consumed throughput, and splits partitions for heat ahead of demand, which is how "double the previous peak, instantly" is possible.

Placement and multi-tenancy. Many partitions, from many customers, share each storage node. The system monitors each node's throughput and storage, and moves partitions off nodes approaching their limits. Each partition's capacity cap (3,000 RCU and 1,000 WCU) exists precisely so that any one partition fits comfortably on a node next to others.

Durability and correctness:

  • Checksums on every log entry, message and file.
  • Continuous log archival to S3, which also powers PITR.
  • Background scrubbing, which compares replicas against archived logs to catch silent corruption.
  • Formal methods (TLA+) for the replication protocol.
  • Deployments handle the mix of old and new software versions, with a read-new and write-old phase, so a rollback is always possible.

The service-level agreement is 99.99% availability for regular tables, and 99.999% for global tables.

Static stability is another theme. DynamoDB tries to keep working on cached state when a dependency fails. For example, routers cache IAM authorisation results and table metadata, so a brief outage of an authentication or metadata dependency doesn't immediately fail traffic.

What this means for designers:

  • Latency stays flat because every request touches one small partition through a cached route. Your design must keep it that way: single-key access, bounded items.
  • Throttling usually means your key distribution is skewed, not that "DynamoDB is slow".
  • "Eventually consistent" reads are usually only milliseconds behind, but GSIs and global tables add asynchronous hops, whose lag grows under load.
Deep Dive: Transactions, isolation and concurrency control patternsShow

Isolation levels by operation:

OperationIsolation relative to transactions
GetItem, PutItem, UpdateItem, DeleteItemSerializable with respect to transactions on that item
TransactWriteItems, TransactGetItemsSerializable
BatchGetItem, Query, ScanRead committed: never see uncommitted transactional writes, but not a snapshot across items
BatchWriteItemEach item individually; no atomicity across items

The practical consequence: a Query that runs while a transaction updates two items in its range can see one updated and the other not yet updated. If you need a consistent view of several items, use TransactGetItems (up to 100 keys), or model the invariant into one item.

How a transaction executes (per the 2023 ATC paper):

  1. A transaction coordinator receives TransactWriteItems, and assigns a timestamp.
  2. Prepare. The coordinator sends each item's partition leader a prepare request. Each leader checks the conditions, checks that no conflicting, newer transaction or write has been accepted, and records the pending transaction against the item. Any rejection aborts the transaction.
  3. Commit. Once every leader has accepted, the coordinator logs the decision durably, and tells the leaders to apply the writes.
  4. Recovery. If a coordinator dies, a recovery manager finds unfinished transactions in the durable ledger, and drives them to commit or abort.

Timestamp ordering means:

  • no lock is held across network round trips between client and server;
  • conflicting transactions are rejected (TransactionConflict), rather than queued;
  • a single-item write that arrives while the item is part of a prepared transaction can be rejected too.

Under heavy contention on the same items, transactions fail and retry, much like optimistic concurrency. The design keeps non-transactional single-item operations fast, which matters because they're the vast majority of traffic.

Contention patterns:

  • Optimistic locking.

    1. Read the item with its version.
    2. Compute in the application.
    3. Write with ConditionExpression: version = :v and SET version = :v + 1.
    4. On ConditionalCheckFailed, re-read and retry.

    This is ideal when conflicts are rare, and it works for long, human-scale edits.

  • Atomic in-place updates. UpdateItem SET available = available - :q with ConditionExpression: available >= :q never needs a read. The leader serialises updates to that item, so it handles high contention well, up to the per-item ~1,000 WCU limit.

  • Reservation with TTL. For a seat hold, write PK = SEAT#e1#A12 with hold_by = user, expires_at = now + 600, and ConditionExpression: attribute_not_exists(PK) OR expires_at < :now. An expired hold can be taken over immediately, even if TTL hasn't physically deleted it yet. The final booking is a transaction that converts the hold into a booking, and creates the order (Ticket Booking).

  • Idempotency keys. PutItem PK = IDEMP#<request-id> with attribute_not_exists(PK), as part of the same transaction as the side effect. A retried request fails the condition, and returns the stored result (Idempotency).

  • Fencing and leases. A lock item with owner, lease_until and a monotonically increasing fence number. Acquire with a conditional write, renew before expiry, and have downstream writes check the fence. DynamoDB-based lock clients exist for this. The usual distributed-locking caveats apply (Distributed Locking).

Transaction costs and limits in practice.

  • A transaction over 10 items of 1 KB costs 20 WCU (2× each), plus GSI updates.
  • Latency is roughly two round trips to the leaders, often about 10–20 ms, against about 5 ms for a single write.
  • Items in one transaction can live in different tables, but must be in the same region. In global tables, other regions apply the transaction's writes individually as they replicate. A reader there can see part of the transaction, and a concurrent write in another region can overwrite part of it via LWW.
  • Rule of thumb: keep transactions small, uncontended and rare. Most write paths should be single-item conditional writes.

Exactly-once processing with Streams. Streams deliver each change exactly once into the stream. A Lambda consumer can still process a batch more than once, because retries happen after a failure partway through the batch. Make consumer side effects idempotent: conditional writes keyed by the source item's (PK, SK, version), or by the stream sequence number.

Deep Dive: Advanced data modelling patterns, migrations and cost modellingShow

Many-to-many with adjacency lists. For example, users ↔ groups.

  • Store edges as items PK = USER#u1, SK = GROUP#g5 (with denormalised group name and role).
  • Add an inverted-index GSI that swaps the keys: GSI1PK = SK, GSI1SK = PK.
  • Query PK = USER#u1, begins_with(SK, "GROUP#") returns the groups of a user.
  • Query GSI1 PK = GROUP#g5 returns the members of a group.

Each direction is one Query. Denormalised attributes on edges go stale when the source changes. Update them by a Streams fan-out, or accept the staleness for immutable fields.

Time series:

  • PK = device#d1#2026-12-02 (a day bucket), with SK = timestamp. That bounds item collections, and spreads load across days.
  • For "all devices, last hour", maintain a sharded GSI or a separate aggregate table.
  • AWS's guidance for heavy time-series tables is a table per period (for example, monthly). The current table gets high write capacity, older tables get reduced capacity (or the Standard-IA table class), and expired periods are deleted as whole tables, which is cheaper than TTL-ing billions of items.

Item versioning.

  • Write each change as SK = v<N> (history), and also overwrite SK = v0 (latest), in one transaction: a conditional v0.version = N - 1 update plus a Put of vN.
  • Reads of "current" hit v0. Audit and history are begins_with(SK, "v").
  • This gives append-only history with an O(1) current read.

Leaderboards.

  • A GSI with PK = GAME#g1#SHARD#k and SK = score (zero-padded or Number) lets you read the top N per shard, with ScanIndexForward = false, and merge the shards' top N.
  • Exact global rank (what's my position among 50 million?) is expensive in DynamoDB. Use Redis sorted sets for live ranks, and DynamoDB for durable scores (Top-K).

Geo queries. Store a geohash prefix as a GSI partition key (for example, 5 characters, about 5 km cells), and a fuller geohash as the sort key. Query the cell plus its neighbours, then filter by exact distance in the application (Geospatial Indexing). For heavy geo search, use OpenSearch, PostGIS or Redis GEO instead.

Pagination. Expose LastEvaluatedKey as an opaque, encoded cursor. Never use offset pagination: DynamoDB has no OFFSET, and skipping N items means reading them. Combined with a time-ordered sort key, "load older" is SK < cursor.

Schema migrations without downtime:

  1. Add attributes lazily. Read old and new shapes, and write the new one (schema-on-read with a schema_version attribute).

  2. Add a GSI for a new access pattern. DynamoDB backfills it online. Watch the backfill's write consumption.

  3. Re-keying (changing the partition or sort key design) needs a new table or new items:

    • turn on Streams;
    • backfill with a parallel Scan, or from an export to S3 (no table capacity used);
    • dual-write via a Streams-to-Lambda replicator into the new design;
    • verify counts and checksums;
    • flip reads, then stop the old writes.

    This is the general pattern in Data Migration.

Cost modelling: a worked comparison. Take a steady workload of 20,000 writes/s (1 KB items) and 60,000 eventually consistent reads/s (4 KB), 24×7, with 2 TB stored. Prices are rough and region-dependent; check the current price sheet.

  • Provisioned: 20,000 WCU × $0.00065 × 730 h ≈ $9,500 per month. 30,000 RCU (eventual halves 60,000) × $0.00013 × 730 ≈ $2,850 per month. Storage, 2 TB at about $0.25/GB ≈ $500 per month. Total about $13k per month before reserved-capacity discounts (which can cut throughput costs substantially) and before GSIs (each ALL-projected GSI on every write adds roughly the write cost again).
  • On-demand: 20,000 × 2.6 million s/month ≈ 52 billion writes. At about $0.625 per million write request units, that's ≈ $32,500. Reads: 156 billion × 0.5 units ≈ 78 billion read request units, at about $0.125 per million ≈ $9,750. Total about $43k per month: about 3× provisioned for this steady load.
  • Self-managed Cassandra or ScyllaDB: perhaps 6–12 nodes for throughput (more for storage and failure headroom). Instance costs might be in the same order of magnitude, but you add engineering time for operations, on-call, upgrades and repair.

The decision usually turns on people cost and risk, not on the instance bill: DynamoDB's zero-operations premium is often worth it below a few hundred thousand writes per second.

Levers that move the bill most:

  • Smaller items. Compress large text, and shorten attribute names; names count towards item size.
  • Fewer, sparser GSIs with KEYS_ONLY or INCLUDE projections.
  • Eventual reads wherever they're acceptable.
  • DAX or caching for hot reads.
  • Aggregating writes upstream.
  • TTL instead of deletes.
  • The Standard-IA table class for rarely read data (cheaper storage, pricier requests).
  • Reserved capacity for the baseline, with on-demand or auto scaling for peaks.

Key Takeaways#

  • DynamoDB is a managed, serverless key-value and document store. The partition key hashes to a partition (a 3-way Multi-Paxos group across AZs), and the sort key orders items within the partition key's item collection. Design every hot path as a GetItem or a single-partition Query.
  • Indexes are deliberate:
    • GSIs are separate, asynchronously maintained tables, with eventually consistent reads and their own capacity. They can be added any time. Make them sparse or overloaded, and watch write amplification and back-pressure.
    • LSIs share the partition key, support strong reads, must be created with the table, and cap item collections at 10 GB.
  • Single-table design pre-joins related entities in item collections, using prefixed generic keys. It's powerful for stable access patterns, and unnecessary otherwise.
  • Capacity: 1 WCU per 1 KB write, 1 RCU per 4 KB strong read (0.5 eventual), and 2× for transactions. Each partition is limited to 3,000 RCU and 1,000 WCU and holds ~10 GB. On-demand suits spiky or unknown traffic; provisioned with auto scaling and reserved capacity suits steady load.
  • Consistency is per read. Strong reads go to the leader (base table and LSIs only). Writes are durable on 2 of 3 replicas. Conditional writes and atomic counters are linearizable per item. Transactions cover up to 100 items in one region, at 2× cost, with timestamp ordering.
  • Streams (24 h, exactly-once, ordered per item) power CDC to OpenSearch, aggregates, events and cache invalidation. DAX gives microsecond eventually consistent reads, but its query cache ignores writes, and direct writes bypass it. Global tables are multi-active with last-writer-wins (or MRSC for strong multi-region consistency).
  • Hot keys are the main scaling enemy. Adaptive capacity and split for heat help, but one item caps at ~1,000 writes/s. Shard, aggregate and cache.
  • Choose DynamoDB for AWS-native, key-based access at any scale with no operations work. Choose PostgreSQL for flexible queries, Cassandra or ScyllaDB for very high sustained writes or multi-cloud, and Elasticsearch for search.