How it works
A table contains items identified by either a partition key alone or a composite primary key consisting of a partition key and sort key. DynamoDB hashes the partition-key value to place data on physical partitions. Items with the same partition-key value form an item collection, with sort keys supporting ordered retrieval and range conditions.
DynamoDB manages physical partitions and replicates data across multiple Availability Zones within a Region. It adds or splits partitions as storage and throughput needs change. Describe this documented behavior rather than assuming DynamoDB implements every mechanism from the original Amazon Dynamo paper, such as client-visible vector clocks or configurable read and write quorums.
GetItem reads a primary key, while Query requires one partition-key value and optionally a sort-key condition. Scan walks a table or index and is usually unsuitable for frequent request-path lookups. Query and Scan filters run after items are read, so filtering does not avoid the read work or capacity consumed.
Secondary indexes provide additional access paths. A global secondary index, or GSI, can use different partition and sort keys and is updated asynchronously. A local secondary index, or LSI, keeps the table's partition key but offers a different sort key; it must be defined when the table is created. Index projections trade storage and write cost against follow-up reads.
Single-item writes are atomic, and condition expressions allow compare-and-set updates or create-if-absent operations. Transactions coordinate bounded sets of items within one account and Region on supported tables. DynamoDB Streams exposes item-level changes for asynchronous consumers, while global tables replicate data across Regions with consistency and conflict behavior determined by the selected mode.
What it gives you in a design
- Access-pattern-driven data modeling
- Composite keys support patterns such as all messages in a conversation ordered by sequence, or all orders for a customer ordered by time. Denormalization and sometimes single-table design replace joins, but single-table design is an option rather than a requirement.
- Secondary indexes
- GSIs support alternate lookup keys and sparse indexes that contain only items with the required index attributes. Each index adds storage, write amplification, and another key distribution to evaluate for hot spots.
- Conditional writes and transactions
- Condition expressions support optimistic concurrency, uniqueness by primary key, inventory checks, and idempotency records. Transactions provide all-or-nothing changes across multiple items, at additional capacity cost and with contention-related failures that callers must handle.
- Read consistency choices
- Table and LSI reads can request strong consistency within a Region; otherwise reads are eventually consistent by default. GSI reads are eventually consistent, so a GSI lookup should not be the final authority for an inventory claim or uniqueness decision.
- Managed capacity
- On-demand mode manages request capacity, while provisioned mode allocates read and write capacity and can use auto scaling. Both still require attention to quotas, sudden traffic changes, hot partitions, and retry behavior.
- Change streams and expiration
- DynamoDB Streams can drive materialized views, notifications, and downstream indexing, with consumers designed for duplicate processing. TTL asynchronously removes expired items; it is storage cleanup, not a precise timer or an authorization check.
- Multi-Region global tables
- Global tables support multi-Region eventual consistency, or MREC, and multi-Region strong consistency, or MRSC, in supported configurations. MREC uses asynchronous replication and last-writer-wins conflict resolution; MRSC has different latency, availability, feature, and Region constraints.
Scaling, replication and failure
Choose partition keys that spread both data and traffic. A large tenant, popular post, or shared counter can dominate one key even when total table capacity is ample. Adaptive capacity and partition splitting help with uneven workloads, but they do not make a single hot item infinitely writable.
Write sharding distributes a logical workload across multiple partition-key values, such as POST#123#SHARD#0 through POST#123#SHARD#15. The trade-off is read fan-out, aggregation work, and more complicated pagination. Time buckets can bound growing collections, but a current-time bucket alone can still concentrate all new writes.
Regional replication provides resilience to infrastructure failures, but clients must still handle throttling, transient errors, and uncertain write outcomes. Use bounded exponential backoff with jitter, retry unprocessed batch items, and make retried business operations idempotent. A timed-out counter increment may already have succeeded, so blindly repeating it can overcount.
For multi-Region designs, state the global-table consistency mode explicitly. Under MREC, a locally strong read does not make replication globally synchronous, and conflicting regional writes can overwrite one another. Transactions are not replicated as an atomic cross-Region unit under MREC; MRSC has separate restrictions, including no transaction API support.
Limits and defaults worth knowing
Check the current documentation before relying on an exact value; many of these are configurable.
| Maximum item size | 400 KB per item, including attribute names and values. Store large media or documents in object storage and keep references in DynamoDB. |
|---|---|
| Query and Scan page size | Each request evaluates up to 1 MB of data before applying a filter, or stops earlier at a configured item limit. Continue with LastEvaluatedKey, even if a filtered page contains no returned items. |
| Transaction size | A transaction can include up to 100 distinct items with an aggregate size of up to 4 MB, within one account and Region. Multiple actions cannot target the same item in one transaction. |
| Physical partition throughput | AWS documents physical partition limits of 3,000 read capacity units and 1,000 write capacity units per second. These are capacity units, not universal request-per-second guarantees; item size and operation type affect consumption. |
| DynamoDB Streams retention | Stream records are retained for 24 hours. Consumers that fall behind beyond retention need a separate recovery or rebuild strategy. |
| TTL deletion timing | Expired items are typically deleted within a few days, not immediately at expiration. Reads and conditional writes must enforce logical expiry when correctness depends on it. |
Use it when
- The main request paths can be expressed as primary-key lookups or bounded queries against known partition keys.
- You need managed regional replication and horizontal scaling without operating database shards yourself.
- The data model can tolerate denormalization and asynchronous propagation to alternate views or indexes.
- Correctness can usually be enforced with single-item conditional writes or small, bounded transactions.
- You need a durable source of item changes for asynchronous projections, with a recovery plan for stream retention limits.
Avoid it when
- The core workload requires changing ad hoc queries, joins, or broad aggregations over operational data.
- A single record must sustain a concentrated write workload that cannot be sharded, buffered, or otherwise redesigned.
- Large values dominate the workload, or items routinely approach or exceed the 400 KB limit.
- You require unrestricted cross-Region transactions or assume every Region can independently accept conflicting writes while preserving a global invariant.
What interviewers ask about it
Follow-ups you can expect once DynamoDB is on your whiteboard, and the core of a strong answer.
- How would you choose the partition key and sort key?
- Start with the exact reads and writes, including ordering, pagination, and expected traffic skew. For chat history, a conversation key plus a sequence-based sort key supports ordered queries, but very busy conversations may need sharding or bucketing with explicit read fan-out.
- What happens when one key becomes hot?
- Separate a hot item from a hot collection: a single counter cannot be split transparently into independently writable values. Depending on the invariant, use caching, write sharding, batching, admission control, or a different coordination path, and explain the resulting freshness or aggregation trade-off.
- Can DynamoDB prevent overselling inventory?
- Yes, a conditional update can decrement inventory only if enough remains, and a transaction can atomically combine that update with a reservation or idempotency record. Retrying after an uncertain response must not create another reservation, and external payment operations still need a separate workflow.
- Can I read a GSI immediately after writing an item?
- You can query it, but the new item may not yet appear because GSIs are eventually consistent. If the next operation requires the authoritative result, read the base-table key with strong consistency or carry the known write result forward.
- Does on-demand capacity eliminate capacity planning?
- No, it removes provisioned-capacity management but not partition limits, quotas, traffic-ramp considerations, or cost planning. Estimate item sizes, index writes, read consistency, and peak key-level traffic, then plan throttling and retries.
- How would you use DynamoDB Streams reliably?
- Make downstream effects idempotent because processing can repeat, and rely on per-item ordering rather than a global order across the table. Monitor consumer lag against the 24-hour retention window and define how to rebuild a projection or recover missed changes.
Common mistakes
- Claiming DynamoDB exposes the same architecture and tunable quorum mechanisms as the original Dynamo paper.
- Choosing a partition key by entity name alone without estimating skew, item growth, or the read fan-out introduced by sharding.
- Using a Scan or a selective filter as though it were an efficient indexed lookup, or assuming a new GSI entry is immediately visible.
- Treating TTL as an exact lease release mechanism, or treating regional transactions and locally strong reads as global correctness guarantees.
Alternatives
- PostgreSQL or Amazon Aurora
- Prefer these when relational constraints, joins, evolving query patterns, and multi-row transactional workflows matter more than key-based horizontal scaling.
- Apache Cassandra
- Consider it for partition-oriented workloads when deployment control, self-managed multi-datacenter operation, or tunable consistency justify the additional operational work.
- Google Cloud Bigtable
- Consider it for large ordered-key or wide-column workloads, especially time-series and analytical serving patterns where row-key range access is central.
- Redis
- Prefer it for an in-memory cache or specialized low-latency data structures when memory cost and the chosen persistence and failover guarantees are acceptable.
Where it comes up
Interview questions where DynamoDB is a natural fit, and why.
- Design a URL shortener like BitlyA short-code-keyed table supports direct redirect lookups, while conditional creation prevents code collisions and caching absorbs popular links.
- Design a chat app like WhatsAppConversation-partitioned message storage illustrates ordered queries, cursor pagination, and the sharding trade-offs for high-volume conversations.
- Design a ticket booking system like TicketmasterConditional writes and bounded transactions can protect seat reservations, while logical expiry and idempotency handle hold and payment races.
- Design Facebook likes at scalePer-user like state and sharded aggregates expose the difference between authoritative conditional updates and eventually consistent counts.
- Design a distributed job schedulerDurable job state, conditional lease acquisition, and time-bucketed indexes fit DynamoDB, but TTL cannot serve as a precise scheduling mechanism.
- Design a distributed key-value storeDynamoDB provides a concrete comparison for managed partitioning, replication, consistency choices, and hot-key behavior without assuming its private implementation.
Questions people ask
Is DynamoDB a key-value database or a document database?
It supports both models: items are addressed by keys, and their attributes can include nested maps and lists. Document support does not provide relational joins or automatically index arbitrary nested fields. Efficient reads still depend on primary keys and explicitly designed indexes.
Is DynamoDB strongly consistent or eventually consistent?
It depends on the operation and configuration. Table and LSI reads default to eventual consistency but can request strong consistency; GSI reads are eventually consistent. Global tables separately offer MREC and MRSC modes, so a multi-Region answer must specify which mode is being used.
How do you model DynamoDB for a system design interview?
List access patterns first, then show primary keys, sort keys, and only the indexes those patterns require. Walk through the busiest read and write, identify potential hot keys, and explain conditional writes, consistency, and pagination. Do not assume single-table design is necessary unless colocating entities actually simplifies those access patterns.