DynamoDB
Amazon DynamoDB is a fully managed NoSQL database: a key-value and document store that AWS runs for you. You create a table, define its key, and read and write items over HTTPS. There are no servers to size, no replicas to set up and no failover to configure, and performance stays in the single-digit milliseconds whether the table holds a gigabyte or a petabyte.
A few properties define it:
- Key-based access: every read and write goes through the primary key. Lookups by key and range queries within one partition key are fast; anything else is either an index you planned for or an expensive full scan.
- Horizontally partitioned by design: tables are split into partitions by a hash of the partition key and spread across many storage nodes. Capacity grows by adding partitions, so throughput and size have no practical ceiling as long as your keys spread the load.
- Managed and serverless: replication across three availability zones, backups, encryption and scaling are handled by AWS. You pay per request (on-demand) or for provisioned throughput.
- Tunable reads, conditional writes: reads are eventually consistent by default, with strongly consistent reads on request. Writes can be conditional, and transactions span up to 100 items.
DynamoDB comes up constantly in interviews because it's the standard answer for "store a lot of simple records and look them up by key, at any scale," and it's the commercial descendant of the ideas behind distributed key-value stores. It's also one of the easiest places for interviewers to probe: what's your partition key, what are your access patterns, what happens with a hot key, and how do you query by something that isn't the key?
The Data Model
A table holds items (rows), and each item is a set of attributes (columns). Apart from the key attributes, items in the same table can have completely different attributes. Items are limited to 400 KB, including attribute names.
The primary key comes in two forms:
- Partition key only (simple primary key): each item is identified by one attribute, like
user_id. Good for pure key-value lookups. - Partition key + sort key (composite primary key): items with the same partition key form an item collection, stored together and sorted by the sort key. This is what makes DynamoDB more than a hash map.
With a composite key you get range queries inside a partition:
Table: messages
partition key: chat_id
sort key: sent_at#message_id
Query: chat_id = "c_918" AND sort key BETWEEN "2026-11-29T00" AND "2026-11-29T23"
ScanIndexForward = false, Limit = 50
→ the 50 most recent messages in that chat on that day, in one request
There are three ways to read:
| Operation | What it does | Cost |
|---|---|---|
| GetItem / BatchGetItem | Fetch items by full primary key | Cheapest; reads only what you ask for |
| Query | Fetch items with one partition key, optionally a sort key condition (=, <, BETWEEN, begins_with) |
Reads only the matching range; pages of up to 1 MB |
| Scan | Read every item in the table (or index) | Reads everything; avoid on the request path |
A FilterExpression on a Query or Scan is applied after items are read, so you pay for everything read, not just what's returned. Filtering doesn't replace a good key.
The most important interview habit with DynamoDB is to list your access patterns first, then design keys to serve them. "Get a user's orders, newest first" tells you
PK = user_id, SK = order_date#order_id. If you pick keys before knowing the queries, you end up scanning.
Designing Keys and Single-Table Design
Because DynamoDB has no joins, you shape the data so each access pattern is one request. A common technique is single-table design: store several entity types in one table with generic key names and prefixed values, so related items share a partition and come back in one Query.
| PK | SK | Attributes |
|---|---|---|
USER#42 |
PROFILE |
name, email, plan |
USER#42 |
ORDER#2026-11-28#9001 |
total, status |
USER#42 |
ORDER#2026-11-29#9007 |
total, status |
ORDER#9007 |
ITEM#1 |
sku, qty, price |
ORDER#9007 |
ITEM#2 |
sku, qty, price |
- "Get user 42's profile and recent orders":
Query PK = USER#42, sorted newest first withScanIndexForward = false. - "Get only the orders":
Query PK = USER#42 AND begins_with(SK, "ORDER#"). - "Get the line items for order 9007":
Query PK = ORDER#9007.
The same trick handles many-to-many relationships with an adjacency list. To model users belonging to groups, write one item per membership with PK = GROUP#7, SK = USER#42, and add a GSI that swaps the keys (GSI_PK = USER#42, GSI_SK = GROUP#7). The table answers "members of group 7" and the GSI answers "groups user 42 is in," each as a single Query.
Pagination falls out of the sort key. A Query returns at most 1 MB per call along with a LastEvaluatedKey. Pass that back as ExclusiveStartKey to continue from where the previous page stopped. This is cursor-based pagination for free: it stays fast no matter how deep you page, unlike OFFSET in SQL, and you can hand the key to the client as an opaque cursor. What DynamoDB can't do cheaply is "jump to page 50" or "count the items," since both mean reading everything before them.
Single-table design is efficient but rigid: adding a new access pattern later can mean a new index or a data migration. Many teams use one table per entity with a few indexes instead, which is easier to understand. In an interview, either is fine as long as each of your access patterns maps to a GetItem or a Query.
Secondary Indexes
When you need to query by something other than the primary key, you add a secondary index.
| Global Secondary Index (GSI) | Local Secondary Index (LSI) | |
|---|---|---|
| Key | Any partition key and sort key | Same partition key, different sort key |
| When created | Any time | Only at table creation |
| Consistency | Eventually consistent only | Strong or eventual |
| Capacity | Its own throughput | Shares the table's |
| Size limit | None | 10 GB per partition key value (item collection) |
| How many | Up to 20 per table (default quota) | Up to 5 |
A GSI is really a second table that DynamoDB keeps in sync for you, asynchronously. You choose which attributes it projects (copies): keys only, specific attributes, or all of them. If an item doesn't have the GSI's key attributes, it isn't in the index, which makes sparse indexes a useful trick: put a pending_review attribute only on items that need review, index on it, and the GSI contains only those items.
Two GSI details are worth knowing:
- GSI keys don't have to be unique. Many items can share a GSI key, so "all orders with status
SHIPPED" is a valid GSI query (though a low-cardinality key like status makes a hot GSI partition; see below). - A throttled GSI throttles the base table. If a GSI can't keep up with writes, DynamoDB throttles writes to the table itself, so size GSI capacity for the table's write rate.
If your interviewer asks "how do you look up a user by email?" in a table keyed by
user_id, the answer is a GSI onEMAIL#[email protected]in the same transaction, with a condition that it doesn't already exist.
Architecture
But what is actually happening under the hood? AWS has published a fair amount about DynamoDB's design, and the broad shape is worth knowing.
- Request routers receive every API call. They authenticate the request, look up which partition holds the key (from partition metadata, cached aggressively), and forward the request to that partition's storage nodes.
- Each table is split into partitions by a hash of the partition key. A partition holds up to roughly 10 GB of data.
- Each partition is a replication group of three replicas in three availability zones. One replica is the leader, elected with Multi-Paxos.
- Writes go to the leader, which writes them to its log and replicates the log entry to its peers. The write is acknowledged once a quorum (two of the three replicas, counting the leader) has durably logged it.
- Strongly consistent reads are served by the leader. Eventually consistent reads can be served by any replica, which might be slightly behind, usually by well under a second.
- When a partition grows past its size limit or sustains too much traffic, DynamoDB splits it in the background, without downtime.
Each storage node keeps a B-tree of items plus a replication log, and periodically ships logs to S3, which is what powers point-in-time recovery.
This is why the rules of DynamoDB look the way they do. A request for one partition key goes to one replication group, so it's fast and predictable. A request that doesn't name the partition key has to visit every partition, so it's a Scan.
Capacity and Hot Partitions
DynamoDB meters work in capacity units:
- 1 write capacity unit (WCU) = one write per second of an item up to 1 KB. A 3.5 KB item costs 4 WCUs per write.
- 1 read capacity unit (RCU) = one strongly consistent read per second of up to 4 KB, or two eventually consistent reads. A 6 KB item costs 2 RCUs strongly consistent, 1 eventually consistent.
- Transactional reads and writes cost twice as much.
There are two billing modes. On-demand charges per request and adapts to traffic automatically, which suits spiky or unpredictable workloads (it accommodates up to double your previous peak instantly and scales further as traffic keeps growing). Provisioned lets you set RCUs and WCUs, optionally with auto scaling, and is cheaper for steady, predictable traffic.
The number that matters most in interviews is the per-partition limit: a single partition serves at most about 3,000 RCUs and 1,000 WCUs per second. All traffic for one partition key lands on one partition, so one key can handle roughly 1,000 writes per second of 1 KB items, no matter how much capacity the table has overall.
Let's do the math for a likes counter. A viral post gets 20,000 likes per second. If every like increments a counter item with PK = post_id, that's 20,000 WCUs on one key, twenty times what one partition can take. The table could have a million WCUs provisioned and it would still throttle.
DynamoDB softens hot spots in a few ways:
- Burst capacity: unused capacity from the last five minutes can be spent on short spikes.
- Adaptive capacity: the table's capacity is shifted toward busy partitions automatically, and a partition with a sustained hot range of keys can be split so that range is spread out ("split for heat").
None of these help with a single hot item, because a split can't divide one key. For that, you change the design:
- Write sharding: spread one logical key over N physical keys by appending a suffix,
post_42#0throughpost_42#19. Each like goes to a random shard, and readers sum all 20 shards (or a background job does and caches the total). - Aggregate before writing: buffer increments in memory, Kinesis or Redis, and write a combined increment every second.
- Cache hot reads with DAX or Redis.
import random
shard = random.randint(0, 19)
table.update_item(
Key={"pk": f"post_42#{shard}", "sk": "likes"},
UpdateExpression="ADD like_count :one",
ExpressionAttributeValues={":one": 1},
)
When you put DynamoDB in a design, say your partition key out loud and check it against the 1,000 WCU and 3,000 RCU per-partition limits. "Celebrity" keys, low-cardinality GSI keys (status, country, date) and time-based partition keys (everything written today lands on
2026-11-29) are the classic mistakes interviewers look for.
Consistency, Conditional Writes and Transactions
Read Consistency
- Eventually consistent reads (default) are half the price and may miss a write from the last moment.
- Strongly consistent reads (
ConsistentRead=true) return the latest committed write. They're served by the partition leader, are not available on GSIs, and aren't available across regions in a standard global table.
Conditional Writes
Every write can carry a ConditionExpression that DynamoDB checks atomically against the current item. This is the building block for most correctness guarantees:
# Create only if absent (e.g. claim a short URL code, register a username)
table.put_item(
Item={"pk": "CODE#x7Kq2", "long_url": url},
ConditionExpression="attribute_not_exists(pk)",
)
# Optimistic locking: update only if nobody changed it since we read version 7
table.update_item(
Key={"pk": "ACCOUNT#42"},
UpdateExpression="SET balance = :b, version = :new",
ConditionExpression="version = :old",
ExpressionAttributeValues={":b": 400, ":old": 7, ":new": 8},
)
# Decrement stock only if some is left
table.update_item(
Key={"pk": "SKU#123"},
UpdateExpression="SET stock = stock - :one",
ConditionExpression="stock >= :one",
ExpressionAttributeValues={":one": 1},
)
A failed condition raises ConditionalCheckFailedException, which your code treats as "someone else won." Conditional writes also make DynamoDB a reasonable backing store for leases and locks: write a lock item with an owner and expiry, with a condition that it doesn't exist or has expired. See distributed locks for why you'd still want fencing tokens.
Transactions
TransactWriteItems and TransactGetItems group up to 100 items (4 MB total) across any tables in one region into an all-or-nothing, serializable operation. Each action can carry its own condition, and if any condition fails, nothing is written.
TransactWriteItems:
1. Update ACCOUNT#alice SET balance = balance - 50 IF balance >= 50
2. Update ACCOUNT#bob SET balance = balance + 50
3. Put TRANSFER#t_771 {...} IF attribute_not_exists(pk)
Transactions cost double, and concurrent transactions touching the same items cancel each other rather than wait, so they don't fit hot items. Passing a ClientRequestToken makes a transaction idempotent for 10 minutes, so a retry after a timeout doesn't apply it twice.
Streams and Change Data Capture
DynamoDB Streams records every item-level change (insert, modify, remove), optionally with the item's old and new images, and keeps it for 24 hours. Changes to a given item appear in the order they happened, and each change appears in the stream exactly once.
Streams turn DynamoDB into the source of an event-driven system:
- Lambda triggers that react to changes: send a notification when an order ships, update an aggregate.
- Keeping other stores in sync: index items into OpenSearch for full-text search, update a cache, or feed a data lake.
- A built-in outbox: since the stream is written atomically with the item, writing the item is publishing the event, so there are no dual-write bugs.
- Cross-region replication: global tables are built on the same change capture.
For longer retention or more consumers, you can stream changes into Kinesis Data Streams instead.
Notable Features
- TTL: set an attribute with an expiry timestamp, and DynamoDB deletes the item for free some time after it expires (typically within a few days, so filter out expired items on read if exact expiry matters). Deletions appear in Streams, which is handy for "do something when a session or hold expires."
- DAX (DynamoDB Accelerator): an in-memory, write-through cache in front of a table that serves eventually consistent reads in microseconds. Good for read-heavy hot items; it doesn't help writes.
- Global tables: multi-region, multi-active replication. Every region accepts writes, changes replicate asynchronously (typically within about a second), and conflicting concurrent writes to the same item resolve with last writer wins. AWS has also added a multi-region strongly consistent mode for workloads that can pay the extra write latency.
- Backups: continuous point-in-time recovery (up to 35 days), on-demand backups, and exports to S3 for analytics.
- PartiQL: a SQL-like syntax for the same operations. It doesn't add joins; a
SELECTwithout the key is still a Scan.
Limits to Remember
| Limit | Value |
|---|---|
| Item size | 400 KB |
| Query / Scan page | 1 MB of data read per request |
| Per-partition throughput | ~3,000 RCU and ~1,000 WCU per second |
| Transaction | 100 items, 4 MB |
| GSIs / LSIs | 20 (default quota) / 5 per table |
| LSI item collection | 10 GB per partition key value |
| Streams retention | 24 hours |
For large objects like images or documents, store the bytes in S3 and keep the S3 key and metadata in DynamoDB.
DynamoDB vs Other Options
| DynamoDB | Cassandra | Postgres | |
|---|---|---|---|
| Operations | Fully managed by AWS | You run it (or use a managed service) | Managed or self-run |
| Scale-out writes | Yes, automatic | Yes, add nodes | No, single primary |
| Query model | Key lookups, range within partition, indexes | Same, via CQL | Full SQL, joins, ad-hoc queries |
| Consistency | Strong or eventual per read, conditional writes, transactions | Tunable per query, lightweight transactions | Strong, full ACID |
| Cost model | Per request or provisioned throughput | Hardware | Hardware or instance |
| Lock-in | AWS only | Open source | Open source |
DynamoDB in an Interview
When to Use It
- Key-value and simple query workloads at large or unpredictable scale: user sessions, shopping carts, URL mappings, device state, profiles, idempotency keys, rate-limit or lock records.
- Write-heavy workloads with well-distributed keys: event logs per user, chat messages per conversation, IoT readings per device.
- When you want no operations: no capacity planning beyond the key design, built-in multi-AZ durability, easy multi-region with global tables.
- Event-driven designs where Streams can drive downstream work.
Knowing Its Limitations
- You must know your access patterns. Ad-hoc queries, joins and aggregations aren't supported. Analytics belong in a warehouse fed by Streams or S3 exports.
- Hot keys throttle. One partition key tops out around 1,000 writes per second. Celebrity counters need write sharding or aggregation.
- GSIs are eventually consistent and can't enforce uniqueness.
- Item size is capped at 400 KB. Big documents and media go to S3.
- Cost can surprise you. Scans, large items, many GSIs and transactional writes multiply the bill, and on-demand pricing is expensive for steady high throughput.
- AWS only. If the interviewer wants a cloud-neutral design, name Cassandra or ScyllaDB, which have a similar data model.
Questions You Might Get
- "What's your partition key, and is it going to be hot?" Name it, estimate the peak traffic per key, compare it with the per-partition limits, and describe write sharding if needed.
- "How do you query orders by status?" A GSI on status, but status has few values, so make the GSI key
status#shardorstatus#dateto spread it. - "How do you make sure a username is unique?" A conditional put on a
USERNAME#nameitem, in the same transaction as the user item. - "How do you keep search in sync?" Streams to a Lambda that indexes changes into OpenSearch, which is eventually consistent but has no dual-write gap.
- "Two people update the same item at once." Conditional writes with a version attribute (optimistic locking), or atomic update expressions like
ADDthat don't need a read first.
Summary
DynamoDB is a managed, partitioned key-value and document store. Items are addressed by a partition key, optionally with a sort key that enables range queries within an item collection. Under the hood, each partition is a three-way replicated group across availability zones with a Multi-Paxos leader, and the table splits partitions automatically as data and traffic grow.
To use it well, design keys from your access patterns, add GSIs for other lookups, and check every key against the per-partition throughput limits. Conditional writes, transactions and Streams cover correctness and event-driven needs, while TTL, DAX and global tables round out the feature set. In an interview, DynamoDB is a strong choice for simple, massive, key-based workloads, as long as you can say exactly how each query maps to a key and how you'll handle the hot ones.