AlgoViz

DynamoDB

medium 36 min

Amazon DynamoDB is a managed key-value and document database.

Video lesson · Chapter 1 of 5

Find a customer's last order

0:00 / 3:53

DynamoDB in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

DynamoDB is a database service of AWS. A table holds items, an item holds named attributes, and the only thing all items of a table must share is the primary key. There are no servers to choose: AWS places the data, copies it and moves it.

The primary key is a partition key alone, or a partition key with a sort key. A hash of the partition key says where an item lives. Items with the same partition key form an item collection and are kept in the order of their sort key.

Why it exists

Many requests are simple: this cart, this session, the last ten orders of this customer. A relational database answers them well until the data grows, and then plans, locks and joins make the time uncertain. DynamoDB gives up joins and free queries so that the time of a request does not depend on the size of the table.

The other reason is operations. Copies in several Availability Zones, splitting, patching and recovery are the service's work, and capacity can follow the traffic.

A short history

  1. October 2007

    Amazon presents the Dynamo paper: a leaderless key-value store for the shopping cart. DynamoDB later takes its name and its goals from it, with a different design.

  2. 18 January 2012

    AWS launches DynamoDB as a managed service.

  3. 29 November 2017

    Global tables are announced: one table with writable copies in several Regions.

  4. 27 November 2018

    Transactions over several items and tables are announced.

  5. July 2022

    The team describes the inside of the service in a paper at USENIX ATC: replication groups, Multi-Paxos, log replicas and splitting by heat.

Words to know

Partition key
The attribute that is hashed to find the partition. It must be given exactly.
Sort key
The attribute that orders items with the same partition key and allows ranges.
Item collection
All items with one partition key value.
GSI
Global secondary index: a copy of chosen attributes under another key.
RCU, WCU
Read and write capacity units, the currency of throughput.
Conditional write
A write that happens only if a condition about the item is true.
Throttling
The service refuses a request because a limit on throughput is reached.

How it works

Step through the idea, or press Play.

Step 1 of 3

List the questions. Write each access pattern with how often it happens

Understand it

Start here

The key-cutting wall

A key-cutting shop keeps a copy of every key it has cut. The wall has one row for each owner, and each row hangs its keys from the oldest to the newest. Imagine asking the shopkeeper for a key.

One row for each owner
1234AshaLeeNoorshopkeeper

The general ideas are on other pages: key-value databases, partitioning, and how such a store is built in key-value store design.

Fit

When to choose it

  • Predictable time

    A lookup by key takes about the same time on a kilobyte and on a petabyte.

  • Grows by itself

    Partitions are added and split by the service. You do not plan shards, but you do plan keys.

  • Little to operate

    No servers, patches or replication to set up. Backups exist, and you must switch on point-in-time recovery.

  • Pay for use

    On-demand mode charges for each request. Storage, indexes, streams and copies in other Regions are charged as well.

Choose it when

  • The questions are known: carts, sessions, orders of a customer
  • Very many requests with a steady time
  • The team wants no database servers
  • The system already lives in AWS with events and functions
  • Data is simple or forms a small hierarchy

Look elsewhere when

  • People will ask new questions every week
  • Joins and reports are the main work
  • Lookups by another attribute must always be fresh
  • The data is small and PostgreSQL would be simpler
  • You must run outside AWS

Keys

Partition key and sort key

One table of orders

PKSKAttributes
USER#123PROFILEname, email
USER#123ORDER#2026-01-15#001total, status
USER#123ORDER#2026-02-02#002total, status
ORDER#001ITEM#Aquantity, price
ORDER#001ITEM#Bquantity, price
PK and SK are plain names for the two keys. The prefix says what kind of thing a row is.

What a query may say

QuestionKey conditionReads
One profilePK = USER#123, SK = PROFILE1 item
Profile and all ordersPK = USER#123The collection
Orders, newest firstPK = USER#123, SK begins with ORDER#, backwardsAs many as the limit
Orders of January 2026PK, SK between two datesThat slice
Items of an orderPK = ORDER#0012 items
All paid orders of everybodyNot possible on this keyNeeds an index
The partition key is always an equality. The sort key allows equality, comparison, between and begins with.

A good partition key has many values used about equally often. A key such as status, with two values, puts everything in two places.

Query returns at most 1 MB for one call and a LastEvaluatedKey to continue. An item may have at most 400 KB, names included.

Inside

How a request travels

Router, partition, three copies

An app sends a request to DynamoDB. A request router checks permission and looks up the partition. It reaches the leader of partition 7, which runs on a machine in zone A and copies its log to two replicas on machines in zones B and C.
Each thick box is one machine in its own Availability Zone. A table has many such groups, one for each partition.
  1. 1

    The request arrives

    Signed with AWS credentials, sent straight to the service, or through DAX if a cache is used.

  2. 2

    The router dispatches

    Request routers check permission, hash the partition key, and look up the partition in metadata, most of it cached.

  3. 3

    The leader takes the write

    It writes a log record and sends it to its peers. Two of three must have it on disk before success.

  4. 4

    The B-tree follows

    A storage replica keeps a write-ahead log and a B-tree. The log makes the write safe, the tree makes it findable.

  5. 5

    Reads choose

    A strongly consistent read goes to the leader. An eventually consistent read may use any copy.

  6. 6

    Heat is watched

    Busy partitions are split, and busy items are kept apart from each other.

A write and its quorum

The paper calls the three a replication group. Leaders are elected with Multi-Paxos and keep a lease.

If a storage copy is lost, a log replica that holds only recent log records can be added in seconds to make the quorum whole, and the full copy is built afterwards.

Guarantees

Consistency

ReadCost for 4 KBSeesAvailable on
Eventually consistent0.5 unitPerhaps not the newest writeTables, LSI, GSI, streams
Strongly consistent1 unitEvery write confirmed before it, in this RegionTables and LSI only
Transactional2 unitsSeveral items as one snapshotTables
Eventually consistent is the default. A read through a global secondary index can never be strongly consistent.

Capacity

Read and write units

Units for one item of size s

RCU=⌈s4 KB⌉×{0.5eventual1strong2transactionWCU=⌈s1 KB⌉×{1write2transaction\text{RCU} = \left\lceil \frac{s}{4\,\text{KB}} \right\rceil \times \begin{cases} 0.5 & \text{eventual} \\ 1 & \text{strong} \\ 2 & \text{transaction} \end{cases} \qquad \text{WCU} = \left\lceil \frac{s}{1\,\text{KB}} \right\rceil \times \begin{cases} 1 & \text{write} \\ 2 & \text{transaction} \end{cases}
A 10 KB item: 3 units strongly consistent, 1.5 eventually, 6 in a transaction. Writing it costs 10.

A worked estimate

10,000 readss×4 KB eventual=5,000 RCU1,000 writess×2 KB=2,000 WCU10{,}000\ \tfrac{\text{reads}}{s} \times 4\,\text{KB eventual} = 5{,}000\ \text{RCU} \qquad 1{,}000\ \tfrac{\text{writes}}{s} \times 2\,\text{KB} = 2{,}000\ \text{WCU}
Add the writes to every index: an update that changes an indexed attribute costs units there as well.

Two modes

On-demandProvisioned
You pay forEach request unitUnits reserved for each hour
Good forNew, spiky or unknown trafficSteady traffic you can forecast
GrowthUp to twice the previous peak at onceAuto scaling follows a target with a delay
New table4,000 writes and 12,000 reads a secondWhat you set
RiskA bill that follows a bugThrottling, or paying for idle units
The default quota is 40,000 read and 40,000 write units for a table in either mode, and it can be raised.

Which mode?

Compare with the price page of your Region. The gap between the modes has changed over the years.

The common failure

Hot partitions

One partition gives at most 3,000 read units and 1,000 write units a second. Adding capacity to the table does not change this for one key.

  1. 1

    Burst capacity

    Up to 300 seconds of unused throughput is kept for short peaks.

  2. 2

    Adaptive capacity

    A partition may use more than its even share while the table as a whole has room. It works at once and needs no setting.

  3. 3

    Isolation of busy items

    Busy items are moved so that they do not share a partition. One item can then have the whole 3,000 and 1,000.

  4. 4

    Write sharding

    For a single key that needs more, add a number: item_123#0 to item_123#9. This is your work, not the service's.

How many parts?

N=⌈50,000 writes/s×1 WCU1,000 WCU⌉=50 parts, and some spareN = \left\lceil \frac{50{,}000\ \text{writes/s} \times 1\ \text{WCU}}{1{,}000\ \text{WCU}} \right\rceil = 50\ \text{parts, and some spare}
Reading the total then asks all 50 parts. The trade is explained in sharded counters.

Scatter the writes, gather the reads

Choose the part by a random number or by a hash of the user. A hash of the item itself would always give the same part.

Indexes

GSI, LSI and index overloading

Global (GSI)Local (LSI)
KeyAny partition and sort keySame partition key, other sort key
ConsistencyEventual onlyEventual or strong
How many20 by default, can be raised5
CreatedAny timeOnly with the table
LimitOwn throughput10 GB for one partition key value
If a GSI has too little write capacity, writes to the table are throttled too.

Sparse index: only items that have the index attributes appear in it, so an index on openSince holds only open tickets. Inverted index: swap PK and SK to look up the other way. Overloading: one index serves several questions when its keys have neutral names and prefixes.

One overloaded index

ItemGSI1PKGSI1SKAnswers
Profile of 123EMAIL#sam@example.comUSER#123User by email
Order 001STATUS#PENDING2026-01-15Pending orders by date
Order 002STATUS#SHIPPED2026-01-16Shipped orders by date
A status has few values. If many orders change status each second, add a number to that key as well. A GSI key may also combine up to four attributes, so fewer joined strings are needed.

Modelling

One table or several

With single-table design, kinds of item that are read together share a partition key, so one query brings a user and the orders. It saves round trips, because there is no join. It costs clarity: keys are strings with prefixes, and a new question may need a new index and a backfill.

Design steps

Use several tables when the things are never read together or have different owners and backups.

Correct writes

Conditions first, transactions second

A conditional write checks and changes one item in one step. It needs no transaction: attribute_not_exists(PK) prevents duplicates, a version number prevents lost updates, and a status check allows only legal steps. A failed condition still uses write units.

Python
# Claim a short link: only one of two simultaneous callers succeeds.table.put_item(    Item={"PK": "LINK#my-link", "SK": "META", "target": "https://example.com"},    ConditionExpression="attribute_not_exists(PK)",)# Optimistic locking.table.update_item(    Key={"PK": "USER#123", "SK": "PROFILE"},    UpdateExpression="SET #n = :new, version = version + :one",    ConditionExpression="version = :seen",    ExpressionAttributeNames={"#n": "name"},          # name is a reserved word    ExpressionAttributeValues={":new": "Noor", ":seen": 1, ":one": 1},)# A counter without reading first. Only a pending order may be shipped.table.update_item(    Key={"PK": "PRODUCT#456", "SK": "META"},    UpdateExpression="SET viewCount = if_not_exists(viewCount, :zero) + :one",    ExpressionAttributeValues={":zero": 0, ":one": 1},)table.update_item(    Key={"PK": "ORDER#789", "SK": "META"},    UpdateExpression="SET #s = :shipped",    ConditionExpression="#s = :pending",    ExpressionAttributeNames={"#s": "status"},    ExpressionAttributeValues={":shipped": "SHIPPED", ":pending": "PENDING"},)
A failed condition raises ConditionalCheckFailedException. Return a conflict, or read again and retry.

A transaction (TransactWriteItems, TransactGetItems) covers up to 100 items and 4 MB, in one or several tables of one account and Region. It costs twice the units, because each item is prepared and then committed.

Prepare, then commit

A cancelled transaction lists a reason for each item. A client token makes a retry safe for ten minutes.

Transactions are serializable against each other and against single-item reads and writes. A Query, Scan or BatchGetItem as a whole is only read-committed: it may see one item before and another after a transaction.

Time

TTL and streams

TTL deletes items whose timestamp, in Unix seconds, has passed. It uses no write units, but it is not prompt: deletion happens typically within a few days. Until then reads return the item, so filter by time or check it in code.

DynamoDB Streams is an ordered log of item changes, kept for 24 hours. Each record appears once in the stream and changes to one item stay in order. A record can hold the keys, the new image, the old image, or both. A Lambda function reads the stream, and Lambda may process a record more than once, so make the handler idempotent.

Outbox without a dual write

Other uses: search index, notifications, totals, an archive of items that TTL removed.

The general pattern is change data capture. A removal by TTL can be recognised by the user identity of the service in the record.

Speed and distance

DAX and global tables

A cache in one Region, a copy in another

Two Regions. In each Region an app reads and writes its local copy of a DynamoDB table. The app in Region one also reads through a DAX cluster. Changes are copied between the two tables in both directions.
The dashed arrows are the copying between Regions, in both directions. Both copies accept writes. DAX belongs to one Region.

DAX is an in-memory cache in front of DynamoDB that speaks the same API and answers in microseconds. It has an item cache and a query cache, and writes pass through it. It helps with many repeated eventually consistent reads. Strongly consistent reads are passed on and not cached, so it gives nothing there. You pay for its nodes.

Global tables: two consistency modes

Eventual (MREC, default)Strong (MRSC)
Copies between RegionsAfterwards, typically within a secondBefore the write succeeds
Two Regions write one itemLast writer winsConflict is refused
RegionsAs many as you addExactly three: three copies, or two and a witness
TransactionsAtomic only in the Region of the callNot supported
TTL, LSISupportedNot supported
With last writer wins, a lost update is silent. Send each user's writes to one home Region.

Operations

Running it

WatchWhyDo
Throttled requestsA key, an index or a quota is fullFind the key with Contributor Insights
Consumed unitsThe bill and the headroomAlarm, and a maximum for on-demand
Latency by operationA slow client or large itemsSmaller items, projections
Iterator age of the functionThe stream is read too slowlyFix errors before 24 hours pass
RecoveryA bad deploy deletes dataPoint-in-time recovery, up to 35 days

Decide

Trade-offs and neighbours

What you gain

  • Scale: one design for ten requests a second and millions.
  • Steady time: table size does not matter.
  • No servers: patches and copies are not your work.
  • Availability: three zones without setting anything.
  • Pay by request if you like.

What you pay

  • Known questions: a new one may need an index and a backfill.
  • No joins: copy data or ask twice.
  • Stale indexes: GSI reads are eventual.
  • Hard modelling: single-table keys take practice.
  • Lock-in: the API and the key design are AWS only.

Compared with neighbours

AlikeDifferentChoose the other for
CassandraPartition and sort keys, high write rateNo leader, CQL, you run the nodesOther clouds, own hardware, tuning
MongoDBDocuments, horizontal scaleFree queries, pipelines, runs anywhereQuestions still changing
PostgreSQLStructured data, transactionsJoins, a planner, strong reads by defaultReports, relations, smaller data
RedisKeys, expiry, quickIn memory, rich structures such as sorted setsCache, ranking, short-lived data

Summary

The whole topic in one minute.

DynamoDB is a wall of hooks: the partition key picks the row, the sort key orders the hooks, and a request that names both is quick however long the wall is. So list the questions first and shape the keys for them.

Reads are eventually consistent unless you ask, indexes always are, and one partition gives at most 3,000 read and 1,000 write units a second. Most production trouble is a hot key, a scan or a filter mistaken for an index.

  • Design from the questions: every one a Get or a Query.
  • A partition gives 3,000 read and 1,000 write units; split hot keys yourself.
  • 4 KB for a read unit, 1 KB for a write unit; eventual is half, transactions are double.
  • GSI reads are always eventual, and a filter saves no units.
  • Use a condition for one item, a transaction for several.
  • TTL takes days, streams keep 24 hours, handlers must be idempotent.

Sources