TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท databases ยท nosql ยท key-value

Amazon DynamoDB

A fully managed key-value and document database. Items are spread across partitions by a hashed partition key, so reads and writes by key stay fast at any size, as long as the keys are designed around the queries you'll run.

16 min6 animations

๐Ÿ“š Builds on๐Ÿ“• Sharding

๐Ÿ–จ๏ธ Cheat sheet

A hall of pinboards

Picture a huge hall where a shop keeps a card for every order. Each card has a few lines on it: what was bought, how much it cost, whether it has been sent.

The shop never walks up to the boards itself. It hands each card to the steward at the door. The steward reads the name on the card, runs it through a fixed rule and gets a board number. Ana's cards always go on the same board, so finding them later is quick. On that board, Ana's cards hang together in one column, in date order.

The name on the card is called the partition key. Apart from the name and the date, nobody needs to agree on what goes on a card: one can mention gift wrap, the next one not.

Tables, items and keys

Amazon DynamoDB is a fully managed, serverless NoSQL database. There are no servers to size or patch: you create a table and read and write over an HTTPS API.

TermMeaning
TableA collection of items, such as Orders
ItemOne record, up to 400 KB, like a row
AttributeA named value on an item: string, number, binary, boolean, list, map, set or null
Partition keyThe required part of the primary key; DynamoDB hashes it to choose a partition
Sort keyOptional second part of the primary key; orders items that share a partition key
PartitionAn internal slice of the table's storage and throughput, replicated across Availability Zones

The primary key is either a partition key alone, or a partition key plus a sort key. Items with the same partition key form an item collection, stored together and sorted by sort key. Only the key attributes are part of the schema; every other attribute is optional and can differ from item to item.

This is sharding done for you. DynamoDB adds and splits partitions as data and traffic grow, and the hash on the partition key decides where each item lives.

Partition keys pick the partition5 steps
๐Ÿ“Œ Orders hallBoard 001234Board 101234Board 201234๐ŸชShop๐Ÿง‘โ€๐Ÿ’ผSteward
Press play and watch it happen!

Ask for one name, not every card

Because the steward knows which board holds Ana's cards, "Ana's cards from June" is a quick errand: one board, one column, already in date order. That kind of question is called a query.

"Every card that mentions a red scarf" is different. The name doesn't help, so the steward must walk along every board and read every card, then ignore the ones that don't match. That's slow, and the hall charges for every card read, not just the ones you keep.

So before setting up the hall, write down the questions you'll ask, and choose names and dates that make each of them a quick errand.

Query, Scan and access patterns

  • GetItem reads one item by its full primary key.
  • Query needs an equality condition on the partition key and can add a range condition on the sort key (=, <, BETWEEN, begins_with). It reads one item collection, in sort key order, forwards or backwards.
  • Scan reads every item in the table (or index).

Both Query and Scan return at most 1 MB per call and hand back a LastEvaluatedKey to page through the rest. A FilterExpression runs after items are read, so it trims the response but not the capacity consumed.

That's why DynamoDB design starts from access patterns: list every query the application needs, then choose keys (often composite sort keys such as ORDER#2026-06-01) so each one is a GetItem or Query. Joins, ad-hoc filters and aggregates aren't what it's built for; a table you mostly Scan is usually a sign the keys are wrong.

Query one partition, or Scan them all4 steps
๐Ÿ“Œ Orders hallBoard 001234Board 101234Board 201234๐ŸชShop๐Ÿง‘โ€๐Ÿ’ผSteward
Press play and watch it happen!

Paying for pins, and the crowded board

There are two ways to pay the hall. You can pay for each card pinned or read, and the hall makes room whenever it gets busy (only a sudden, enormous rush means a short wait). Or you can book a fixed number of cards per second in advance, which is cheaper when the flow is steady; past that number, the steward asks you to come back in a moment.

Whichever you choose, each board can only take so many cards a second, because only so many hands fit in front of it. If a big sale means every card carries the same name, they all go to one board. That board is mobbed while the others stand idle. This is a hot partition.

The fix is in the names: write "Sale 1", "Sale 2" and "Sale 3" instead of just "Sale", so the cards spread over several boards. Reading the sale back then means asking for all three names and putting the answers together.

Capacity modes and hot partitions

On-demandProvisioned
You pay forEach read and write requestRead and write capacity units per second, reserved
ScalingAutomatic; can still throttle on a sudden jump past double the previous peakYou set capacity, optionally with auto scaling
SuitsSpiky or unknown trafficSteady, predictable traffic, at lower cost

Capacity is measured in units. One write unit covers a write of up to 1 KB. One read unit covers one strongly consistent read of up to 4 KB, or two eventually consistent reads; sizes round up. Going past provisioned capacity gets requests throttled (ProvisionedThroughputExceededException), and the SDK retries with backoff.

Underneath both modes, each partition serves at most 3,000 read units and 1,000 write units per second. A partition key that takes a large share of traffic (a hot key) can be throttled at that ceiling even when the table as a whole has plenty of capacity. Adaptive capacity shifts throughput to busy partitions. Split for heat can spread a hot item collection by sort key (not if the table has an LSI), but never one item.

Prefer high-cardinality partition keys (user id, order id). For an unavoidable hot key, use write sharding: append a suffix such as SALE#1 โ€ฆ SALE#3, then read all suffixes and merge.

A hot partition key4 steps
๐Ÿ“Œ Orders hallBoard 001234Board 101234Board 201234๐ŸชShop๐Ÿง‘โ€๐Ÿ’ผSteward
Press play and watch it happen!

A second board, sorted another way

The packing team doesn't care about names. It wants "every card that hasn't been sent yet". Walking along every board for that each morning would be slow, so the hall keeps a second set of boards, arranged by status instead of by name. That second set is called an index.

A runner copies each new card's summary onto the status board. The runner is fast but not instant, so for a moment right after a card is pinned, the status board may not show it yet. And if almost every card says "waiting", they all land on the same status board, which gets mobbed just like a busy name.

Secondary indexes

A secondary index lets you Query by keys other than the table's primary key. DynamoDB maintains it on every write.

Global secondary index (GSI)Local secondary index (LSI)
KeyAny partition key and sort keySame partition key as the table, different sort key
WhenAdd or remove any timeOnly when the table is created
ReadsEventually consistent onlyEventually or strongly consistent
CapacityIts own, separate from the tableShares the table's
Limit20 per table (default quota)5 per table

A GSI is effectively a second table that DynamoDB updates asynchronously, so a query on it can briefly miss a write the table already acknowledged. You choose which attributes to project into the index (keys only, some, or all); queries can only return projected attributes. Writes to the table also consume write capacity on each affected GSI, and a GSI that's throttled can throttle writes to the table.

A GSI has its own partitions, so a key with few values, such as status, can make the index hot even when the table is evenly spread; at scale, shard the index key or use a sparse index.

With an LSI, an item collection (the table's and its LSIs' items for one partition key) can't exceed 10 GB.

A global secondary index5 steps
Name boards01234Status board01234๐ŸชShop๐Ÿ“ฆPacking team
Press play and watch it happen!

Copies in three buildings

Each board has two twin copies in two other buildings, so a power cut in one building loses nothing. A new card goes on the main board first, and the shop hears "got it" as soon as enough copies have it. The last copy catches up a moment later.

When you ask a question, the quick answer may come from any copy, even the one that's a moment behind, so it might miss the newest card. If you need to be sure, ask for a strongly consistent answer: it always comes from the main board, and it costs twice as much.

Read consistency

DynamoDB stores each partition as several replicas across Availability Zones in a Region, with one leader taking the writes. A successful write is durable, but replicas apply it a moment apart.

  • Eventually consistent (the default): the read may be served by any replica and may not reflect a write that just succeeded. Costs half a read unit per 4 KB.
  • Strongly consistent (ConsistentRead=true): returns the latest acknowledged write. Costs a full read unit, has higher latency, and can fail with a server error during a network delay or outage, where an eventually consistent read would still succeed.

Strongly consistent reads work on tables and LSIs, but not on GSIs or Streams. With global tables (multi-Region replicas), a strongly consistent read only sees writes made in its own Region, unless the global table was created with multi-Region strong consistency (generally available since June 2025).

Eventually or strongly consistent reads5 steps
๐Ÿข Building 1๐Ÿฌ Building 2๐Ÿฃ Building 3Main board0123Copy board0123Copy board0123๐ŸชShop
Press play and watch it happen!

Only if nobody changed it

Two shop workers, Lu and Bo, look at Ana's card at the same moment. It says "version 3" at the top. Each writes a new card and hands it to the steward with a note: "swap it only if it still says version 3". That's called a conditional write.

Lu's swap goes through, and the card now says version 4. Bo's is refused, because the card no longer says version 3. Instead of silently wiping out Lu's change, Bo reads the card again and redoes the change on top.

For changes that must happen together, such as marking a pair of shoes as sold and adding them to Ana's order, the steward can swap several cards as one errand: all of them or none. And the hall keeps a diary of every change, so others can react, like emailing Ana when her order is sent.

Conditional writes, transactions and Streams

Every write (PutItem, UpdateItem, DeleteItem) can carry a ConditionExpression. DynamoDB evaluates it atomically against the current item and rejects the write with ConditionalCheckFailedException if it's false. Common uses: attribute_not_exists(pk) to insert only if absent, and a version check for optimistic locking: read the item with its version, write with version = :expected, and on failure re-read and retry.

TransactWriteItems and TransactGetItems group up to 100 actions on distinct items, across tables in one account and Region, all-or-nothing and serializable. Transactions consume twice the capacity of plain reads and writes.

DynamoDB Streams records item-level changes (keys only, new image, old image, or both), in order per item, and keeps them for 24 hours. A Lambda function or a Kinesis Client Library consumer typically reads it to update search indexes, send notifications or replicate data.

With the AWS SDK for Java v2, the Enhanced Client maps a bean to a table. @DynamoDbVersionAttribute turns on optimistic locking: it adds the version condition to every putItem and updateItem (not deleteItem, which needs its own condition) and increments the number for you.

1@DynamoDbBean2public class Order {3    private String customerId;   // partition key4    private String orderDate;    // sort key5    private String status;6    private Long version;7 8    @DynamoDbPartitionKey9    public String getCustomerId() { return customerId; }10    public void setCustomerId(String customerId) { this.customerId = customerId; }11 12    @DynamoDbSortKey13    public String getOrderDate() { return orderDate; }14    public void setOrderDate(String orderDate) { this.orderDate = orderDate; }15 16    @DynamoDbVersionAttribute17    public Long getVersion() { return version; }18    public void setVersion(Long version) { this.version = version; }19 20    public String getStatus() { return status; }21    public void setStatus(String status) { this.status = status; }22}
1DynamoDbEnhancedClient enhanced = DynamoDbEnhancedClient.create();2DynamoDbTable<Order> orders = enhanced.table("Orders", TableSchema.fromBean(Order.class));3 4Key key = Key.builder().partitionValue("ana").sortValue("2026-06-01").build();5 6// Strongly consistent GetItem7Order order = orders.getItem(GetItemEnhancedRequest.builder()8        .key(key).consistentRead(true).build());9if (order == null) return;10 11order.setStatus("SHIPPED");12try {13    orders.updateItem(order);    // succeeds only if version is unchanged14} catch (ConditionalCheckFailedException e) {15    // someone else updated it first: re-read, reapply, retry16}17 18// Query: Ana's June orders, in sort key order19orders.query(QueryConditional.sortBetween(20        Key.builder().partitionValue("ana").sortValue("2026-06-01").build(),21        Key.builder().partitionValue("ana").sortValue("2026-06-30").build()))22      .items()23      .forEach(o -> System.out.println(o.getOrderDate()));

Without the Enhanced Client, the plain DynamoDbClient takes attribute maps and the condition as a string:

1DynamoDbClient dynamo = DynamoDbClient.create();2 3dynamo.putItem(PutItemRequest.builder()4        .tableName("Orders")5        .item(Map.of(6                "customerId", AttributeValue.fromS("ana"),7                "orderDate", AttributeValue.fromS("2026-06-01"),8                "status", AttributeValue.fromS("PENDING")))9        .conditionExpression("attribute_not_exists(customerId)")10        .build());

In Spring Boot, Spring Cloud AWS offers a DynamoDbTemplate built on the same Enhanced Client.

Conditional writes for optimistic locking4 steps
Ana's card, each version0123๐Ÿ‘ฉShop worker Lu๐Ÿ‘จShop worker Bo
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • โšกServerless APIThe smallest useful backend: API Gateway, Lambda and DynamoDB.guided design

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Amazon DynamoDB, told the same way as the story.
  1. The shop wants every card that mentions a red scarf, and the names on the cards don't help. What happens?
  2. During a sale, every card is written under the name "Sale". The shop booked plenty of cards per second, yet the steward says to come back later. Why?
  3. The shop updates Ana's card, hears "got it", then immediately asks a quick question and sees the old version. Is something broken?
  4. Two shop workers both read version 3 of a card and both hand in changes marked "only if it still says version 3". What happens?
Answer every question to check.Passing marks Amazon DynamoDB as done.
Got the hang of Amazon DynamoDB? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜๏ธ AWS from zeroStep 8 of 12

โ† Previous on the path๐Ÿงบ Amazon SQS and SNSNext on the path โ†’๐Ÿ›๏ธ Amazon RDS and Aurora