PrepStack › Databases › Cassandra & DynamoDB
Cassandra & DynamoDB interview cheat sheet
Wide-column and key-value design, partitioning, tunable consistency and capacity
Interviewers use Cassandra and DynamoDB to test whether you can design for scale without joins. Expect questions on how data is spread (partition keys, consistent hashing), how writes stay fast (commit log, memtable, SSTables), what consistency you get (quorums, R + W > N, eventual vs strong reads) and how to model tables from the queries backwards. For DynamoDB, be ready to do RCU/WCU math and explain GSIs, single-table design and hot partitions. Read the 15-minute list, then quiz yourself section by section.
15-minute revision
- Both are partitioned, replicated, masterless-style stores built for huge write throughput and predictable latency. Neither does joins; you model per query and denormalize.
- Cassandra is a wide-column store: a partition key picks the node, and clustering columns sort rows inside that partition. DynamoDB is key-value/document: partition key (+ optional sort key) per item.
- Cassandra places data with consistent hashing on a token ring (Murmur3). Vnodes (
num_tokens, default 16 since 4.0) give each node many small ranges for even load and faster rebuilds. - Replication factor (RF) = copies per DC. Use
NetworkTopologyStrategyin production;SimpleStrategyis for single-DC dev only. A snitch tells Cassandra the rack/DC layout; gossip spreads node state. - Any node can be the coordinator. It forwards the request to replicas and waits for as many acks as the consistency level asks for.
- Write path: commit log (durability) → memtable (memory) → ack. Memtables flush to immutable SSTables; compaction merges them later. Writes never read before writing.
- Read path: memtable + SSTables, filtered by per-SSTable bloom filters and partition indexes, merged by newest timestamp (last write wins).
- Strong consistency rule:
R + W > RF.QUORUM=floor(RF/2) + 1; with RF 3, QUORUM writes + QUORUM reads are strong and tolerate one down replica. UseLOCAL_QUORUMin multi-DC. - Repair trio: hinted handoff (store missed writes for a down node, default 3h window), read repair (fix replicas seen to differ during a read), anti-entropy repair (
nodetool repair, Merkle trees). Run repair withingc_grace_seconds(default 10 days). - Deletes write tombstones. Too many tombstones slow reads (warn at 1,000, fail at 100,000 per query by default). Missing repair before gc_grace expires can resurrect deleted data.
- Lightweight transactions (
IF NOT EXISTS,IF col = x) use Paxos, cost about 4 round trips and give linearizable single-partition updates. Cassandra 6.0 adds Accord multi-partition ACID transactions; 5.0 does not have it. - Avoid hot and huge partitions: add a time bucket or shard suffix to the partition key; keep partitions well under ~100 MB.
ALLOW FILTERINGon a big table is a red flag. - DynamoDB capacity: 1 RCU = one strongly consistent read/s of up to 4 KB (or two eventual reads). 1 WCU = one write/s of up to 1 KB. Transactions cost 2×. Max item size is 400 KB.
- LSI: same partition key, different sort key, created with the table, can be strongly consistent, 10 GB per item collection. GSI: any keys, added any time, eventually consistent only, own capacity.
- Modes: on-demand (pay per request, spiky or unknown load) vs provisioned (+ auto scaling, steady load, cheaper at high utilization). One partition tops out at about 3,000 RCU / 1,000 WCU.
- DynamoDB extras: Streams (24h change log → Lambda), TTL (free expiry deletes, within a few days), transactions (up to 100 items / 4 MB), DAX (microsecond cache), global tables (multi-Region; MREC default, MRSC for strong consistency).
Foundations
Wide-column vs key-value & the Dynamo heritage
Cassandra stores sorted rows inside partitions; DynamoDB stores items by key; both descend from Amazon's Dynamo ideas.
- Key-value store: you get and put a value by key. DynamoDB extends this into a key-value + document model: each item is a set of typed attributes (strings, numbers, maps, lists, sets) and only the key is fixed.
- Wide-column store (Cassandra, HBase, Bigtable): a table has a partition key that groups many rows, and clustering columns that keep those rows sorted on disk. Think of it as a distributed
Map<partitionKey, SortedMap<clusteringKey, row>>. - Cassandra (Facebook, 2008, now Apache) mixes Dynamo's distribution (consistent hashing, gossip, hinted handoff, tunable quorums) with Bigtable's storage engine (memtable + SSTables + compaction).
- The Dynamo paper (Amazon, 2007) described a leaderless, always-writeable key-value store using consistent hashing, sloppy quorums, vector clocks and Merkle-tree repair. DynamoDB (2012) is a managed service inspired by it, but internally it uses leader-based replication per partition with Paxos, not the paper's leaderless design.
- In CAP terms both default to AP behaviour (available during partitions, eventually consistent), but you can ask for stronger consistency per request: Cassandra via consistency levels, DynamoDB via
ConsistentRead. - Pick these stores for massive scale, high write rates, simple known access patterns and multi-region availability. Avoid them for ad-hoc queries, reporting and heavy multi-row transactions.
Interview questions
- What is a wide-column store?
- How is Cassandra related to the Dynamo paper and Bigtable?
- Is DynamoDB the same as the Dynamo described in Amazon's 2007 paper?
Ring, consistent hashing & vnodes
The partition key is hashed to a token; each node owns ranges of the token ring, so adding a node moves only a slice of data.
- The partitioner hashes the partition key into a token. The default
Murmur3Partitionerproduces 64-bit tokens from −2^63 to 2^63−1, arranged as a ring. - Each node owns the range of tokens up to its own token. A key belongs to the first node clockwise from its token; replicas are the next distinct nodes clockwise (adjusted for racks/DCs).
- Consistent hashing means adding or removing a node only moves the keys in the affected ranges. With plain
hash % N, changing N moves most keys. - Virtual nodes (vnodes): each physical node holds many tokens (
num_tokens). This spreads load evenly, lets a new node stream from many peers at once, and avoids manual token assignment. Defaultnum_tokensis 16 since Cassandra 4.0 (it was 256), paired with a smarter token allocation algorithm. - Data is spread by partition, not by row. All rows of one partition live on the same replicas, which is why partition key choice matters so much.
- DynamoDB does the same idea internally: it hashes the partition key to pick a physical partition, and splits partitions automatically as data or traffic grows.
Interview questions
- What is consistent hashing and why does Cassandra use it?
- What are vnodes and what problem do they solve?
- What is a token and which partitioner is the default?
Replication, gossip, snitch & coordinator
RF copies per data center, placed by the replication strategy and snitch; any node can coordinate a request.
- Replication factor (RF) is set per keyspace and per DC. RF 3 is the usual production choice: it survives one replica down at QUORUM.
- SimpleStrategy places replicas on the next nodes clockwise and ignores racks and DCs; use it only for single-DC test clusters. NetworkTopologyStrategy sets RF per DC and spreads replicas across racks.
- The snitch tells each node which rack and DC every node is in.
GossipingPropertyFileSnitch(each node reads its own rack/DC from a file and gossips it) is the common production choice; cloud-specific snitches exist for AWS, GCP and Azure. - Gossip is a peer-to-peer protocol: every second each node exchanges state with up to three others. It spreads membership, liveness, schema versions and load. The phi accrual failure detector turns heartbeat gaps into an up/down suspicion level.
- Seed nodes are just contact points for new nodes to join gossip. They are not masters, and there is no single point of failure.
- The coordinator is whichever node the client talked to. It finds the replicas for the token, sends them the request, waits for the number of responses required by the consistency level, and replies.
Interview questions
- Difference between SimpleStrategy and NetworkTopologyStrategy?
- What does the snitch do?
- How does gossip work and what are seed nodes?
Cassandra storage engine
Write path: commit log, memtable, SSTables
Append to the commit log, update the memtable, ack; later flush to immutable SSTables. No read-before-write.
- Each replica first appends the mutation to the commit log on disk for crash recovery. Sequential appends are cheap.
- Then it writes into the memtable, an in-memory sorted structure per table. Cassandra 5.0 adds a trie memtable that uses less memory and GC.
- The replica acks the coordinator. The write is now durable (subject to the
commitlog_syncsetting,periodicby default) and readable. - When a memtable is full or old, it is flushed to a new SSTable (Sorted String Table): an immutable file set with data, partition index, bloom filter, compression info and statistics. The matching commit log segments are then freed.
- Because SSTables are immutable, updates and deletes are just newer writes (with timestamps or tombstones). There is no read-before-write, so an
INSERTand anUPDATEare both upserts. - Many SSTables pile up over time, so background compaction merges them, keeps the newest version of each cell and drops expired tombstones.
Interview questions
- Walk me through Cassandra's write path.
- Why are Cassandra writes so fast?
- What is the difference between INSERT and UPDATE in Cassandra?
Compaction strategies: STCS, LCS, TWCS, UCS
Compaction merges SSTables; the strategy trades write amplification against read amplification and disk space.
- Compaction merges SSTables, keeps only the newest version of each cell (by timestamp), removes data shadowed by tombstones and drops tombstones older than
gc_grace_seconds. - STCS (Size-Tiered): merges SSTables of similar size. Low write amplification, good for write-heavy loads. Downsides: a partition can be spread over many SSTables (slower reads), and a big compaction may temporarily need lots of free disk.
- LCS (Leveled): SSTables are organised in levels of small, non-overlapping files; each level is about 10× bigger. Most reads touch one SSTable. Higher write amplification, so best for read-heavy, update-heavy tables.
- TWCS (Time-Window): groups SSTables by write time window (for example 1 day) and never mixes windows. Ideal for time series with TTL: whole old SSTables expire and are dropped cheaply. Avoid out-of-order writes and explicit deletes.
- UCS (Unified Compaction Strategy), new in Cassandra 5.0, uses a density-based sharded design with a tunable scaling parameter, so one strategy can behave like STCS (tiered) or LCS (leveled) and can be retuned without rewriting data. It is the recommended choice for new tables.
- Watch
nodetool compactionstatsfor pending compactions. A growing backlog means reads touch more SSTables and latency rises.
Interview questions
- Why does Cassandra need compaction?
- STCS vs LCS: when do you choose each?
- Why is TWCS a good fit for time-series data?
- What is UCS in Cassandra 5.0?
Read path: bloom filters, indexes & caches
Check memtable and the SSTables that might hold the partition, then merge cells by timestamp.
- The coordinator sends a full data read to the closest replica and digest reads (hashes) to the others needed for the consistency level. If digests disagree, it fetches full data and runs read repair.
- On each replica: check the row cache (off by default), then the memtable, then each SSTable whose bloom filter says the partition might be there.
- A bloom filter is a small in-memory bit array per SSTable. It can say "definitely not here" or "maybe here" (false positives, never false negatives). Tune with
bloom_filter_fp_chance(default 0.01; LCS tables default to 0.1). - For SSTables that pass: the key cache (on by default) or the partition index finds the partition's byte offset; compression offsets map it to the compressed chunk. Cassandra 5.0's trie-indexed SSTables (BTI format) make this lookup faster and smaller.
- Rows from all sources are merged by write timestamp (last write wins per cell), tombstones hide older data, and the result goes back to the coordinator.
- Reads are more expensive than writes. Keep the number of SSTables per read low (compaction) and keep partitions small.
Interview questions
- Walk me through Cassandra's read path.
- What is a bloom filter and why does Cassandra use it?
- Why are reads slower than writes in Cassandra?
Consistency & repair
Tunable consistency & R + W > N
Choose per request how many replicas must answer; overlapping read and write sets give strong consistency.
- The consistency level (CL) says how many replicas must acknowledge a write or answer a read before the coordinator replies. Writes are still sent to all replicas.
- Common levels:
ONE,TWO,THREE,QUORUM(majority of all replicas across DCs),LOCAL_QUORUM(majority in the coordinator's DC),EACH_QUORUM(majority in every DC, writes),ALL,LOCAL_ONE, andANY(writes only; a hint is enough). - Quorum =
floor(RF / 2) + 1. With RF 3, quorum is 2. - If R + W > RF, every read set overlaps every write set, so a read sees the latest acknowledged write.
QUORUM/QUORUMis the classic choice.ONE/ONEis fastest but eventually consistent. - Use
LOCAL_QUORUMfor multi-DC apps: strong within the local DC without paying cross-DC latency. PlainQUORUMacross DCs needs replicas in more than one DC. - Availability trade-off: higher CL means fewer node failures tolerated.
ALLfails if any replica is down. - Serial levels
SERIAL/LOCAL_SERIALare used for the Paxos phase of lightweight transactions.
Interview questions
- Explain R + W > N.
- QUORUM vs LOCAL_QUORUM?
- A client wrote at ONE and immediately read at ONE but got old data. Why?
- Does a QUORUM write that times out mean the write failed?
Hinted handoff, read repair & anti-entropy
Three layers keep replicas in sync: hints for short outages, read repair on reads, and full repair with Merkle trees.
- Hinted handoff: if a replica is down during a write, the coordinator stores a hint and replays it when the node returns. Hints are kept only for
max_hint_window(default 3 hours); a longer outage needs repair. - Hints help availability, but a hint does not count towards the consistency level (except with
ANY). - Read repair: when a read at CL > ONE sees replicas disagree, the coordinator writes the newest data to the stale replicas before answering (blocking read repair). The old background
read_repair_chanceoption was removed in Cassandra 4.0. - Anti-entropy repair (
nodetool repair) compares replicas with Merkle trees (hash trees over token ranges) and streams only the ranges that differ. - Incremental repair only repairs data written since the last repair (SSTables are marked repaired). Full repair checks everything. Use
-pr(primary range) to avoid repairing the same range on every replica. - Rule: repair every node at least once every
gc_grace_seconds(default 10 days), or deleted data can come back. Tools like Cassandra Reaper schedule this.
Interview questions
- What is hinted handoff?
- What is read repair?
- How does anti-entropy repair use Merkle trees?
- A node was down for 2 days. What do you do when it comes back?
Tombstones, TTL & gc_grace_seconds
Deletes are written as markers; they must outlive repair or deleted data can resurrect, and too many slow reads.
- A delete writes a tombstone: a marker with a timestamp that hides older data. It cannot delete data in place because SSTables are immutable and other replicas must learn about the delete.
- Tombstone kinds: cell, row, range (delete a slice of clustering keys), partition, and TTL expiry. Setting a column to
nullalso writes a tombstone. - Compaction can drop a tombstone only after
gc_grace_seconds(default 864000 = 10 days) and only when it no longer shadows data in other SSTables. - Zombie data: if a replica missed the delete and the tombstone is purged elsewhere before repair, the old value on that replica wins during repair and comes back. Hence repair within gc_grace.
- Reads must scan tombstones. Defaults: warn at 1,000 and fail at 100,000 tombstones per query (
tombstone_warn_threshold,tombstone_failure_threshold). - Common causes: queue-like tables (insert then delete), inserting
nullvalues from drivers, frequent collection overwrites, and range deletes inside huge partitions.
Interview questions
- What is a tombstone in Cassandra?
- What is gc_grace_seconds and why does it matter?
- A query started failing with TombstoneOverwhelmingException. How do you fix it?
Lightweight transactions, batches & Accord
LWTs give compare-and-set on one partition via Paxos; batches give atomicity, not isolation; Accord brings ACID in 6.0.
- A lightweight transaction (LWT) is a conditional write:
INSERT ... IF NOT EXISTS,UPDATE ... IF balance = 100. It returns an[applied]column. - LWTs use Paxos among the replicas of one partition: prepare/promise, read, propose/accept, commit. That is about 4 round trips, so use them sparingly (unique usernames, leader election, idempotency keys).
- The Paxos phase uses
SERIALorLOCAL_SERIAL; the commit phase uses the normal CL. Cassandra 4.1 added Paxos v2 (paxos_variant: v2) which cuts round trips and improves performance. - LWTs are linearizable for a single partition. Mixing LWT and non-LWT writes on the same data breaks the guarantee.
- Logged BATCH: guarantees all statements eventually apply (batchlog), but gives no isolation and is slower. Use it to keep denormalized tables in sync, not for bulk loading. Unlogged batch to a single partition is applied as one mutation and is efficient.
- Accord (CEP-15) brings general-purpose multi-partition ACID transactions (
BEGIN TRANSACTION ... COMMIT TRANSACTION). It is part of Cassandra 6.0, not 5.0 (5.0 shipped SAI, vector search, UCS, trie memtables/SSTables and JDK 17).
Interview questions
- What is a lightweight transaction in Cassandra?
- Does a Cassandra BATCH give you a transaction?
- Does Cassandra 5.0 support ACID transactions via Accord?
Cassandra data modelling
Query-first modelling: partition & clustering keys
Design one table per query; the partition key decides where data lives, the clustering key decides order inside it.
- Start from the access patterns (the queries the app runs), not from entities. Each query should be served by one partition read of one table.
- Primary key = partition key + clustering columns.
PRIMARY KEY ((a, b), c, d):(a, b)is a composite partition key;c, dare clustering columns. - Partition key: hashed to pick replicas; queries must give it with
=(orIN). Clustering columns: sort rows inside the partition, allow range filters (>,<) and ordering, in declared order only. - Denormalize: the same data is written to several tables, one per query (
videos_by_user,videos_by_tag). Disk is cheap; cross-node joins are not. - Clustering order is fixed at table creation (
WITH CLUSTERING ORDER BY (ts DESC)), so pick the order your query needs, for example newest first. - Columns outside the primary key cannot be filtered efficiently. Add a table, a materialized view (experimental) or an SAI index (5.0) instead.
Interview questions
- Difference between partition key and clustering key?
- What does query-first (query-driven) data modelling mean?
- What is the difference between PRIMARY KEY (a, b, c) and PRIMARY KEY ((a, b), c)?
- How do you model a messaging app's 'latest messages in a conversation' query?
Hot partitions, partition size & bucketing
Spread load across many partitions and keep each one bounded in size and traffic.
- A hot partition gets far more traffic than others (a celebrity user, today's date as key, a status flag). Its replicas saturate while the rest of the cluster idles.
- A large partition (hundreds of MB, millions of rows) slows reads, compaction and repair, and stresses the heap. Keep partitions well under ~100 MB and ideally far smaller; Cassandra logs a warning for large partitions during compaction.
- Bucketing: add a time component (
day,month) or a shard number (hash(id) % N) to the partition key to bound size and spread writes. Readers query all buckets they need. - Choose high-cardinality partition keys (user id, device id). Low-cardinality keys like
countryorgendercreate a few giant partitions. - Estimate size: rows per partition × row size. Plan for growth over the data's lifetime, not today's volume.
- Find problems with
nodetool tablehistograms,nodetool tablestats, and the 5.0sstablepartitionstool.
Interview questions
- What is a hot partition and how do you fix it?
- How big should a Cassandra partition be?
- Design a table for IoT sensor readings at 1,000 readings per second per sensor.
CQL limits: no joins, ALLOW FILTERING, indexes
CQL looks like SQL but only supports queries that map to efficient partition reads.
- No joins, no subqueries, no foreign keys.
GROUP BYworks only on primary key columns, and aggregates (COUNT,SUM) run on the coordinator, so use them only on small partitions. - A
WHEREclause must restrict the full partition key (or the query becomes a cluster-wide scan) and clustering columns in order. ALLOW FILTERINGtells Cassandra to read data and discard non-matching rows. Within one partition it can be fine; across the table it is a full scan of every node.- Secondary indexes (legacy 2i) are local to each node, so a query fans out to all nodes. They suit low-to-medium cardinality columns queried together with the partition key.
- SAI (Storage-Attached Index), new in 5.0, is attached to SSTables and memtables, supports multiple-column filters, numeric ranges and vector search (ANN on the
vectortype). It is the recommended index type now, but still fans out when no partition key is given. - Materialized views auto-maintain a second table but are marked experimental (disabled by default) because of consistency issues. Prefer application-managed denormalized tables.
- Counters live in separate counter-only tables, cannot be set or TTL'd, and increments are not idempotent on retry.
Interview questions
- Why doesn't Cassandra support joins?
- What does ALLOW FILTERING do and when is it acceptable?
- Secondary index vs SAI vs a new table: which do you use?
- Why are materialized views discouraged?
DynamoDB
Tables, items, keys & operations
A table holds items addressed by a partition key and optional sort key; Query reads one partition, Scan reads everything.
- A table holds items (rows); an item holds attributes. Apart from the key, items in the same table can have different attributes. Max item size is 400 KB (names + values).
- Simple primary key: partition key only (one item per key). Composite primary key: partition key + sort key; items with the same partition key form an item collection sorted by sort key.
- The partition key is hashed to choose a physical partition. Each partition holds up to about 10 GB and serves up to about 3,000 RCU and 1,000 WCU.
- Operations:
GetItem(one item by full key),Query(one partition key, optional sort key conditions likebegins_withandBETWEEN),Scan(whole table),PutItem,UpdateItem,DeleteItem,BatchGetItem(up to 100),BatchWriteItem(up to 25). - Query and Scan return up to 1 MB per call; use
LastEvaluatedKey→ExclusiveStartKeyto page. AFilterExpressionis applied after reading, so it does not save capacity. - Condition expressions (
attribute_not_exists(pk),version = :v) make writes conditional, which enables idempotent creates and optimistic locking.
Interview questions
- What is the difference between a partition key and a sort key in DynamoDB?
- Query vs Scan?
- Does a FilterExpression reduce read cost?
LSI vs GSI
LSIs give another sort key on the same partition; GSIs give a whole new key and are eventually consistent.
- A Local Secondary Index (LSI) keeps the same partition key but uses a different sort key. It must be created with the table, and you can have up to 5.
- LSIs share the base table's partitions and capacity and support strongly consistent reads. A table with LSIs limits each item collection (all items with one partition key) to 10 GB.
- A Global Secondary Index (GSI) can use any partition key and sort key. It can be added or removed anytime; the default quota is 20 per table.
- GSIs are stored separately and updated asynchronously, so reads are eventually consistent only. Key values need not be unique.
- A GSI has its own throughput (provisioned mode). If a GSI is under-provisioned, writes to the base table get throttled (back-pressure).
- Projection:
KEYS_ONLY,INCLUDE(chosen attributes) orALL. Project only what the query needs; every write to a projected attribute also costs a write on the index. - Sparse index: items without the index key attribute are not in the index. Great for "only open orders" style queries.
Interview questions
- LSI vs GSI: what are the key differences?
- Why can my base table get throttled because of a GSI?
- What is a sparse index and when is it useful?
Capacity modes, RCU/WCU math & adaptive capacity
Reads are billed per 4 KB, writes per 1 KB; choose on-demand for unpredictable load and provisioned for steady load.
- 1 RCU = one strongly consistent read per second of up to 4 KB, or two eventually consistent reads. A transactional read costs 2 RCUs per 4 KB.
- 1 WCU = one write per second of up to 1 KB. A transactional write costs 2 WCUs per 1 KB. Sizes round up: a 1.5 KB write costs 2 WCUs.
- On-demand mode bills per request (read/write request units), scales instantly to previously seen peaks and beyond, and needs no planning. AWS cut on-demand prices by 50% in late 2024, so it is the default choice for many workloads.
- Provisioned mode: you set RCU/WCU (optionally with auto scaling). Cheaper for steady, predictable traffic, and can use reserved capacity. Over the limit, requests are throttled (
ProvisionedThroughputExceededException). - Per-partition limits (about 3,000 RCU / 1,000 WCU) apply in both modes. A single hot key can be throttled even if the table has spare capacity.
- Adaptive capacity automatically lends unused throughput to hot partitions and can split a partition that gets steady heavy traffic (split for heat). Burst capacity saves up to 5 minutes of unused capacity for short spikes. Neither fixes a single extremely hot item.
Interview questions
- How many RCUs do you need for 100 strongly consistent reads per second of 9 KB items? And eventual?
- How many WCUs for 50 writes per second of 3.5 KB items?
- On-demand vs provisioned capacity: how do you choose?
- What is adaptive capacity?
Read consistency, conditional writes & transactions
Reads are eventual by default; strong reads cost double; transactions give ACID across up to 100 items.
- Each item is stored on three replicas in different AZs. A write is acknowledged once a quorum (two of three, including the leader) has it durably.
- Eventually consistent reads (default) may hit any replica and can be slightly stale (usually caught up within a second). Strongly consistent reads (
ConsistentRead: true) go to the leader and cost 2×. - Strong reads are available on tables and LSIs, not on GSIs or Streams, and they can have higher latency or fail during a network problem.
- Conditional writes check a condition atomically on one item:
attribute_not_existsfor create-once,version = :expectedfor optimistic locking. - Transactions:
TransactWriteItemsgroups up to 100 actions (Put, Update, Delete, ConditionCheck) on distinct items, across tables in one account and Region, up to 4 MB total; all succeed or none do.TransactGetItemsreads up to 100 items as a consistent snapshot. Both cost 2× capacity. - Transactions are serializable with respect to other writes on those items and can fail with
TransactionCanceledExceptionon conflict. AClientRequestTokenmakesTransactWriteItemsidempotent for 10 minutes. BatchWriteItemis not a transaction: some items can succeed while others come back inUnprocessedItems.
Interview questions
- Eventually consistent vs strongly consistent reads in DynamoDB?
- How do you implement optimistic locking in DynamoDB?
- What are the limits and costs of DynamoDB transactions?
- BatchWriteItem vs TransactWriteItems?
Single-table design & access patterns
Store several entity types in one table with generic PK/SK values so related data comes back in one Query.
- List every access pattern first ("get customer and recent orders", "orders by status"), then design keys to serve each with a
GetItemorQuery. - Use generic key names (
PK,SK) and prefixed values (CUSTOMER#42,ORDER#2026-12-02#981). Different entity types share one table. - Pre-joining: put related items under the same partition key (an item collection), so one Query returns the customer profile plus their orders, like a join done at write time.
- Hierarchical sort keys (
COUNTRY#IN#STATE#GJ#CITY#...) supportbegins_withqueries at each level. - GSI overloading: one GSI with generic
GSI1PK/GSI1SKattributes serves different access patterns for different entity types. - Trade-offs: very efficient and cheap at scale, but harder to read, hard to change when access patterns change, and awkward for analytics (export to S3 / Athena). Many teams use a few tables when patterns are simple or evolving.
Interview questions
- What is single-table design and why use it?
- How do you model a one-to-many relationship in DynamoDB?
- How do you handle a many-to-many relationship?
- When would you NOT use single-table design?
Streams, TTL, DAX & global tables
Streams feed change events, TTL expires items for free, DAX caches reads, and global tables replicate across Regions.
- DynamoDB Streams: an ordered (per item) log of item changes kept for 24 hours. View types:
KEYS_ONLY,NEW_IMAGE,OLD_IMAGE,NEW_AND_OLD_IMAGES. Usually consumed by Lambda for events, aggregations, search indexing or the outbox pattern. You can also stream to Kinesis Data Streams for longer retention and more consumers. - TTL: pick a Number attribute holding an epoch-seconds timestamp. Expired items are deleted in the background within a few days, with no WCU cost. Until then they can still appear in reads, so filter them out. TTL deletes appear in Streams as service deletions.
- DAX (DynamoDB Accelerator): an in-memory, write-through cache cluster in your VPC with an API-compatible client. Gives microsecond reads for eventually consistent
GetItem/Query; strongly consistent reads pass through to DynamoDB. - Global tables: multi-Region, multi-active replicas of a table. Default MREC (multi-Region eventual consistency): async replication, usually under a second, last writer wins conflicts.
- MRSC (multi-Region strong consistency): writes replicate synchronously to another Region before success, strongly consistent reads see the latest version in any Region. Needs exactly three Regions (three replicas, or two plus a witness), the table must be empty when converted, and TTL and LSIs are not supported.
- Also know: PITR (point-in-time recovery, continuous backups), on-demand backups, export to S3 without using table capacity, and PartiQL for SQL-like access.
Interview questions
- What are DynamoDB Streams used for?
- How does TTL work and what are its caveats?
- When would you use DAX instead of ElastiCache?
- How do global tables handle conflicts?
Choosing & comparing
Cassandra vs DynamoDB vs MongoDB
Cassandra for self-managed write-heavy scale, DynamoDB for serverless AWS key-value, MongoDB for flexible documents and rich queries.
- Cassandra: open source, runs anywhere, leaderless, linear write scaling, tunable consistency, strong multi-DC support. You (or a vendor like DataStax Astra / Amazon Keyspaces) operate it: repair, compaction, tuning.
- DynamoDB: fully managed and serverless on AWS, pay per request, single-digit millisecond latency, built-in Streams, TTL, backups and global tables. Vendor lock-in and strict item/partition limits.
- MongoDB: document store with rich queries, secondary indexes, aggregation pipeline and multi-document ACID transactions. Replica sets have a single primary per shard; sharding is optional.
- All three need you to think about the shard/partition key; a poor key causes hot spots everywhere.
- Scenario picks: IoT/time-series ingestion across DCs → Cassandra. Serverless app on AWS with known patterns → DynamoDB. Product catalog or content with varied queries → MongoDB.
Interview questions
- Cassandra vs DynamoDB: how do you choose?
- Cassandra vs MongoDB?
- Design question: store 1 billion chat messages a day, readable by conversation. Which database and why?