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.
| Term | Meaning |
|---|---|
| Table | A collection of items, such as Orders |
| Item | One record, up to 400 KB, like a row |
| Attribute | A named value on an item: string, number, binary, boolean, list, map, set or null |
| Partition key | The required part of the primary key; DynamoDB hashes it to choose a partition |
| Sort key | Optional second part of the primary key; orders items that share a partition key |
| Partition | An 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.
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
GetItemreads one item by its full primary key.Queryneeds 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.Scanreads 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.
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-demand | Provisioned | |
|---|---|---|
| You pay for | Each read and write request | Read and write capacity units per second, reserved |
| Scaling | Automatic; can still throttle on a sudden jump past double the previous peak | You set capacity, optionally with auto scaling |
| Suits | Spiky or unknown traffic | Steady, 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 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) | |
|---|---|---|
| Key | Any partition key and sort key | Same partition key as the table, different sort key |
| When | Add or remove any time | Only when the table is created |
| Reads | Eventually consistent only | Eventually or strongly consistent |
| Capacity | Its own, separate from the table | Shares the table's |
| Limit | 20 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.
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).
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 {3private String customerId; // partition key4private String orderDate; // sort key5private String status;6private Long version;78@DynamoDbPartitionKey9public String getCustomerId() { return customerId; }10public void setCustomerId(String customerId) { this.customerId = customerId; }1112@DynamoDbSortKey13public String getOrderDate() { return orderDate; }14public void setOrderDate(String orderDate) { this.orderDate = orderDate; }1516@DynamoDbVersionAttribute17public Long getVersion() { return version; }18public void setVersion(Long version) { this.version = version; }1920public String getStatus() { return status; }21public void setStatus(String status) { this.status = status; }22}
1DynamoDbEnhancedClient enhanced = DynamoDbEnhancedClient.create();2DynamoDbTable<Order> orders = enhanced.table("Orders", TableSchema.fromBean(Order.class));34Key key = Key.builder().partitionValue("ana").sortValue("2026-06-01").build();56// Strongly consistent GetItem7Order order = orders.getItem(GetItemEnhancedRequest.builder()8.key(key).consistentRead(true).build());9if (order == null) return;1011order.setStatus("SHIPPED");12try {13orders.updateItem(order); // succeeds only if version is unchanged14} catch (ConditionalCheckFailedException e) {15// someone else updated it first: re-read, reapply, retry16}1718// Query: Ana's June orders, in sort key order19orders.query(QueryConditional.sortBetween(20Key.builder().partitionValue("ana").sortValue("2026-06-01").build(),21Key.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();23dynamo.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.