Wide-Column & Key-Value at Scale: Cassandra & DynamoDB
"Dynamo sacrifices consistency under certain failure scenarios. It makes extensive use of object versioning and application-assisted conflict resolution in a manner that provides a novel interface for developers to use." — DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007
Summary: Wide-column and key-value stores give up joins and ad-hoc queries so that every request names its partition, which lets data, writes and availability scale past one machine. Focus: The Dynamo and Bigtable designs, partition and sort keys, query-first modeling, hot partitions, DynamoDB capacity and single-table design, Cassandra tunable consistency, tombstones, repair and multi-region, and when PostgreSQL is simply enough. Learning goal: Choose keys that spread traffic, model tables from queries, pick a consistency level on purpose, and decide honestly between DynamoDB, Cassandra, ScyllaDB and PostgreSQL.
This page is the conceptual comparison of the two products that define the family: Apache Cassandra (and its C++ sibling ScyllaDB) and Amazon DynamoDB. It explains the two papers they descend from (Dynamo 2007: consistent hashing, vector clocks, sloppy quorum, hinted handoff, Merkle-tree anti-entropy, gossip; Bigtable 2006: tablets, SSTables, Chubby), then every practical concept: partition key and sort key, query-first modeling, denormalization, hot partitions and the celebrity problem, DynamoDB read and write units, on-demand and provisioned capacity, adaptive capacity, single-table design, GSI and LSI, transactions (TransactWriteItems in DynamoDB, lightweight transactions on Paxos in Cassandra), TTL, streams and change data capture, tunable consistency, tombstones, compaction, repair, multi-region, cost models, and when PostgreSQL is enough. The CQL syntax, compaction-strategy choice, repair operations and ScyllaDB's shard-per-core design are the job of the deep dive Cassandra & ScyllaDB in Depth; the ring and virtual nodes in general are in Consistent Hashing; the consistency vocabulary is in Eventual Consistency in Database Systems; the LSM mechanics are in Storage Engines. Here each of those gets the part you need to compare the two products, and a link.
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why these stores exist and what they cost | Why they exist |
| The Dynamo and Bigtable papers, and how Cassandra and DynamoDB descend from them | Where it comes from |
| Partition key, sort key, clustering key, item collection | Partition key and sort key |
| How a key becomes a node: ring, tokens, vnodes, replicas | Placement on the ring |
| ONE, QUORUM, LOCAL_QUORUM, ALL, eventually vs strongly consistent reads | Tunable consistency |
| Sloppy quorum, hinted handoff, vector clocks, Merkle trees, gossip | Dynamo's failure toolkit |
| One table per query, denormalization, duplication | Query-first modeling |
| Hot partitions, celebrity keys, write sharding | Hot partitions |
| Read and write units, on-demand vs provisioned, adaptive capacity | DynamoDB capacity |
| Single-table design, item collections | Single-table design |
| GSI, LSI, Cassandra 2i and SAI | Secondary indexes |
TransactWriteItems, ConditionExpression, Cassandra LWT | Transactions and conditions |
| TTL, tombstones, deletes, compaction, repair | Deletes and TTL, Compaction, Repair |
| DynamoDB Streams, Cassandra CDC | Streams and CDC |
| Global tables, multi-datacenter Cassandra | Multi-region |
| What it costs, and when PostgreSQL is enough | Cost models, When PostgreSQL is enough |
| Product-by-product comparison and error codes | Per-engine behaviour, Mechanics |
| Code for Go (aws-sdk-go-v2, gocql) and Laravel (AWS SDK, cache driver) | Solving the classic problems, Retries |
| Reproduce hot keys and tombstones on your laptop | Lab |
| Wrong beliefs, cheat sheet, self-check, glossary | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The ten ideas. Every row is unpacked later.
| Idea | In plain words | Tiny example | Where it bites |
|---|---|---|---|
| Partition key | The part of the primary key that is hashed to choose where the data lives | PK = USER#42 | Low cardinality means one busy partition |
| Sort / clustering key | The part that orders items inside one partition | SK = ORDER#2026-11-25 | A range of it is one contiguous read |
| Query-first modeling | List the queries, then build one table per query | orders_by_user, orders_by_day | A new query is a new table and a backfill |
| Denormalization (denormalization) | Copy the same fact into every table that needs it | Customer name stored in each order item | Updates must touch every copy |
| Tunable consistency | Choose per request how many replicas must answer | LOCAL_QUORUM, ConsistentRead | ONE can return stale data |
| Hot partition | One key gets far more traffic than its share | A celebrity feed, today's date | Throttling while the table idles |
| Single-table design | Several entity types under one partition key in one table | USER#42 holds profile, orders, addresses | Only the author can read the schema |
| Tombstone | A delete is a marker, not an erase | Cassandra DELETE writes a marker | Reads scan past markers |
| Transaction / LWT | Conditional or multi-item atomic writes, at a cost | TransactWriteItems, IF NOT EXISTS | 2x capacity in DynamoDB, Paxos rounds in Cassandra |
| Multi-region | Replicas in several regions or datacenters | Global tables, NetworkTopologyStrategy | Concurrent writes resolve last-writer-wins |
DynamoDB against Cassandra, side by side.
| Axis | DynamoDB | Apache Cassandra / ScyllaDB |
|---|---|---|
| Who runs it | AWS, fully managed, serverless | You (or a managed offering) |
| Key vocabulary | Partition key, sort key | Partition key, clustering key |
| Placement | Internal hash, hidden partitions | Murmur3 tokens on a visible ring, vnodes |
| Consistency | Eventually consistent default, ConsistentRead per request | ONE ... ALL, LOCAL_QUORUM, EACH_QUORUM per query |
| Conditional writes | ConditionExpression, TransactWriteItems | IF NOT EXISTS / IF (Paxos), batches |
| Secondary access paths | GSI (eventually consistent), LSI (strong, 10 GB per key) | Local 2i, SAI, materialised views, query tables |
| Capacity model | Read/write units, on-demand or provisioned | Nodes, you size the cluster |
| Change feed | DynamoDB Streams (24 hours) | CDC commit-log segments |
| Multi-region | Global tables (MREC or MRSC) | Multi-datacenter replication, per-query CL |
The three things to do.
| Situation | Do this |
|---|---|
| Designing a new table | Write the access patterns first, choose a high-cardinality partition key, and put the sort order you read in the sort key |
| One key is hot | Shard the write key with a suffix and fan out on read, or change the key; do not just raise capacity |
| You need a join, ad-hoc reports or multi-row constraints | Use PostgreSQL; add a wide-column store only for the one workload that outgrew it |
Why they exist
A relational database makes the schema general and the queries free: any join, any filter, decided at query time. The price is that the planner may touch any page of any table, so the data must live where one engine can coordinate it. Dynamo and Bigtable made the opposite bet. If every request must name the partition it wants, the system never needs a global view: it can hash the key, go to a few machines, and answer. Adding machines adds capacity, and losing one costs a replica, not the service.
| You give up | You get |
|---|---|
Joins, ad-hoc WHERE, cross-partition constraints | Reads and writes that cost the same at 1 GB and 100 TB |
| One current copy of every fact (you duplicate) | Latency that depends on the partition, not on the table size |
| Strong consistency by default | Availability when nodes or regions fail |
| A schema the database enforces | A schema your key design and your code enforce |
| The freedom to ask a new question later | Predictable cost per request |
The everyday picture, reused through the page. A library with a million shelves and no catalogue. Each shelf label is the book's partition key, and the librarian can walk to any label instantly, then read the shelf left to right (the sort key). If you ask for "everything by this author", there is nowhere to look except every shelf. So the library does what these systems do: it shelves a second copy of each book under the author's name, and a third under the subject. Reads are instant, shelving costs more, and one famous shelf that everyone queues at is the hot partition.
Three common misunderstandings, up front
- "NoSQL means no schema." The schema moves into your key design and your application. Changing a key means rewriting the data.
- "Hash partitioning guarantees even load." It spreads keys, not traffic. A celebrity key is still one partition.
- "A Scan with a filter is a query." The filter runs after the read, so cost and latency track the table size, not the result size.
Where it comes from
Two papers, one year apart, define the family. Both are Google or Amazon describing what they had to build because a single database could not meet their availability and scale targets. Cassandra was written by combining the two; DynamoDB is Amazon's managed service whose name and key-based partitioning come from Dynamo, but which is a different system from the 2007 paper. This page takes concepts from the papers and DynamoDB's actual behaviour from the AWS documentation.
The Dynamo paper (Amazon, SOSP 2007) Must-know
In plain words: Amazon's shopping cart must accept writes even when servers or networks fail, so Dynamo is a store with no master where any replica can accept a write, and where conflicting versions are kept and merged later instead of blocking the write.
Common misunderstanding: "DynamoDB is the Dynamo paper." It is not. The paper describes a system Amazon used internally; DynamoDB is a separate managed service that shares the partitioning idea and the name. Features the paper describes (vector clocks surfaced to the client, sloppy quorum, application-assisted merge) are not what the DynamoDB API exposes.
Definition: the paper combines six techniques, which its summary table lists as problem and technique pairs:
| Problem | Technique in the paper | Advantage |
|---|---|---|
| Partitioning | Consistent hashing | Incremental scalability |
| High availability for writes | Vector clocks with reconciliation during reads | Version size is decoupled from update rates |
| Handling temporary failures | Sloppy quorum and hinted handoff | High availability and durability when some replicas are unavailable |
| Recovering from permanent failures | Anti-entropy using Merkle trees | Synchronises divergent replicas in the background |
| Membership and failure detection | Gossip-based membership protocol | Avoids a centralised registry |
Two parameters describe a Dynamo configuration: N (replicas per key), R (replicas that must answer a read) and W (replicas that must acknowledge a write). The paper's rule: "Setting R and W such that R + W > N yields a quorum-like system." A common production choice in the paper is (N, R, W) = (3, 2, 2).
Dynamo write of key k (N = 3, W = 2), preference list = A, B, C, then D
1 client -> any node (or a load balancer) -> coordinator = first node in k's preference list
2 coordinator generates the new vector clock for the new version, writes locally
3 coordinator sends the version to the N highest-ranked REACHABLE nodes
4 A is down: replica goes to D with the hint "intended for A"; B and C store it normally
5 B and D ack -> W = 2 reached -> coordinator answers the client
6 A returns; D hands the hinted replica back and deletes itReal scenarios: the shopping cart (the paper's own example: an "add to cart" must never be refused, and a deleted item may reappear after a merge); session stores; best-seller lists; anything where "always writable" beats "always exact".
What provides it today: Cassandra and ScyllaDB (ring, gossip, hints, Merkle repair, tunable consistency); Riak (the paper's other well-known open-source descendant). DynamoDB (the service) keeps the partitioning and replication but hides everything else behind ConsistentRead and conditional writes.
The Bigtable paper (Google, OSDI 2006) Must-know
In plain words: a table is a giant sorted map from (row key, column, timestamp) to a value. Because it is sorted by row key, a range of keys is a contiguous read, and the table is cut into slices called tablets that different machines serve.
Common misunderstanding: "Wide-column means a table with thousands of columns." The "wide" is about the sparse, sorted map: each row can have a different set of columns, and a Cassandra partition holds many rows. Column families in Bigtable are a storage and access-control grouping, not a relational schema.
Definition: "A Bigtable is a sparse, distributed, persistent multi-dimensional sorted map. The map is indexed by a row key, column key, and a timestamp". The moving parts:
| Component | What it does | Where you meet it today |
|---|---|---|
| Tablet | A contiguous row range; "each table consists of just one tablet" at first and splits automatically, each approximately 100-200 MB by default | HBase regions; Cassandra partition ranges; DynamoDB partitions |
| Tablet server | Serves a set of tablets and handles reads and writes | HBase RegionServer |
| Master | Assigns tablets to servers, detects live servers, handles schema changes | HBase Master |
| Chubby | A distributed lock service that holds the root of the tablet location tree, tracks tablet servers, and stores schema and ACLs | ZooKeeper in HBase; Cassandra uses gossip instead |
| SSTable | "a persistent, ordered immutable map from keys to values" file | Cassandra SSTables, RocksDB, HBase HFiles |
| Memtable + commit log | Writes go to a log and an in-memory sorted buffer, flushed to a new SSTable | Cassandra commit log and memtable |
| Compaction | Merges SSTables; a major compaction rewrites all into one | Storage Engines |
| Three-level location | Chubby file, then the root METADATA tablet, then other METADATA tablets, then user tablets | HBase hbase:meta |
The deliberate difference between the two designs: Bigtable has one master and a lock service (it is strongly consistent per row, built on GFS), while Dynamo has no master and trades consistency for availability. Cassandra took Bigtable's data model and storage engine and put them on Dynamo's masterless ring.
Bigtable read of row r (client library caches locations)
1 client asks Chubby for the root tablet location (cached after the first time)
2 root METADATA tablet -> which METADATA tablet covers r
3 METADATA tablet -> which tablet server serves r's tablet
4 tablet server reads: memtable + SSTables (merged view), most recent first
5 answer; the next read of the same range skips steps 1-3Real scenarios: time-series by (device, time), web crawl tables (the paper's Webtable), user profile stores, analytics row stores.
What provides it today: Google Cloud Bigtable, Apache HBase, Cassandra and ScyllaDB (storage model), Amazon DynamoDB (sorted items within a partition key).
From the papers to the products
| Concern | Dynamo paper | Bigtable paper | Cassandra | DynamoDB |
|---|---|---|---|---|
| Master | None | One master + Chubby | None | Hidden, managed |
| Placement | Consistent hashing, preference list | Sorted row ranges (tablets) | Murmur3 token ring, vnodes | Internal hash on the partition key |
| Data model | Opaque value per key | Row, column family, column, timestamp | Partition key, clustering columns, columns | Items with attributes, partition key, sort key |
| Conflicts | Vector clocks, client merges | Single writer per tablet | Last-write-wins by timestamp per cell | Last-writer-wins in global tables |
| Storage | Pluggable (BDB, MySQL) | SSTables, memtable, GFS | SSTables, memtable, commit log | Managed, hidden |
| Membership | Gossip | Master + Chubby | Gossip | Managed |
Cassandra is usually described as Bigtable-style rows and columns on a Dynamo-style ring (a secondary-source summary; its own docs list "Distributed cluster membership and failure detection via a gossip protocol" and tunable consistency among the Dynamo-derived parts). Note one real change from the paper: Cassandra does not use vector clocks. Its docs say mutations are “timestamped (including deletes) and then the latest version of data is the "winning" value”, formally a last-write-wins element-set CRDT per CQL row.
The concept catalogue
Partition key and sort key Must-know
In plain words: the first part of the primary key chooses the machine; the second part sorts the items on that machine. If you can name the first part, you are one hop from your data.
Common misunderstanding: "The partition key is like an index I can add later." It is the physical address. You can query efficiently only by equality on the full partition key (plus a range on the sort key), and you cannot change it without rewriting the data.
Definition: DynamoDB: "All items with the same partition key value are stored together, in sorted order by sort key value." The hash of the partition key picks the partition; the sort key orders items within it. Cassandra calls the second part the clustering key, and the pair of partition key and clustering columns is the primary key. A group of items sharing a partition key is an item collection (DynamoDB) or a partition (Cassandra).
Query: all orders of user 42, newest first
1 PK = "USER#42" -> hash -> one partition (one replica set)
2 SK in the partition is sorted: ORDER#2026-11-25 ... ORDER#2026-11-20
3 ScanIndexForward=false -> read from the end, stop at Limit
4 one request, one partition, cost proportional to items returned
Query: all orders with status = "pending" (no key names it)
1 no partition key -> Scan: read every partition
2 FilterExpression keeps pending ones AFTER reading
3 cost proportional to the whole tableReal scenarios: chat messages by (room, time); orders by (user, time); telemetry by (device, day); a catalogue by (category, product).
What provides it:
| Concept | DynamoDB | Cassandra / ScyllaDB | Bigtable / HBase |
|---|---|---|---|
| Distribution key | Partition key (hash) | Partition key (Murmur3 token) | Row key (range, sorted) |
| In-partition order | Sort key | Clustering columns, CLUSTERING ORDER BY | Row key order, column qualifiers |
| Range scan by key | Only inside one partition | Only inside one partition (ALLOW FILTERING otherwise) | Across rows, because rows are globally sorted |
| Composite keys | PK and SK strings, prefixes by convention | Composite partition key ((a, b), c) | Row-key design by convention |
Fix / how to use it: the key builders live in one package; the key format is your schema. See the Go code and the PHP OrderStore below.
-- Cassandra (CQL): partition key = user_id, clustering key = placed_at, newest first
CREATE TABLE orders_by_user (
user_id uuid,
placed_at timestamp,
order_id uuid,
total decimal,
PRIMARY KEY ((user_id), placed_at, order_id)
) WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);
SELECT order_id, total FROM orders_by_user WHERE user_id = ? LIMIT 20;Bigtable differs from the other two in one way worth knowing: because rows are range-partitioned and sorted globally, a scan across many row keys is a normal operation, and the classic failure is the opposite one (a monotonically increasing key such as a timestamp sends all writes to the last tablet). Hash-partitioned stores (DynamoDB, Cassandra) cannot range-scan across partitions, and their classic failure is the low-cardinality key.
Placement on the ring: tokens, vnodes, replicas Must-know
In plain words: hash the partition key to a number, find that number on a circle of machines, and the machines that sit clockwise from it hold the copies. Adding a machine moves only the neighbouring slice.
Common misunderstanding: "Consistent hashing balances load." It balances key ranges. Equal slices of the ring do not mean equal traffic, and with few physical nodes the slices are uneven unless each node owns many small ones (virtual nodes).
Definition: Cassandra's docs: "Multiple Tokens per Physical Node (vnodes)" fix the uneven-slice problem; Dynamo's wording is "A virtual node looks like a single node in the system, but each node can be responsible for more than one virtual node." The first replica is the node owning the token range; further replicas are the next distinct nodes clockwise until the replication factor is met (the preference list). The full algorithm, with rendezvous and jump hash for comparison, is in Consistent Hashing.
Placement of (PK = USER#42) on a four-node ring, RF = 3
1 token = Murmur3("USER#42") (Cassandra) / internal hash (DynamoDB)
2 find the first node token clockwise: N1 owns this range -> primary replica
3 continue clockwise to the next DISTINCT nodes: N2, N3 -> replicas (RF = 3)
4 coordinator (any node) forwards to N1, N2, N3; CL decides how many must answer
5 add N5 later: it takes ranges from its clockwise neighbours only; other keys stayReal scenarios: growing a cluster by one node without a full reshuffle; replacing a dead node by streaming only its ranges; spreading a node's data across the cluster so rebuilds read from many sources.
What provides it:
| Product | Placement | Replication unit | Visible to you? |
|---|---|---|---|
| Cassandra | Murmur3 partitioner, num_tokens vnodes per node (16 in the 5.0 default config the lab uses) | Keyspace replication factor, NetworkTopologyStrategy | nodetool ring, nodetool describering |
| ScyllaDB | Same ring idea, plus shard-per-core ownership of tokens inside a node | Same | nodetool ring |
| DynamoDB | Internal hash of the partition key to partitions | Automatically replicated across multiple Availability Zones in a Region (managed) | No: partitions are hidden |
| Bigtable / HBase | Sorted row ranges, no hash | Tablets served by one server, data replicated by the filesystem | Tablet or region boundaries |
| Redis Cluster | 16384 hash slots | Replica per master | CLUSTER SLOTS |
Fix / how to use it: you do not place data yourself; you choose keys so that the hash spreads traffic. In Cassandra, check the actual spread with nodetool status (ownership) and nodetool tablestats (partition sizes).
Tunable consistency: ONE, QUORUM, LOCAL_QUORUM, ALL Must-know
In plain words: with three copies of every row you decide, per request, how many copies must agree before you get an answer. Fewer copies means faster and always available but possibly stale; more means slower and stricter.
Common misunderstanding: "QUORUM makes Cassandra strongly consistent, like a single database." It gives you read-your-writes for a single partition when both the write and the read use QUORUM (R + W > N) and no hint or repair is racing you, but it is not a transaction: concurrent writers still resolve by timestamp, and a failed write may be partly applied.
Definition: N is the replication factor. A write at level W waits for W replicas; a read at level R waits for R. When R + W > N the read set and write set overlap in at least one replica, so a read sees the latest acknowledged write. Cassandra's levels:
| Level | Replicas that must respond | Use it for |
|---|---|---|
ANY | One replica, or the coordinator stores a hint (writes only) | Fire-and-forget logs where loss is acceptable |
ONE / LOCAL_ONE | One replica (LOCAL_ONE: one in the local datacenter) | Fast reads that may be stale; high-volume writes |
QUORUM | A majority of all replicas (n/2 + 1) | Read-your-writes in a single datacenter cluster |
LOCAL_QUORUM | A majority in the coordinator's datacenter | The usual multi-datacenter default: strong inside one DC, no cross-DC latency |
EACH_QUORUM | A majority in every datacenter | Writes that must be durable in every DC (slow, fails if one DC is unreachable) |
ALL | Every replica | Rare: any one node down makes the request fail |
DynamoDB hides replicas and exposes one switch: reads are eventually consistent by default; setting ConsistentRead to true returns "the most up-to-date data, reflecting the updates from all prior write operations that were successful". A strongly consistent read costs twice an eventually consistent one, is available on tables and LSIs but not on GSIs or streams (all of their reads are eventually consistent).
Cassandra RF = 3, a stale read at ONE
1 client -> write v2 at ONE coordinator writes R1, R2, R3 in parallel
2 R1 acks v2 -> coordinator returns OK (R2, R3 are still applying, or R3 is down)
3 client -> read at ONE coordinator asks the nearest replica: R3
4 R3 still holds v1 -> client reads v1 (stale: R + W = 1 + 1 = 2, not greater than 3)
5 same sequence at QUORUM/QUORUM: write waits for 2, read asks 2 -> overlap guaranteed -> v2Real scenarios: a shopping-cart read after the add (LOCAL_QUORUM); a timeline of "latest posts" (LOCAL_ONE); a payment-status read right after the write (DynamoDB ConsistentRead); an audit log across datacenters (EACH_QUORUM, rarely).
What provides it:
| Product | Default | Strongest | Per request? |
|---|---|---|---|
| Cassandra / ScyllaDB | Set by the driver or by cqlsh, not by the server (gocql: Quorum) | ALL, or SERIAL / LOCAL_SERIAL for conditional writes | Yes, per statement |
| DynamoDB | Eventually consistent read | ConsistentRead: true on table and LSI; transactional APIs | Yes, per read call |
| Redis | Single primary; replicas are async | WAIT for replica acks (not a guarantee) | Per command |
| MongoDB | Read concern local, write concern w:1/majority by version | majority read and write concern | Yes |
| PostgreSQL | One primary, synchronous replicas optional | Synchronous commit to standbys | Per transaction |
| CockroachDB | Serializable | Serializable (default, always) | No |
Fix / how to use it: Go with gocql sets it per query; the same in CQL with CONSISTENCY LOCAL_QUORUM; in cqlsh.
// From the cql snippet below: consistency is a per-query decision.
s.Query(`SELECT order_id, total FROM orders_by_user WHERE user_id = ? LIMIT 20`, userID).
Consistency(gocql.One).Iter()The vocabulary of consistency models (read-your-writes, monotonic reads, bounded staleness) and the replica-lag mechanics are in Eventual Consistency in Database Systems and Replication, Read Replicas & Failover.
Dynamo's failure toolkit: sloppy quorum, hinted handoff, vector clocks, Merkle anti-entropy, gossip Important
In plain words: when a replica is down, a neighbour takes the write and promises to hand it back; when two replicas disagree, the system either keeps both versions (Dynamo) or picks the newest timestamp (Cassandra); in the background the replicas compare fingerprints and copy what differs; nodes learn who is alive by gossiping.
Common misunderstanding: "Hinted handoff guarantees the replica will catch up." Hints are best effort. Cassandra's docs: "Hints are best effort, however, and do not guarantee eventual consistency like anti-entropy repair does."
Definition:
| Mechanism | What it does | Dynamo paper | Cassandra | DynamoDB |
|---|---|---|---|---|
| Sloppy quorum | Reads and writes use the first N healthy nodes of the preference list, not strictly the first N on the ring: “it does not enforce strict quorum membership and instead it uses a “sloppy quorum”” | Yes | No: quorum is strict over the real replicas; ANY is the only level that accepts a hint as an ack | Hidden |
| Hinted handoff | A node that took a write for a down replica stores it with a hint and delivers it when that replica returns | Yes | Yes: coordinators store hints on their local filesystem and replay them; max_hint_window is 3 hours by default in the 5.0 config | Hidden |
| Vector clocks | "A vector clock is effectively a list of (node, counter) pairs", one per version, to tell a causal successor from a parallel branch | Yes; capped in size by truncation | No: last-write-wins by cell timestamp | No: last-writer-wins |
| Read repair | Reads that find stale replicas write the newest version back | Yes (on read) | Yes (at QUORUM and above, or by chance) | Hidden |
| Merkle-tree anti-entropy | Replicas hash ranges of their data into a tree; "each branch of the tree can be checked" without reading everything, and only differing ranges are exchanged | Yes | nodetool repair compares Merkle trees | Hidden |
| Gossip | Nodes exchange membership and failure state with random peers, no central registry | Yes | Yes (nodetool gossipinfo) | Hidden |
Vector clock vs last-write-wins, two clients edit cart v1 while partitioned
1 v1 = [A:1]
2 client X writes via node A -> v2 = [A:2] items: {book}
3 client Y writes via node B -> v3 = [A:1, B:1] items: {book, pen} (concurrent with v2)
4 read sees v2 and v3: neither clock dominates -> Dynamo returns BOTH (siblings)
5 application merges -> v4 = [A:2, B:1] items: {book, pen} (nothing lost)
Cassandra instead keeps one value per cell by timestamp: if Y's timestamp is higher,
X's change to that cell is silently discarded (per-cell, so different columns both survive)Real scenarios: a node reboots for a patch (hints cover the window, repair is cheap); a rack loses power for hours (hints expire, so run repair after); a multi-datacenter write during a WAN cut (sloppy quorum keeps accepting writes in Dynamo's design; Cassandra uses LOCAL_QUORUM to avoid depending on the other DC).
What prevents lost updates: nothing in the base model: both Dynamo and Cassandra accept concurrent writes and resolve them later. Use conditional writes (see Transactions) or model writes as inserts of new rows that are merged on read.
Fix / how to use it: run nodetool repair regularly within gc_grace_seconds (it compares Merkle trees; incremental repair is the default in recent versions), and treat any statement of the form "we wrote at ONE and read at ONE" as eventually consistent.
Query-first modeling, denormalization and duplication Must-know
In plain words: in a relational database you describe your data and ask questions later. Here you write down the questions first and build a table that answers each one, copying data as needed.
Common misunderstanding: "Duplicating data is a design smell." In a store with no joins it is the design. Cassandra's docs: "Data duplication and a high write throughput are used to achieve a high read performance." The smell is duplication without a plan to keep the copies in step.
Definition: Cassandra's data modeling intro opens: "Apache Cassandra data model is based around and optimized for querying." The method: (1) list the access patterns with their frequency and latency targets; (2) design one table (or one key schema in DynamoDB) per pattern so each read is one partition; (3) decide which attributes to copy into each; (4) decide how copies are written (in one batch, by a stream consumer, by a job). Compare the relational method in Schema Design.
Access patterns for a shop Tables (Cassandra) or key schemas (DynamoDB)
1 show a user's latest orders orders_by_user PK = user_id, SK = placed_at DESC
2 show all orders placed today (ops view) orders_by_day PK = (day, shard), SK = placed_at
3 find an order by its id (support) orders_by_id PK = order_id
4 place an order write ALL THREE (copy), idempotently
5 customer renames themselves update the copy in orders_by_user rows or accept stale nameReal scenarios: feeds and timelines (one table per timeline type); time-series by device and day; session and shopping-cart stores; IoT ingestion; messaging history by conversation.
What provides it:
| Product | How duplication is written | Keeping copies in step |
|---|---|---|
| Cassandra | BATCH (logged batch is atomic per call, not isolated), or app writes each table | Idempotent writes; repair; accept short divergence |
| DynamoDB | TransactWriteItems (up to 100 actions), or a stream consumer builds the second view | DynamoDB Streams to Lambda or a worker; GSIs do the copy for you, asynchronously |
| PostgreSQL | One normalised table plus indexes or materialised views | The database does it, transactionally |
| MongoDB | Embedding plus occasional references | Application and change streams |
Fix / how to use it: prefer a GSI when the second access path can tolerate eventual consistency and you accept the write cost of the copy; prefer an explicit second table or item when you need a different key and strong control.
-- Cassandra: the second copy, same data, different partition key
CREATE TABLE orders_by_id (
order_id uuid PRIMARY KEY,
user_id uuid,
placed_at timestamp,
total decimal
);
-- Logged batch: both inserts are applied, or neither, but it is not isolated
-- and spanning partitions costs coordinator work.
BEGIN BATCH
INSERT INTO orders_by_user (user_id, placed_at, order_id, total) VALUES (?, ?, ?, ?);
INSERT INTO orders_by_id (order_id, user_id, placed_at, total) VALUES (?, ?, ?, ?);
APPLY BATCH;Hot partitions and the celebrity problem Must-know
In plain words: the hash spreads keys evenly, but traffic is not even. If one key gets most of the requests, one partition does most of the work while the others idle, and you are throttled although the table as a whole is quiet.
Common misunderstanding: "I will raise the provisioned capacity." Capacity is shared across partitions but each has a ceiling. DynamoDB: "Every partition in a DynamoDB table is designed to deliver a maximum capacity of 3,000 read units per second and 1,000 write units per second." More table capacity does not lift a single partition's ceiling.
Definition: a hot partition is a partition whose request rate or size approaches the per-partition limit while the table's average is far below. Causes: a low-cardinality key (an order status, a boolean), a very popular key (a celebrity, a viral post, today's date as the key for a day's events), a sequential key (an auto-increment id in a range-partitioned store like Bigtable), or one big tenant in a multi-tenant table.
Celebrity problem: a follower feed keyed by the author
1 PK = AUTHOR#celebrity -> every follower write lands on one partition (1,000 WCU ceiling)
2 at 5,000 follows per second: ProvisionedThroughputExceededException on that key, table at 5%
3 fix A: PK = AUTHOR#celebrity#<0..15>, write picks one shard (hash of follower id)
4 fix B: do not store the celebrity's fan-out: pull model, merge the celebrity's timeline at read time
5 readers Query all 16 shard keys in parallel and merge by sort key (cost: 16 reads)Real scenarios: an e-commerce flash sale where all orders for one SKU hit one key; a metrics table keyed by DATE#2026-11-25 where all today's writes go to one partition; a social feed with one account that has millions of followers; a multi-tenant table where one tenant is 90% of traffic.
What prevents it:
| Technique | How | Cost |
|---|---|---|
| High-cardinality key | USER#<id>, DEVICE#<id> instead of STATUS#pending | None, if you do not need to list by status |
| Composite key | Add a bucket: (day, hour) or (device, day) | A query spans several keys |
| Write sharding | Random or hash suffix KEY#00..15; read all and merge | N reads per query; counts need aggregation |
| Adaptive capacity | DynamoDB "works by automatically increasing throughput capacity for partitions that receive more traffic", isolating hot items | Bounded by table throughput and the per-partition ceiling; helps skew, does not remove it |
| Caching | DAX or an application cache in front of hot reads | Staleness, invalidation |
| Time bucketing | Cassandra partitions per (sensor, day) so partitions stay bounded | More partitions to read for a range |
| Pull instead of push | Do not fan out the celebrity; merge at read time | Read-time work |
Fix / how to use it: the Go code below shards the write key; the lab shows the same 2,000 writes under a hot key and under a user key.
// shardedPK from the shard snippet: hash the event id so a retry lands on the same shard.
func shardedPK(logical, eventID string) string {
h := fnv.New32a()
_, _ = h.Write([]byte(eventID))
return fmt.Sprintf("%s#%02d", logical, h.Sum32()%shards)
}Cassandra has the same problem and a Cassandra-specific cousin: an unbounded partition (all of a device's readings forever) grows without limit, slows reads and compaction, and eventually hurts the node. Bound partitions with a time bucket in the partition key.
DynamoDB capacity: read and write units, on-demand, provisioned, adaptive Must-know
In plain words: DynamoDB bills and throttles in units. One read unit reads 4 KB, one write unit writes 1 KB. You either pay per request (on-demand) or reserve a rate per second (provisioned).
Common misunderstanding: "A strongly consistent read and an eventually consistent read cost the same." The first costs twice the second. And a 100-byte write still costs a full write unit.
Definition: "One read request unit represents one strongly consistent read operation per second, or two eventually consistent read operations per second, for an item up to 4 KB in size." Of writes: "One write request unit represents one write operation per second, for an item up to 1 KB in size." Larger items round up per 4 KB or 1 KB; a transactional read or write costs two units (see Transactions).
| Mode | How you pay | Scaling | Fits |
|---|---|---|---|
| On-demand | Per read or write request unit; nothing when idle | New tables sustain 4,000 writes and 12,000 reads per second; "instantly accommodates up to double the previous peak traffic on a table"; if traffic exceeds double the previous peak within 30 minutes it may be throttled while capacity is allocated | Spiky, unknown or new workloads; the documented default |
| Provisioned | For the capacity you reserve per hour, used or not | You set read and write units (optionally with auto scaling); exceeding them returns ProvisionedThroughputExceededException | Steady, predictable traffic where you can forecast |
Other facts: on-demand tables have a per-table throughput quota (the docs say 40,000 reads and writes by default, adjustable); you can configure a maximum on-demand throughput to cap runaway cost; switching provisioned to on-demand is limited to four times in 24 hours; warm throughput lets you pre-warm a table before a launch. Adaptive capacity is on for every table at no cost and "rebalances your partitions such that frequently accessed items don't reside on the same partition".
Cost of reading one 6 KB item
1 eventually consistent read: ceil(6 / 4) = 2 units, halved -> 1.0 read unit
2 strongly consistent read: ceil(6 / 4) = 2 units -> 2.0 read units
3 transactional read (TransactGetItems): 2 x 2 -> 4.0 read units
4 writing a 1.5 KB item: ceil(1.5 / 1) = 2 write units; transactional: 4Real scenarios: a marketing launch (on-demand, pre-warmed); a nightly ETL that writes a known rate (provisioned with auto scaling); a cache table of tiny items (on-demand, almost free when idle).
What provides it:
| Product | Capacity model | Throttling signal |
|---|---|---|
| DynamoDB | Read/write units, on-demand or provisioned | ProvisionedThroughputExceededException, ThrottlingException; SDKs retry with backoff |
| Cassandra / ScyllaDB | Nodes: you add machines | Timeouts, Unavailable, dropped mutations, pending compactions |
| Bigtable | Nodes | Latency rising with CPU |
| PostgreSQL | One server's CPU, IOPS, connections | Queueing, connection exhaustion |
Fix / how to use it: read and write consumption are returned by ReturnConsumedCapacity on every call (the lab prints it). Use projections and Limit to cut read units, keep items small, and prefer an eventually consistent read unless the next action depends on the latest value.
Single-table design Important
In plain words: instead of one table per entity, put users, orders and addresses in one table, with keys built so that everything one screen needs sits under one partition key and arrives in a single Query.
Common misunderstanding: "Single-table design is the only correct way to use DynamoDB." AWS describes it as one choice: it "allows you to store multiple types (entities) of data in a single DynamoDB table" to optimise access patterns, and also documents multiple-table design. The choice trades round trips for readability.
Definition: DynamoDB "stores items with the same partition key (known as an item collection) on the same partition(s) as each other". Single-table design puts related entities in the same item collection by sharing a partition key, uses a generic PK/SK and key prefixes (USER#, ORDER#) to tell entity types apart, and reads a whole collection, or a prefix of it with begins_with, in one request. Without LSIs, a large item collection is split over as many partitions as needed.
Screen: "My account" shows profile, last 10 orders and addresses
1 multi-table: GetItem(users) + Query(orders) + Query(addresses) = 3 round trips
2 single-table: Query PK = "USER#42", no SK condition = 1 round trip
3 the response is a mixed list: PROFILE, ADDRESS#home, ORDER#2026-11-25#o-9, ...
4 application maps item types by the SK prefix
5 "all orders" only: begins_with(SK, "ORDER#"), ScanIndexForward = false, Limit = 10Real scenarios: an account page; an order with its lines (ORDER#o-9 plus LINE#1, LINE#2); a tenant with its users and settings; a game session with its events.
What provides it:
| Choice | Strength | Weakness |
|---|---|---|
| Single table | One request per screen, smoother traffic, one capacity pool and one set of alarms | Opaque schema, hard analytics, harder migrations, one blast radius |
| One table per entity | Obvious schema, per-table capacity and TTL, simpler streams | More round trips; joins in application code |
| Cassandra | Tables per query (Cassandra tables are cheap in count only up to a point) | Many tables to write; keep the number in the low hundreds |
Fix / how to use it: document the key schema in code, one builder package for all key formats (Go: userPK, orderSK), and write down every access pattern next to the key it uses. The after snippet shows PK = USER#<id>, SK = ORDER#<timestamp>#<orderId> and a GSI for the inverse lookup.
Secondary indexes: GSI, LSI, Cassandra 2i and SAI Important
In plain words: the primary key is the only cheap lookup. An index is another copy of the data under a different key, kept in step for you, at a price.
Common misunderstanding: "An index makes any query fast." In these stores an index changes which key you can name; it does not give you ad-hoc filtering, and it multiplies write cost.
Definition:
| Index | Key | Consistency | Limits and cost |
|---|---|---|---|
| DynamoDB GSI | Own partition key and sort key; spans all partitions; separate storage | Always eventually consistent: "updated asynchronously, using an eventually consistent model" | 20 per table by default (adjustable); its own capacity; if its write capacity is insufficient, "the write activity on the table will be throttled" |
| DynamoDB LSI | Same partition key as the table, different sort key | Strong or eventual reads | 5 per table, not adjustable; 10 GB per distinct partition key value, including the base items; must be created with the table; ItemCollectionSizeLimitExceededException when exceeded |
| Cassandra 2i (legacy) | "all local indexes, stored in a hidden table on each node" | Local to each node's replica | Only recommended "when used in conjunction with a partition key"; without one the query fans out to many nodes |
| Cassandra SAI (5.0) | Storage-attached, per SSTable, multiple column types | Local to the node | "the most appropriate indexing method for most use cases"; still not a substitute for the right partition key |
| Cassandra materialised view | A server-maintained second table with another key | Maintained by Cassandra, eventually consistent | Disabled by default in the 5.0 config (materialized_views_enabled=false in the lab output); many teams write the second table themselves |
Why a GSI read can be stale
1 PutItem order o-9 (PK = USER#42) acknowledged
2 GSI (PK = order_id) is updated asynchronously, usually within moments
3 Query GSI order_id = "o-9" immediately -> may return nothing
4 ConsistentRead on a GSI is not supported -> retry or read the base table by keyReal scenarios: "who owns order X" (GSI on order_id); "orders of a user sorted by status" (LSI with status as sort key, same USER# partition key); "users by email" (GSI on email).
Fix / how to use it: a GSI Query uses the IndexName field (the ownerOfOrder function in the snippets), never ConsistentRead. Project only the attributes you need (KEYS_ONLY, INCLUDE, ALL) to cut index storage and write cost. Sparse indexes (only items that have the index key attribute are indexed) give you cheap "only the pending ones" views.
Transactions and conditions: TransactWriteItems and Cassandra LWT Must-know
In plain words: a plain write in these stores just lands, with no check on the old value. When you need "only if", or "these two items together or neither", there is a separate, slower, more expensive path.
Common misunderstanding: "DynamoDB transactions are like SQL transactions." They are bounded, item-set batches with all-or-nothing semantics and serializable isolation per item, not interactive BEGIN ... COMMIT sessions: no reads inside, no rollback by choice, fixed up front. And Cassandra "transactions" are single-partition compare-and-set, not multi-row transactions.
Definition:
DynamoDB TransactWriteItems | Cassandra lightweight transaction (LWT) | |
|---|---|---|
| Scope | "up to 100 write actions in a single all-or-nothing operation", across items and tables in one account and Region, at most 4 MB total | One partition: INSERT ... IF NOT EXISTS, UPDATE ... IF col = ?, DELETE ... IF |
| Actions | Put, Update, Delete, ConditionCheck; the same item cannot appear twice | A single conditional statement (or a conditional batch within one partition) |
| Isolation | Serializable between transactional operations; read-committed for a BatchGetItem as a unit | Linearizable per partition ("Lightweight transactions with linearizable consistency" is a listed guarantee) |
| Mechanism | Two underlying reads or writes per item (prepare and commit) | Paxos rounds between replicas; SERIAL or LOCAL_SERIAL consistency |
| Cost | Twice the capacity units of a normal operation | "non-negligible performance cost, because Paxos is used"; use sparingly |
| Idempotency | ClientRequestToken, valid for 10 minutes; same token with different parameters returns IdempotentParameterMismatch | The statement is naturally conditional; retries return [applied] = false |
| Failure | TransactionCanceledException with ordered CancellationReasons (SDKs do not retry it); TransactionConflictException for a plain write that collides with a transaction | Timeout during Paxos leaves the outcome unknown until read at SERIAL |
DynamoDB: place an order and decrement stock, all or nothing
1 TransactWriteItems(ClientRequestToken = "req-7f3a", [
2 Put ORDER#o-1 under USER#42, condition attribute_not_exists(PK),
3 Update SKU#9 STOCK: SET stock = stock - 2, condition stock >= 2 ])
4 prepare phase: DynamoDB checks both conditions before anything is committed
5 stock is 1: condition fails -> TransactionCanceledException
6 CancellationReasons = [ None, ConditionalCheckFailed ] (ordered like the request)
7 nothing was written; the order Put did not happen either
Cassandra LWT: claim a username
1 INSERT INTO usernames (name, user_id) VALUES ('ana', ?) IF NOT EXISTS
2 Paxos: prepare/promise, read, propose/accept, commit (several round trips)
3 returns [applied] = true -> you own it
4 a second INSERT of 'ana' returns [applied] = false and the existing rowReal scenarios: reserve a seat or the last item (ConditionExpression or IF); claim a unique username or email (a table keyed by the value); place an order with a stock decrement; idempotent payments with a request id as the key (attribute_not_exists); a distributed lock row with a TTL.
What provides it:
| Need | DynamoDB | Cassandra | PostgreSQL |
|---|---|---|---|
| Single-item compare-and-set | ConditionExpression on PutItem / UpdateItem (cheap) | UPDATE ... IF (Paxos, expensive) | UPDATE ... WHERE version = ? or SELECT ... FOR UPDATE |
| Multi-item atomic write | TransactWriteItems | Not across partitions in 5.0 (logged batch is atomic but not isolated) | Ordinary transaction |
| Unique constraint | Item whose key is the unique value, attribute_not_exists | IF NOT EXISTS on a lookup table | UNIQUE constraint |
| Aggregate across rows | Not available; maintain counters or use streams | Counters (not idempotent), or SELECT then compute | SUM() in the same transaction |
Fix / how to use it: keep each invariant inside one item or one partition, so a conditional write is enough. For the rest, see the Go (tx snippet) and PHP (PlaceOrder) below. The general theory of locks and optimistic checks is in Optimistic vs Pessimistic Locking and Distributed SQL, Consensus & 2PC; in particular, isolation levels mostly do not apply to these stores.
TTL Important
In plain words: you stamp an item with an expiry time and the database removes it later, so sessions, caches and short-lived events clean themselves up.
Common misunderstanding: "TTL deletes at exactly the expiry time." DynamoDB "automatically deletes expired items within a few days of their expiration time, without consuming write throughput", so expired items can still appear in reads and must be filtered. In Cassandra the expired cell becomes a tombstone that lingers until compaction.
Definition:
| DynamoDB TTL | Cassandra TTL | |
|---|---|---|
| Set by | A Number attribute holding a Unix epoch time (seconds), named in the table's TTL setting | USING TTL <seconds> per write, or default_time_to_live per table |
| Cost | The deletion consumes no write capacity | Expiry writes a tombstone (see below) |
| Visible after expiry? | Yes, until the background deletion; filter with a condition | No (reads treat it as dead), but the tombstone is read until purged |
| Side effects | Deletions appear in DynamoDB Streams as service deletions, and in indexes like normal deletes | A table full of TTL tombstones slows reads; use TWCS |
Fix / how to use it: in Laravel the dynamodb cache store needs a table with TTL enabled on expires_at; in Cassandra pair TTL with Time Window Compaction Strategy ("designed for TTL'ed, mostly immutable time-series data") so whole expired SSTables drop at once.
Tombstones and deletes Must-know
In plain words: Cassandra never edits a file in place, so a delete is a new entry saying "this is gone". Until that entry is cleaned up, every read has to step over it.
Common misunderstanding: "I deleted the rows, so the table is small and fast again." The data and the markers are on disk until compaction runs after gc_grace_seconds, and reads scan the markers. A table used as a queue is the textbook way to turn fast writes into slow reads.
Definition: "Cassandra treats a deletion as an insertion, and inserts a time-stamped deletion marker called a tombstone." Tombstones replicate to every replica and are kept for gc_grace_seconds: "Its default value is 864000 seconds (ten days), after which a tombstone expires and can be deleted during compaction." The grace period gives repair time to deliver the tombstone to a replica that missed it; if the tombstone is purged before a replica that never saw it is repaired, the old data comes back (a zombie). Kinds: cell, row, range (from a range delete) and partition tombstones, and TTL expiry. The server logs Read N live rows and M tombstone cells and warns past tombstone_warn_threshold (1000 in the 5.0 config) and fails the query past tombstone_failure_threshold (100000).
Queue in a table, one partition "jobs"
1 producers INSERT 5,000 rows (id 1..5000)
2 consumers process and DELETE ids 1..4999 -> 4,999 tombstones, all before id 5000
3 SELECT ... WHERE q = 'jobs' LIMIT 1 must walk past all 4,999 markers to reach id 5000
4 trace: Read 1 live rows and 4999 tombstone cells
5 compaction before gc_grace_seconds expires keeps the tombstones; after it, they are droppedReal scenarios: a work queue built on a table; a list column with many removals; a time-series table with TTL on every row; deleting a large range by key; frequent overwrites with nulls (a null write is a tombstone).
What prevents it:
| Technique | How |
|---|---|
| Do not use the table as a queue | Use a real queue (RabbitMQ or Kafka) or partition by time and drop whole partitions |
| Time-window compaction with TTL | Whole expired SSTables are dropped without scanning |
| Never write nulls | Omit the column on insert; use UNSET bind values in drivers |
| Bound partitions | Time-bucket the partition key so scans stay short |
Tune gc_grace_seconds carefully | Lowering it without running repair inside the window risks zombies; it can be 0 on a single node, as the lab does |
| Repair inside the grace period | See Repair |
DynamoDB has no tombstones; a delete is a write, billed as one, and the item is gone from reads. Redis DEL and PostgreSQL deletes are different again: PostgreSQL leaves dead tuples that VACUUM reclaims (MVCC, VACUUM & Bloat).
Compaction and the storage engine Important
In plain words: both stores write sequentially into a memory table and flush immutable sorted files. A background job merges those files, drops overwritten values and expired tombstones, and keeps reads from checking too many files.
Common misunderstanding: "Writes are free." Each write is cheap now and creates compaction work later; compaction competes with reads for disk and CPU.
Definition: the design is Bigtable's: memtable plus commit log, then SSTables ("a persistent, ordered immutable map"). The mechanics (write amplification, levelled vs size-tiered vs time-window) are in Storage Engines and Cassandra & ScyllaDB in Depth.
| Strategy (Cassandra) | Good for | Trade-off |
|---|---|---|
| Size-tiered (STCS) | Write-heavy, general | Space spikes during a merge |
| Leveled (LCS) | Read-heavy, many updates | More write amplification |
| Time-window (TWCS) | TTL time series | Do not update old windows |
| Unified (UCS, 5.0) | One strategy that adapts | Newer |
DynamoDB's storage engine is managed and not configurable; you pay for storage, not for compaction. Related Bloom-filter use in the read path: Bloom Filters & Probabilistic Structures.
Anti-entropy: repair, read repair and gossip Important
In plain words: replicas drift apart (a node was down, a hint was lost). Repair compares fingerprints of the data on each replica and copies whatever differs.
Common misunderstanding: "Cassandra repairs itself." Hints and read repair help, but only nodetool repair (or a managed repair service) closes everything. The docs say repair is "not run automatically by Cassandra. It is run by the operator via nodetool."
Definition: repair "compares the data with merkle trees, which are a hierarchy of hashes" and streams the differing ranges. There are full repairs (all data in the range) and incremental repairs (only data written since the last one, the default); "once an incremental repair marks data as repaired, it won't try to repair it again", so run a full repair occasionally. Dynamo's paper describes the same idea per key range: "A Merkle tree is a hash tree where leaves are hashes of the values of individual keys."
Why repair must finish inside gc_grace_seconds
1 day 0: DELETE row; replicas A, B get the tombstone, C is down
2 day 10: gc_grace_seconds passes; A and B purge the tombstone at compaction
3 day 11: C returns holding the original row; nobody has the tombstone any more
4 repair (or a read at QUORUM) now sees one replica with the row, two without -> the row is resurrected
5 fix: run repair at least once per gc_grace_seconds, so C receives the tombstone firstDynamoDB has no operator-visible repair: replication and convergence are the service's job.
Streams and change data capture Important
In plain words: every change to the table is also written to an ordered log that another process can read to build a copy, a search index, an audit trail or an event.
Common misunderstanding: "A stream is a durable event store." DynamoDB Streams keeps records "for up to 24 hours", and per-item order is guaranteed but not cross-item order; Cassandra CDC leaves commit-log segments on disk until a consumer parses and removes them.
Definition:
| DynamoDB Streams | Cassandra CDC | |
|---|---|---|
| Enable | Per table, with a StreamViewType that cannot be edited once set | WITH cdc = true per table; cdc_enabled: true and cdc_raw_directory in the node config |
| Content | KEYS_ONLY, NEW_IMAGE, OLD_IMAGE, NEW_AND_OLD_IMAGES | Commit-log segments of mutations; you parse them |
| Retention | 24 hours | Until your consumer removes the files; the node blocks CDC writes if the CDC directory fills (cdc_block_writes) |
| Delivery | "Each stream record appears exactly once in the stream"; per-item order | Per replica; duplicates across replicas, so consumers de-duplicate |
| Consumers | AWS Lambda triggers, the Kinesis adapter, Flink | Debezium and similar connectors |
Keeping a second view in sync from a stream (DynamoDB)
1 write order o-9 -> table; stream record NEW_AND_OLD_IMAGES, in item order
2 consumer reads the shard, parents before children (shards split)
3 consumer writes the view item idempotently (key = order id, version attribute)
4 consumer crashes after the write, before the checkpoint -> record is read again
5 idempotent write makes the replay harmless (the same pattern as the outbox)Real scenarios: search index updates; cache invalidation; an audit log; cross-region copies; building a GSI-like view with different keys; feeding analytics (OLTP vs OLAP). The relational parallel is the outbox pattern and logical decoding.
Transactions and streams interact: "stream records from the same transaction might appear at different times and could be interleaved with records from other transactions. Stream consumers shouldn't assume transaction atomicity or ordering guarantees."
Multi-region and multi-datacenter Important
In plain words: keep copies of the data in several regions so users read locally and one region can fail. The hard part is two regions writing the same key at the same moment.
Common misunderstanding: "Multi-region means strongly consistent everywhere." By default it means asynchronous replication and last-writer-wins. Strong consistency across regions is an opt-in mode that costs latency and availability.
Definition:
| DynamoDB global tables | Cassandra multi-datacenter | |
|---|---|---|
| Model | "fully managed, multi-Region, and multi-active"; any replica can serve reads and writes | Keyspace with NetworkTopologyStrategy, a replication factor per datacenter |
| Consistency | MREC (multi-Region eventual consistency, the default) or MRSC (multi-Region strong consistency); cannot change after creation | Per query: LOCAL_QUORUM (local), EACH_QUORUM (all DCs), QUORUM (global majority) |
| Conflicts | Last-writer-wins | Last-write-wins by cell timestamp |
| Transactions | ACID only in the Region where the write was made; other Regions "may observe partially completed transactions" while changes replicate | LWT with LOCAL_SERIAL scope or SERIAL across DCs |
| Operational cost | Per-Region replicated write units and storage | Your own inter-DC bandwidth and repair |
Two regions write the same item at the same time (MREC)
1 us-east-1: UpdateItem plan = "pro" at t = 100.020
2 eu-west-1: UpdateItem plan = "free" at t = 100.018
3 both succeed locally; replication crosses
4 last-writer-wins: "pro" wins in both Regions; the "free" write is silently dropped
5 fix: partition write ownership by region (a home region per user), or use MRSC for that tableReal scenarios: an active-active SaaS with users in two continents; disaster recovery with a warm region; read-local latency for a global product catalogue; GDPR data residency (keep a user's data in a region, which needs careful key and replication design).
Fix / how to use it: route each user to a home region and write there; use LOCAL_QUORUM in Cassandra so a WAN failure does not stop writes; accept that cross-region reads can be stale. The replication mechanics of single-primary systems are in Replication, Read Replicas & Failover.
Cost models Important
In plain words: DynamoDB's cost is a function of requests and storage; Cassandra's is a function of machines. Neither is "cheap": the cost is in the design.
Common misunderstanding: "On-demand is always cheaper" or "provisioned is always cheaper." On-demand wins for spiky or unknown traffic (nothing is charged when idle); provisioned wins for steady, forecastable traffic; both lose to a bad key design that multiplies reads.
| Cost driver | DynamoDB | Cassandra / ScyllaDB |
|---|---|---|
| Reads | Read units; strong reads cost 2x; Scan reads everything; filters do not reduce the bill | Cluster CPU and I/O; reads at QUORUM touch more replicas |
| Writes | Write units, per 1 KB; a GSI multiplies writes; a transaction doubles them; global tables replicate every write | Replication factor multiplies writes; LOCAL_QUORUM waits for fewer remote acks |
| Storage | Per GB; indexes store copies | Disks times replication factor; compaction needs free space |
| Idle | Nothing in on-demand; reserved in provisioned | Machines always run |
| People | Almost no operations | Repair, upgrades, compaction tuning, capacity planning |
| Scaling steps | Automatic, subject to the quotas above | You add nodes; streaming takes time |
Prices change; this page deliberately names no dollar amounts. Measure with ReturnConsumedCapacity, estimate in units, and read the provider's current price page.
A write that looks small but is not
1 one 1 KB order item -> 1 write unit
2 the table has 2 GSIs that project the item -> +1 write per index, billed to the index capacity
3 placed inside TransactWriteItems -> the table write is done twice (prepare + commit): 2 write units
4 replicated to a second Region (global table)-> the replicated writes are billed in that Region tooWhen PostgreSQL is enough Must-know
In plain words: a well-indexed PostgreSQL on a modern machine handles a very large workload, and it lets you ask new questions later. Do not adopt a wide-column store for fashion.
Common misunderstanding: "PostgreSQL does not scale, so I need Cassandra." One primary with read replicas, partitioning and good indexes serves many teams for their whole lifetime; the scale ladder is in Storage & Data Scaling and Partitioning & Sharding in PostgreSQL. Adopting a wide-column store adds new operational and modeling costs.
| Signal | PostgreSQL (or MySQL InnoDB, SQL Server, Oracle) is enough | A wide-column / key-value store earns its place |
|---|---|---|
| Queries | Exploratory, reporting, many joins | Few, known, key-based |
| Data size | Up to a few TB on one node, with partitioning to tens of TB | Beyond what one primary and its replicas can hold or write |
| Writes | Thousands per second on one primary | Sustained write rates one primary cannot absorb |
| Consistency | Needs transactions across entities, constraints | Single-key or single-partition correctness is enough |
| Availability | Single region with failover | Active-active multi-region, no maintenance window |
| Team | Knows SQL, small ops capacity | Has operators for Cassandra, or buys DynamoDB's operations |
| Cost of a wrong choice | A new query is an index | A new query is a new table, a backfill and a dual-write period |
Middle paths: a key-value access pattern in Redis for cache and counters; a document model in MongoDB; distributed SQL such as CockroachDB when you want scale and transactions (Distributed SQL, Consensus & 2PC); SQLite for embedded cases (SQLite); and the map of all families in NoSQL: Families & Data Models.
Per-engine behaviour
Matrix: what each store really does
| Property | DynamoDB | Cassandra | ScyllaDB | Bigtable / HBase | Redis | MongoDB | PostgreSQL |
|---|---|---|---|---|---|---|---|
| Model | Items with attributes, PK + SK | Partition + clustering rows (CQL) | Same as Cassandra (CQL, plus a DynamoDB-compatible API) | Sorted sparse map of row, column family, qualifier, timestamp | Key to data structure | JSON documents | Relational rows |
| Distribution | Hash on partition key | Murmur3 token ring | Same ring, shard per CPU core | Range of row keys (tablets / regions) | 16384 hash slots in Redis Cluster | Shard key (hash or range) | One primary; partitioning or Citus for more |
| Master | Managed | None | None | Master + lock service | Primary per shard | Primary per replica set | Primary |
| Default read | Eventually consistent | Set by client | Set by client | Strong per row | Primary | Primary, local concern | Primary |
| Cross-key transaction | TransactWriteItems, 100 actions | None in 5.0 (LWT per partition) | None (LWT per partition) | Single-row | MULTI on one shard | Multi-document, snapshot | Full ACID |
| Secondary index | GSI, LSI | 2i, SAI | 2i, global 2i, views | Application-built | Application-built / search modules | Built in, any field | Built in (B-tree, GIN, GiST) |
| Conflict rule | Last writer (global tables) | Last write by cell timestamp | Same | Single writer per tablet | Single writer | Single primary | Serializable options |
| Deletes | Item removed | Tombstone, gc_grace_seconds | Tombstone | Delete markers until compaction | Immediate | Immediate (WiredTiger) | Dead tuples until VACUUM |
| Change feed | Streams (24 h) | CDC | CDC | Replication / change streams (version-specific) | Keyspace notifications, Streams | Change streams | Logical decoding |
| Best at | Serverless key access at any scale | Write-heavy, multi-DC, self-hosted | Same, lower latency per core | Huge sorted scans, time series | Cache, counters, queues | Flexible documents | Everything relational |
This is a conceptual comparison; for ScyllaDB's shard-per-core design, its compaction and its DynamoDB-compatible API (Alternator), go to Cassandra & ScyllaDB in Depth.
The same business rule in each store
Rule: "a username is unique."
| Store | How |
|---|---|
| PostgreSQL | UNIQUE (username); a second insert fails with 23505 |
| MySQL InnoDB | UNIQUE KEY; error 1062 |
| SQL Server / Oracle | Unique constraint or unique index |
| SQLite | UNIQUE; SQLITE_CONSTRAINT |
| MongoDB | Unique index; E11000 duplicate key |
| Redis | SET username:ana id NX |
| DynamoDB | A lookup item USERNAME#ana with attribute_not_exists(PK); both in one TransactWriteItems with the user item |
| Cassandra | A lookup table usernames (name PRIMARY KEY, ...) with INSERT ... IF NOT EXISTS (Paxos) |
| CockroachDB | UNIQUE index; serializable, retry 40001 |
Mechanics
Knobs and limits
| Setting | Meaning | Value |
|---|---|---|
| DynamoDB partition ceiling | Read / write units per partition per second | 3,000 / 1,000 |
| DynamoDB read unit | One strongly consistent read of 4 KB, or two eventually consistent | 4 KB |
| DynamoDB write unit | One write of 1 KB | 1 KB |
| Query / Scan page | Up to 1 MB of data, then LastEvaluatedKey | 1 MB |
TransactWriteItems | Actions and total size | 100 actions, 4 MB; capacity is doubled |
ClientRequestToken | Idempotency window | 10 minutes |
| GSIs / LSIs per table | Defaults | 20 (adjustable) / 5 (not) |
| LSI item collection | Per partition key value | 10 GB, including indexes |
| On-demand start | New table sustained rate | 4,000 writes and 12,000 reads per second; up to double the previous peak instantly |
| DynamoDB Streams retention | How long records stay readable | 24 hours |
Cassandra gc_grace_seconds | Tombstone grace | 864000 (10 days) |
Cassandra tombstone_warn_threshold | Log a warning | 1000 |
Cassandra tombstone_failure_threshold | Fail the read | 100000 |
Cassandra max_hint_window | How long a node stores hints for a down peer | 3 hours |
Cassandra num_tokens | Vnodes per node | 16 in the 5.0 default configuration |
Cassandra cas_contention_timeout | LWT contention wait | 1000 ms |
Cassandra batch_size_warn_threshold / batch_size_fail_threshold | Batch size | 5 KiB / 50 KiB |
gocql ClusterConfig.Consistency | Default level | Quorum |
Error codes you will catch
| Error | Store | Meaning | Retry? |
|---|---|---|---|
ProvisionedThroughputExceededException | DynamoDB | Exceeded provisioned throughput of a table or GSI | Yes, with exponential backoff (SDKs do it); fix the key if it persists |
ThrottlingException | DynamoDB | Rate of requests exceeds allowed throughput (also control plane) | Yes, with backoff |
ConditionalCheckFailedException | DynamoDB | Your ConditionExpression evaluated to false | No: a business answer |
TransactionCanceledException | DynamoDB | An action in TransactWriteItems or TransactGetItems was rejected; CancellationReasons ordered like the request | Only if the reason is TransactionConflict or throttling; the SDK does not retry it |
TransactionConflictException | DynamoDB | A plain write collided with an ongoing transaction on the same item | Yes, with backoff |
IdempotentParameterMismatch | DynamoDB | Same ClientRequestToken, different parameters | No: a bug |
ItemCollectionSizeLimitExceededException | DynamoDB | LSI item collection above 10 GB | No: change the key |
ValidationException | DynamoDB | Missing parameter, bad type or range, wrong key schema | No |
Unavailable (0x1000) | Cassandra | Not enough live replicas for the consistency level | Maybe at a lower level; fix the cluster |
Write_timeout (0x1100) | Cassandra | Coordinator did not get enough acks in time; the write may still apply | Only if idempotent |
Read_timeout (0x1200) | Cassandra | Not enough replicas answered in time | Yes, if the query is safe |
CAS_WRITE_UNKNOWN (0x1700) | Cassandra | A contended LWT was partly done; the outcome is unknown | Read at SERIAL, then decide |
Write_failure (0x1500) | Cassandra | A non-timeout failure on a replica | Investigate |
Where the request goes
DynamoDB request path
1 client SDK signs and sends PutItem to the regional endpoint
2 the service authenticates the request and finds the partition for hash(PK) (simplified model)
3 the item is written and replicated across multiple Availability Zones in the Region
4 acknowledged -> GSIs are updated asynchronously, a stream record is emitted
5 over a partition or table limit? the request is throttled instead
Cassandra request path (QUORUM write, RF = 3)
1 driver picks a coordinator (token-aware: a replica for the key)
2 coordinator hashes the key, finds replicas R1, R2, R3 on the ring
3 sends the mutation to all three; each appends to the commit log and the memtable
4 after 2 acks, answers the client; the third (or a hint) catches up
5 memtable flushes to an SSTable; compaction merges laterSolving the classic problems
Problem: queries that scan
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Name the partition key | Query with KeyConditionExpression | One partition, cost proportional to the result | You must know the key |
| Add a GSI | Index on the other attribute | New access path | Eventual consistency, write cost |
| Another table or item | Duplicate under a different key | Full control, strong reads | You maintain the copy |
Do not use Scan + FilterExpression | The filter runs after the read | None | Whole-table cost |
The before and after code:
// Package main shows a DynamoDB design that treats the table like a SQL table:
// a low-cardinality partition key and a Scan to answer a per-user question.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
// ordersTable is keyed by status. There are only a handful of statuses, so
// almost every write for "pending" orders lands on the same partition
// (the hot partition), and one partition is capped at 1,000 writes/second.
func ordersTable() *dynamodb.CreateTableInput {
return &dynamodb.CreateTableInput{
TableName: aws.String("orders"),
AttributeDefinitions: []types.AttributeDefinition{
{AttributeName: aws.String("status"), AttributeType: types.ScalarAttributeTypeS},
{AttributeName: aws.String("order_id"), AttributeType: types.ScalarAttributeTypeS},
},
KeySchema: []types.KeySchemaElement{
{AttributeName: aws.String("status"), KeyType: types.KeyTypeHash},
{AttributeName: aws.String("order_id"), KeyType: types.KeyTypeRange},
},
BillingMode: types.BillingModePayPerRequest,
}
}
// ordersOfUser has no key to look up by user, so it reads every item in the
// table and discards what does not match. FilterExpression runs AFTER the
// read, so the whole table is still billed.
func ordersOfUser(userID string) *dynamodb.ScanInput {
return &dynamodb.ScanInput{
TableName: aws.String("orders"),
FilterExpression: aws.String("user_id = :u"),
ExpressionAttributeValues: map[string]types.AttributeValue{
":u": &types.AttributeValueMemberS{Value: userID},
},
}
}
func main() {
// Constructing a client needs no credentials; nothing is sent here.
_ = dynamodb.New(dynamodb.Options{Region: "us-east-1"})
fmt.Println(aws.ToString(ordersTable().TableName))
fmt.Println(aws.ToString(ordersOfUser("42").FilterExpression))
}The before design keys the table by status (a handful of values, so one hot partition) and answers a per-user question with a Scan. The after design uses PK = USER#<id>, SK = ORDER#<timestamp>#<orderId>, a Query with KeyConditionExpression, a ConsistentRead parameter that is a decision, and a GSI for "who owns order X":
// Package main models orders around the access patterns: one partition per
// user, orders sorted by time inside it, and a GSI for the inverse lookup.
package main
import (
"fmt"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
const (
table = "orders"
gsiByRef = "order_id-index"
)
func userPK(userID string) string { return "USER#" + userID }
func orderSK(at time.Time, orderID string) string {
// RFC 3339 in UTC sorts lexicographically in time order.
return "ORDER#" + at.UTC().Format(time.RFC3339) + "#" + orderID
}
// ordersTable: PK spreads users across partitions, SK orders one user's
// items together. The GSI answers "which user owns order X?".
func ordersTable() *dynamodb.CreateTableInput {
s := types.ScalarAttributeTypeS
return &dynamodb.CreateTableInput{
TableName: aws.String(table),
AttributeDefinitions: []types.AttributeDefinition{
{AttributeName: aws.String("PK"), AttributeType: s},
{AttributeName: aws.String("SK"), AttributeType: s},
{AttributeName: aws.String("order_id"), AttributeType: s},
},
KeySchema: []types.KeySchemaElement{
{AttributeName: aws.String("PK"), KeyType: types.KeyTypeHash},
{AttributeName: aws.String("SK"), KeyType: types.KeyTypeRange},
},
GlobalSecondaryIndexes: []types.GlobalSecondaryIndex{{
IndexName: aws.String(gsiByRef),
KeySchema: []types.KeySchemaElement{
{AttributeName: aws.String("order_id"), KeyType: types.KeyTypeHash},
},
Projection: &types.Projection{ProjectionType: types.ProjectionTypeKeysOnly},
}},
BillingMode: types.BillingModePayPerRequest,
}
}
// latestOrders reads one partition, newest first. ConsistentRead is a
// decision: true costs twice an eventually consistent read, and is right for
// "show the order I just placed"; false is right for a history screen.
func latestOrders(userID string, strong bool, limit int32) *dynamodb.QueryInput {
return &dynamodb.QueryInput{
TableName: aws.String(table),
KeyConditionExpression: aws.String("PK = :pk AND begins_with(SK, :prefix)"),
ExpressionAttributeValues: map[string]types.AttributeValue{
":pk": &types.AttributeValueMemberS{Value: userPK(userID)},
":prefix": &types.AttributeValueMemberS{Value: "ORDER#"},
},
ScanIndexForward: aws.Bool(false),
Limit: aws.Int32(limit),
ConsistentRead: aws.Bool(strong),
}
}
// ownerOfOrder uses the GSI. Reads from a GSI are always eventually
// consistent, so ConsistentRead must not be set here.
func ownerOfOrder(orderID string) *dynamodb.QueryInput {
return &dynamodb.QueryInput{
TableName: aws.String(table),
IndexName: aws.String(gsiByRef),
KeyConditionExpression: aws.String("order_id = :o"),
ExpressionAttributeValues: map[string]types.AttributeValue{
":o": &types.AttributeValueMemberS{Value: orderID},
},
}
}
func main() {
// Constructing a client needs no credentials; nothing is sent here.
_ = dynamodb.New(dynamodb.Options{Region: "us-east-1"})
fmt.Println(orderSK(time.Unix(0, 0), "o-1"))
fmt.Println(aws.ToString(latestOrders("42", true, 20).KeyConditionExpression))
fmt.Println(aws.ToString(ownerOfOrder("o-1").IndexName))
_ = ordersTable()
}Problem: hot key and celebrity writes
Shard the write key and fan out on read. The helper hashes the event id so a retry lands on the same shard; 16 shards support about 16,000 writes per second at the documented ceiling.
// Package main shows write sharding for a hot key: append a small random
// suffix on write, fan out over all suffixes on read, and merge.
package main
import (
"fmt"
"hash/fnv"
"sort"
)
// shards is chosen from the expected peak: a partition takes about 1,000
// writes per second, so 10,000 writes per second needs at least 10 shards.
const shards = 16
// shardedPK spreads one logical key (a day, a celebrity) over many partitions.
// Hashing the event id keeps retries on the same shard; rand.Intn would not.
func shardedPK(logical, eventID string) string {
h := fnv.New32a()
_, _ = h.Write([]byte(eventID))
return fmt.Sprintf("%s#%02d", logical, h.Sum32()%shards)
}
// allPKs is what a reader must query: one Query per shard, in parallel,
// then merge by sort key. That is the price of the fix.
func allPKs(logical string) []string {
out := make([]string, 0, shards)
for i := 0; i < shards; i++ {
out = append(out, fmt.Sprintf("%s#%02d", logical, i))
}
return out
}
func main() {
count := map[string]int{}
for i := 0; i < 10000; i++ {
count[shardedPK("DATE#2026-11-25", fmt.Sprintf("evt-%d", i))]++
}
keys := make([]string, 0, len(count))
for k := range count {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys[:3] {
fmt.Println(k, count[k])
}
fmt.Println(len(allPKs("DATE#2026-11-25")), "queries per read")
}// PHP counterpart of the shard snippet (full file: ShardedKey.php)
public static function forWrite(string $logical, string $eventId): string
{
return sprintf('%s#%02d', $logical, crc32($eventId) % self::SHARDS);
}The full PHP file:
<?php
namespace App\Orders;
// Write sharding for a hot logical key: spread writes over N suffixes,
// read by querying all N and merging. crc32 is stable across processes.
final class ShardedKey
{
public const SHARDS = 16;
public static function forWrite(string $logical, string $eventId): string
{
return sprintf('%s#%02d', $logical, crc32($eventId) % self::SHARDS);
}
/** @return list<string> every partition key a reader must query */
public static function forRead(string $logical): array
{
return array_map(
fn (int $i) => sprintf('%s#%02d', $logical, $i),
range(0, self::SHARDS - 1),
);
}
}Problem: all-or-nothing writes and uniqueness
| Need | Preferred solution | Alternative |
|---|---|---|
| Create only if absent | PutItem with attribute_not_exists(PK); Cassandra IF NOT EXISTS | A lookup table keyed by the unique value |
| Decrement stock safely | UpdateItem with ConditionExpression stock >= :q | TransactWriteItems with the order Put |
| Several items together | TransactWriteItems (100 actions) | Saga with compensations (microservices) |
| Retry-safe | ClientRequestToken | A request id as the key |
Go (aws-sdk-go-v2), building the transaction and mapping the error to a decision:
// Package main builds a TransactWriteItems request: place an order, decrement
// stock and fail the whole thing if stock would go negative. Nothing is sent.
package main
import (
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
const table = "shop"
func s(v string) types.AttributeValue { return &types.AttributeValueMemberS{Value: v} }
func n(v string) types.AttributeValue { return &types.AttributeValueMemberN{Value: v} }
// placeOrder groups two actions on two different items (the same item cannot
// appear twice in one transaction). ClientRequestToken makes a retry within
// 10 minutes idempotent: the same token with the same body is a no-op.
func placeOrder(userID, orderID, sku string, qty int, token string) *dynamodb.TransactWriteItemsInput {
return &dynamodb.TransactWriteItemsInput{
ClientRequestToken: aws.String(token),
TransactItems: []types.TransactWriteItem{
{Put: &types.Put{
TableName: aws.String(table),
Item: map[string]types.AttributeValue{
"PK": s("USER#" + userID), "SK": s("ORDER#" + orderID), "sku": s(sku),
},
// Refuse to overwrite an existing order with the same id.
ConditionExpression: aws.String("attribute_not_exists(PK)"),
}},
{Update: &types.Update{
TableName: aws.String(table),
Key: map[string]types.AttributeValue{"PK": s("SKU#" + sku), "SK": s("STOCK")},
UpdateExpression: aws.String("SET stock = stock - :q"),
ConditionExpression: aws.String("stock >= :q"),
ExpressionAttributeValues: map[string]types.AttributeValue{
":q": n(fmt.Sprint(qty)),
},
// Return the item in the cancellation reason when the condition fails.
ReturnValuesOnConditionCheckFailure: types.ReturnValuesOnConditionCheckFailureAllOld,
}},
},
}
}
// explain turns the SDK error into a decision. The SDK does not retry
// TransactionCanceledException; reasons are ordered like TransactItems.
func explain(err error) string {
var tc *types.TransactionCanceledException
if errors.As(err, &tc) {
for i, r := range tc.CancellationReasons {
switch aws.ToString(r.Code) {
case "ConditionalCheckFailed":
return fmt.Sprintf("action %d: condition failed (out of stock or duplicate): do not retry", i)
case "TransactionConflict":
return fmt.Sprintf("action %d: concurrent transaction: retry with backoff", i)
case "ThrottlingError", "ProvisionedThroughputExceeded":
return fmt.Sprintf("action %d: throttled: retry with backoff", i)
}
}
}
return "other error"
}
// retryable reports whether a failed transaction is worth retrying with backoff:
// a conflict with another transaction, or throttling. A failed condition is an
// answer, not a fault, so it is never retried.
func retryable(err error) bool {
var tc *types.TransactionCanceledException
if !errors.As(err, &tc) {
return false
}
for _, r := range tc.CancellationReasons {
switch aws.ToString(r.Code) {
case "TransactionConflict", "ThrottlingError", "ProvisionedThroughputExceeded":
return true
}
}
return false
}
func main() {
in := placeOrder("42", "o-1", "sku-9", 2, "req-7f3a")
fmt.Println(len(in.TransactItems), aws.ToString(in.ClientRequestToken))
failed := &types.TransactionCanceledException{
CancellationReasons: []types.CancellationReason{{Code: aws.String("None")}, {Code: aws.String("ConditionalCheckFailed")}},
}
fmt.Println(explain(failed), retryable(failed))
}Laravel with the AWS SDK for PHP (Aws\DynamoDb\DynamoDbClient::transactWriteItems):
<?php
namespace App\Orders;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Exception\DynamoDbException;
use Aws\DynamoDb\Marshaler;
// TransactWriteItems: place an order and decrement stock, all or nothing.
// Two different items, because one item may appear only once per transaction.
class PlaceOrder
{
public function __construct(
private readonly DynamoDbClient $client,
private readonly Marshaler $marshaler,
private readonly string $table = 'shop',
) {}
/**
* @return bool true when applied, false when the stock condition failed
*
* @throws DynamoDbException for conflicts and throttling (callers retry those)
*/
public function __invoke(string $userId, string $orderId, string $sku, int $qty, string $token): bool
{
try {
$this->client->transactWriteItems([
// The same token and body within 10 minutes is a no-op, so a
// queue job that retries after a timeout cannot double-charge.
'ClientRequestToken' => $token,
'TransactItems' => [
['Put' => [
'TableName' => $this->table,
'Item' => $this->marshaler->marshalItem([
'PK' => 'USER#'.$userId,
'SK' => 'ORDER#'.$orderId,
'sku' => $sku,
]),
'ConditionExpression' => 'attribute_not_exists(PK)',
]],
['Update' => [
'TableName' => $this->table,
'Key' => $this->marshaler->marshalItem(['PK' => 'SKU#'.$sku, 'SK' => 'STOCK']),
'UpdateExpression' => 'SET stock = stock - :q',
'ConditionExpression' => 'stock >= :q',
'ExpressionAttributeValues' => $this->marshaler->marshalItem([':q' => $qty]),
]],
],
]);
return true;
} catch (DynamoDbException $e) {
if ($e->getAwsErrorCode() === 'TransactionCanceledException'
&& str_contains($e->getMessage(), 'ConditionalCheckFailed')) {
return false; // out of stock or duplicate order id: do not retry
}
throw $e; // TransactionConflict / throttling: let the job retry with backoff
}
}
}Problem: Cassandra consistency, LWT and TTL from Go
github.com/gocql/gocql sets consistency per query, serial consistency for LWT, and the TTL in the statement. (The project continues at github.com/apache/cassandra-gocql-driver; the import path used by most code today is github.com/gocql/gocql.)
// Package main shows the gocql calls that matter for this page: consistency
// per query, a lightweight transaction (Paxos) and a TTL. Nothing connects:
// every function takes the session, so the file only has to compile.
package main
import (
"fmt"
"time"
"github.com/gocql/gocql"
)
// newCluster: LocalQuorum for reads and writes gives read-your-writes inside
// one datacenter without paying cross-DC latency. DCAwareRoundRobin keeps the
// coordinator local.
func newCluster(hosts ...string) *gocql.ClusterConfig {
c := gocql.NewCluster(hosts...)
c.Keyspace = "shop"
c.Consistency = gocql.LocalQuorum
c.Timeout = 2 * time.Second
c.PoolConfig.HostSelectionPolicy = gocql.DCAwareRoundRobinPolicy("dc1")
return c
}
// claimUsername is a lightweight transaction: INSERT ... IF NOT EXISTS runs a
// Paxos round, which the Cassandra docs call a "non-negligible performance cost".
// SerialConsistency chooses the Paxos scope: LocalSerial stays in one DC.
func claimUsername(s *gocql.Session, name, userID string) (bool, error) {
return s.Query(
`INSERT INTO usernames (name, user_id) VALUES (?, ?) IF NOT EXISTS`,
name, userID,
).SerialConsistency(gocql.LocalSerial).ScanCAS(new(string), new(string))
}
// putSession writes a row that expires by itself. USING TTL is per write;
// the expired cell becomes a tombstone until compaction removes it.
func putSession(s *gocql.Session, id, userID string, ttl time.Duration) error {
return s.Query(
`INSERT INTO sessions (id, user_id) VALUES (?, ?) USING TTL ?`,
id, userID, int(ttl.Seconds()),
).Consistency(gocql.LocalQuorum).Idempotent(true).Exec()
}
// latest reads at ONE: fastest, may be stale. Use for feeds and counters
// where a second of staleness is fine.
func latest(s *gocql.Session, userID string) *gocql.Iter {
return s.Query(
`SELECT order_id, total FROM orders_by_user WHERE user_id = ? LIMIT 20`,
userID,
).Consistency(gocql.One).Iter()
}
func main() {
c := newCluster("127.0.0.1")
fmt.Println(c.Consistency, c.Keyspace)
fmt.Println(gocql.LocalSerial, gocql.Quorum, gocql.All)
}Problem: a key-value cache in Laravel
Laravel 13 ships a dynamodb cache driver (the DynamoDB cache driver, a key-value use of the table). The docs: "Typically, DynamoDB will not proactively remove expired items from a table. Therefore, you should enable Time to Live (TTL) on the table", with the TTL attribute named expires_at and the default partition key named key. Install the SDK with composer require aws/aws-sdk-php.
<?php
// config/cache.php (excerpt): the dynamodb store as documented for Laravel 13.
// The table needs partition key "key" (string) and TTL enabled on "expires_at".
return [
'stores' => [
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
// Point at DynamoDB Local in development, e.g. http://localhost:8000
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
],
];
// Usage (anywhere in the app): a key-value access pattern, one item per key.
//
// use Illuminate\Support\Facades\Cache;
//
// Cache::store('dynamodb')->put('profile:42', $profile, now()->addMinutes(10));
// $profile = Cache::store('dynamodb')->get('profile:42');
// $profile = Cache::store('dynamodb')->remember('profile:42', 600, fn () => loadProfile(42));Laravel ships no DynamoDB Eloquent driver; the community package baopham/laravel-dynamodb ("Eloquent syntax for DynamoDB") maps models onto the API, and it follows the same rules: the model is only as good as your keys. Use the SDK directly, as above, when the access patterns are few and known.
The Laravel OrderStore (query by partition key, ConsistentRead as an argument, a GSI lookup, a singleton in the container):
<?php
namespace App\Orders;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Marshaler;
use Illuminate\Support\ServiceProvider;
// Access-pattern-first: PK = USER#<id>, SK = ORDER#<timestamp>#<orderId>.
// One Query reads one partition; no Scan anywhere.
class OrderStore
{
public function __construct(
private readonly DynamoDbClient $client,
private readonly Marshaler $marshaler,
private readonly string $table = 'orders',
) {}
/**
* Newest orders of one user.
*
* $strong chooses a strongly consistent read (twice the cost of an
* eventually consistent one): use it for "the order I just placed".
*
* @return list<array<string, mixed>>
*/
public function latestForUser(string $userId, int $limit = 20, bool $strong = false): array
{
$result = $this->client->query([
'TableName' => $this->table,
'KeyConditionExpression' => 'PK = :pk AND begins_with(SK, :prefix)',
'ExpressionAttributeValues' => $this->marshaler->marshalItem([
':pk' => 'USER#'.$userId,
':prefix' => 'ORDER#',
]),
'ScanIndexForward' => false, // newest first
'Limit' => $limit,
'ConsistentRead' => $strong,
]);
return array_map(
fn (array $item) => $this->marshaler->unmarshalItem($item),
$result['Items'],
);
}
/**
* Inverse lookup through a GSI. Reads from a GSI are always eventually
* consistent, so ConsistentRead is not sent.
*/
public function ownerOf(string $orderId): ?string
{
$result = $this->client->query([
'TableName' => $this->table,
'IndexName' => 'order_id-index',
'KeyConditionExpression' => 'order_id = :o',
'ExpressionAttributeValues' => $this->marshaler->marshalItem([':o' => $orderId]),
]);
$item = $result['Items'][0] ?? null;
return $item === null ? null : $this->marshaler->unmarshalItem($item)['PK'];
}
}
// Bound once in the container; controllers and jobs type-hint OrderStore.
class OrderStoreServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(DynamoDbClient::class, fn () => new DynamoDbClient([
'region' => config('services.dynamodb.region', 'us-east-1'),
'version' => 'latest',
]));
$this->app->singleton(OrderStore::class, fn ($app) => new OrderStore(
$app->make(DynamoDbClient::class),
new Marshaler(),
config('services.dynamodb.orders_table', 'orders'),
));
}
}and the before, which scans and filters:
<?php
namespace App\Orders;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Marshaler;
// Model-like access that treats DynamoDB as a table you can filter freely.
// Scan reads every item in the table; the filter only trims the response,
// so the whole table is read and billed on every call.
class Order
{
public static function forUser(string $userId): array
{
$client = new DynamoDbClient([
'region' => 'us-east-1',
'version' => 'latest',
]);
$marshaler = new Marshaler();
$items = [];
$startKey = null;
do {
$args = [
'TableName' => 'orders',
'FilterExpression' => 'user_id = :u',
'ExpressionAttributeValues' => $marshaler->marshalItem([':u' => $userId]),
];
if ($startKey !== null) {
$args['ExclusiveStartKey'] = $startKey;
}
$result = $client->scan($args);
foreach ($result['Items'] as $item) {
$items[] = $marshaler->unmarshalItem($item);
}
// Scan returns at most 1 MB per call, so you page through everything.
$startKey = $result['LastEvaluatedKey'] ?? null;
} while ($startKey !== null);
return $items;
}
}Problem: a queue in a table
| Approach | Verdict |
|---|---|
| Cassandra table with insert-process-delete | Anti-pattern: tombstones, slow reads |
| Time-bucketed partitions plus TTL plus TWCS | Works for expiring work items |
| DynamoDB table with status and TTL | Possible, but a GSI on status is a hot key; shard it |
| A real queue (RabbitMQ, Kafka, SQS) | The right tool |
PostgreSQL SELECT ... FOR UPDATE SKIP LOCKED | Excellent up to a large scale (isolation levels) |
Retries and failure handling
| Rule | Why |
|---|---|
| Let the SDK retry throttling with exponential backoff and jitter | Documented practice for ProvisionedThroughputExceededException |
Never retry ConditionalCheckFailedException | It is the answer, not a fault |
Make every write idempotent (key = request id, ClientRequestToken) | A timeout leaves the outcome unknown |
Mark Cassandra statements Idempotent(true) only when they are | gocql may retry or speculatively execute idempotent queries |
After CAS_WRITE_UNKNOWN read at SERIAL | The LWT may have applied |
| Cap retries and add a jittered backoff | Retry storms deepen throttling |
// retryable from the tx snippet: retry conflicts and throttling, never a failed condition.
func retryable(err error) bool {
var tc *types.TransactionCanceledException
if !errors.As(err, &tc) {
return false
}
for _, r := range tc.CancellationReasons {
switch aws.ToString(r.Code) {
case "TransactionConflict", "ThrottlingError", "ProvisionedThroughputExceeded":
return true
}
}
return false
}Choosing
| Workload | Recommended store | Extra technique | Reason |
|---|---|---|---|
| Session, cart, profile by id | DynamoDB on-demand or Redis | TTL | One key per request, spiky traffic |
| Multi-region SaaS, small team | DynamoDB global tables | Home-region writes | Managed multi-active replication |
| Write-heavy time series, self-hosted | Cassandra or ScyllaDB with TWCS | Bucketed partitions, TTL | Linear write scale, cheap deletes by window |
| Feeds and timelines | Cassandra or DynamoDB | One table per timeline, fan-out strategy | Known read patterns |
| Orders, payments, inventory with constraints | PostgreSQL | FOR UPDATE, constraints | Transactions and joins |
| Reporting, analytics | PostgreSQL or a columnar store | Replicas or OLAP | Ad-hoc queries |
| Unique usernames at scale | DynamoDB lookup item with a condition | Transaction with the user item | Cheap conditional write |
| Queue | A message broker | Tombstones and polling cost |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
How it shows up: one PostgreSQL; the cache is Redis or the Laravel database cache. The simplest correct usage of this family is a single DynamoDB table for something tiny and keyed (sessions, feature flags, idempotency keys) next to the relational database, not instead of it.
Example: a Laravel monolith keeps orders in PostgreSQL and stores web sessions and rate-limit counters in the dynamodb cache store with TTL, because both are "by key, expire, do not care about joins".
Modular monolith and multiple databases
How it shows up: a module owns a high-volume, key-shaped dataset (events, notifications, audit trail) and gets its own wide-column table, with the relational database kept for the transactional core.
Example: Notifications writes PK = USER#id, SK = TS#time to DynamoDB; Billing stays in PostgreSQL. A transaction cannot span them; link by id and publish an event from a PostgreSQL transaction (outbox) to fill the DynamoDB table.
Microservices
What survives: each service's single-partition or single-item guarantees. What does not: multi-service atomicity. A saga with compensations replaces it.
Order saga with DynamoDB state per service
1 Order service: TransactWriteItems [Put ORDER#o-1 PENDING, Put OUTBOX#evt-1]
2 stream (or outbox relay) -> OrderCreated message
3 Payment service: Put PAY#o-1 with attribute_not_exists (idempotent), then PaymentCaptured
4 Inventory service: Update stock, condition stock >= qty -> ConditionalCheckFailed
5 Inventory publishes StockUnavailable -> Payment refunds (compensation) -> Order set CANCELLED
6 every handler is idempotent: a redelivered message hits the condition and does nothingEach service's state lives in a store whose keys it controls; the cross-service flow is messaging (Saga and idempotent consumers).
Distributed data: replicas, caches and multi-region
- Replica lag is built in. An eventually consistent DynamoDB read, a Cassandra read at
ONE, and a GSI read can each return old data; read your own writes withConsistentReadorQUORUM/LOCAL_QUORUM. - A cache in front (DAX for DynamoDB, Redis for anything) adds a second staleness source; DAX passes strongly consistent and transactional reads through uncached.
- Multi-region adds last-writer-wins; assign a home region per record.
- Clocks matter because Cassandra and global tables use timestamps for conflict resolution; skewed clocks let an older write win. Keep NTP healthy or use client-side version numbers.
Scaling path: 1x, 10x, 100x
| Load | What changes | Consequence |
|---|---|---|
| 1x (one table, modest traffic) | On-demand DynamoDB, or a three-node Cassandra RF 3 with LOCAL_QUORUM | Cheap and simple; design keys now because changing them later means a rewrite |
| 10x (hot keys appear) | Write sharding, GSIs for second paths, caching, bounded partitions | Watch per-partition metrics, TransactionConflict and throttling; move queues out |
| 100x (multi-region, many teams) | Global tables or multi-DC, home-region ownership, streams for derived views, per-team tables | Conflict policy, replica cost, repair windows (Cassandra), quotas and cost review (DynamoDB) |
Lab
Four experiments. The first two use DynamoDB Local in Docker with the lab Go program; the last two use Cassandra 5.0 in Docker. DynamoDB Local does not simulate partitions or throttling: it returns consumed capacity and answers queries like the service, so the lab shows the key design, not the throttle. Expected output is in comments and was captured on the commands below.
Setup.
docker run --rm -d -p 8000:8000 --name ddb amazon/dynamodb-local
cd docs/snippets/database/wide-column-key-value/go
# If port 8000 is busy, map another port and set DDB_ENDPOINT=http://localhost:81001. Hot key against well-distributed key (DynamoDB Local). The program creates two tables, writes 2,000 orders under PK = STATUS#pending (hot) and under PK = USER#<i mod 500> (spread), then counts items per key.
// Package main is the DynamoDB Local lab: write the same 2,000 orders under a
// hot key and under a well-distributed key, then compare how many distinct
// partition-key values (the unit DynamoDB hashes) each design produced.
//
// Start DynamoDB Local first:
//
// docker run --rm -d -p 8000:8000 --name ddb amazon/dynamodb-local
//
// DynamoDB Local does not simulate partitions or throttling. It does return
// consumed capacity, and it answers Query on a key exactly like the service,
// so the lab shows the key design, not the throttling.
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
func attr(name string, t types.ScalarAttributeType) types.AttributeDefinition {
return types.AttributeDefinition{AttributeName: aws.String(name), AttributeType: t}
}
func createTable(ctx context.Context, c *dynamodb.Client, name string) {
_, err := c.CreateTable(ctx, &dynamodb.CreateTableInput{
TableName: aws.String(name),
AttributeDefinitions: []types.AttributeDefinition{attr("PK", "S"), attr("SK", "S")},
KeySchema: []types.KeySchemaElement{
{AttributeName: aws.String("PK"), KeyType: types.KeyTypeHash},
{AttributeName: aws.String("SK"), KeyType: types.KeyTypeRange},
},
BillingMode: types.BillingModePayPerRequest,
})
if err != nil {
log.Fatalf("create %s: %v", name, err)
}
}
func put(ctx context.Context, c *dynamodb.Client, table, pk, sk string) float64 {
out, err := c.PutItem(ctx, &dynamodb.PutItemInput{
TableName: aws.String(table),
Item: map[string]types.AttributeValue{
"PK": &types.AttributeValueMemberS{Value: pk},
"SK": &types.AttributeValueMemberS{Value: sk},
},
ReturnConsumedCapacity: types.ReturnConsumedCapacityTotal,
})
if err != nil {
log.Fatalf("put: %v", err)
}
return aws.ToFloat64(out.ConsumedCapacity.CapacityUnits)
}
func main() {
ctx := context.Background()
endpoint := os.Getenv("DDB_ENDPOINT")
if endpoint == "" {
endpoint = "http://localhost:8000"
}
client := dynamodb.New(dynamodb.Options{
Region: "us-east-1",
BaseEndpoint: aws.String(endpoint),
// DynamoDB Local accepts any credentials.
Credentials: aws.CredentialsProviderFunc(func(context.Context) (aws.Credentials, error) {
return aws.Credentials{AccessKeyID: "local", SecretAccessKey: "local"}, nil
}),
})
createTable(ctx, client, "hot")
createTable(ctx, client, "spread")
const orders = 2000
var hotWCU, spreadWCU float64
for i := 0; i < orders; i++ {
id := fmt.Sprintf("o-%05d", i)
// Hot design: PK is the order status; almost all orders are "pending".
hotWCU += put(ctx, client, "hot", "STATUS#pending", id)
// Good design: PK is the user; 500 users, 4 orders each.
spreadWCU += put(ctx, client, "spread", fmt.Sprintf("USER#%03d", i%500), id)
}
for _, t := range []string{"hot", "spread"} {
var items, pages int32
var lastKey map[string]types.AttributeValue
// Select COUNT with a Scan reads the whole table; fine for a lab.
for {
out, err := client.Scan(ctx, &dynamodb.ScanInput{
TableName: aws.String(t), Select: types.SelectCount, ExclusiveStartKey: lastKey,
})
if err != nil {
log.Fatalf("scan: %v", err)
}
items += out.Count
pages++
if lastKey = out.LastEvaluatedKey; lastKey == nil {
break
}
}
fmt.Printf("%-6s items=%d scan_pages=%d\n", t, items, pages)
}
// One Query on the hot key must page through every item of the collection.
hot, err := client.Query(ctx, &dynamodb.QueryInput{
TableName: aws.String("hot"),
KeyConditionExpression: aws.String("PK = :p"),
ExpressionAttributeValues: map[string]types.AttributeValue{":p": &types.AttributeValueMemberS{Value: "STATUS#pending"}},
Select: types.SelectCount,
ReturnConsumedCapacity: types.ReturnConsumedCapacityTotal,
})
if err != nil {
log.Fatalf("query hot: %v", err)
}
good, err := client.Query(ctx, &dynamodb.QueryInput{
TableName: aws.String("spread"),
KeyConditionExpression: aws.String("PK = :p"),
ExpressionAttributeValues: map[string]types.AttributeValue{":p": &types.AttributeValueMemberS{Value: "USER#007"}},
Select: types.SelectCount,
ReturnConsumedCapacity: types.ReturnConsumedCapacityTotal,
})
if err != nil {
log.Fatalf("query spread: %v", err)
}
fmt.Printf("hot one partition key STATUS#pending holds %d items\n", hot.Count)
fmt.Printf("spread one partition key USER#007 holds %d items\n", good.Count)
fmt.Printf("write units billed: hot=%.0f spread=%.0f (identical: capacity is billed per item, throttled per partition)\n", hotWCU, spreadWCU)
}go run ./lab
# hot items=2000 scan_pages=1
# spread items=2000 scan_pages=1
# hot one partition key STATUS#pending holds 2000 items
# spread one partition key USER#007 holds 4 items
# write units billed: hot=2000 spread=2000 (identical: capacity is billed per item, throttled per partition)Read the output: the bill is the same, but one design has a single partition key holding the whole table (real DynamoDB would cap it at 1,000 write units per second) and the other has 500.
2. Shard the hot key. Run the shard snippet: 10,000 events under one logical key spread over 16 suffixes.
go run ./shard
# DATE#2026-11-25#00 615
# DATE#2026-11-25#01 625
# DATE#2026-11-25#02 608
# 16 queries per readStop the container: docker rm -f ddb.
3. Cassandra tombstone demo. Start Cassandra and build a queue-shaped partition: 5,000 inserts, 4,999 deletes.
docker run --rm -d --name cass cassandra:5.0
# wait until: docker exec cass cqlsh -e "select release_version from system.local"CREATE KEYSPACE IF NOT EXISTS lab WITH replication = {'class':'SimpleStrategy','replication_factor':1};
CREATE TABLE IF NOT EXISTS lab.queue (q text, id int, body text, PRIMARY KEY (q, id)) WITH gc_grace_seconds = 864000;# generate tomb.cql: schema, 5,000 inserts, then 4,999 deletes
{
echo "CREATE KEYSPACE IF NOT EXISTS lab WITH replication = {'class':'SimpleStrategy','replication_factor':1};"
echo "CREATE TABLE IF NOT EXISTS lab.queue (q text, id int, body text, PRIMARY KEY (q, id)) WITH gc_grace_seconds = 864000;"
for i in $(seq 1 5000); do echo "INSERT INTO lab.queue (q,id,body) VALUES ('jobs',$i,'x');"; done
for i in $(seq 1 4999); do echo "DELETE FROM lab.queue WHERE q='jobs' AND id=$i;"; done
} > tomb.cql
docker cp tomb.cql cass:/tomb.cql && docker exec cass cqlsh -f /tomb.cql
docker exec cass nodetool flush lab
docker exec cass cqlsh -e "TRACING ON; SELECT id FROM lab.queue WHERE q='jobs' LIMIT 1;"
# id
# 5000
# (1 rows)
# Read 1 live rows and 4999 tombstone cells (see tombstone_warn_threshold)
docker logs cass 2>&1 | grep tombstone | tail -1
# WARN ... ReadCommand.java:644 - Read 1 live rows and 4999 tombstone cells for query SELECT * FROM lab.queue WHERE q = 'jobs' LIMIT 1 ALLOW FILTERING; ... (see tombstone_warn_threshold)One row was returned, but the read walked past 4,999 markers; past 1,000 it logs a warning, past 100,000 it fails.
4. Why compaction alone does not fix it, and what does.
docker exec cass nodetool compact lab queue
docker exec cass cqlsh -e "TRACING ON; SELECT id FROM lab.queue WHERE q='jobs' LIMIT 1;"
# Read 1 live rows and 4999 tombstone cells <- still there: inside gc_grace_seconds
docker exec cass cqlsh -e "ALTER TABLE lab.queue WITH gc_grace_seconds = 0;"
docker exec cass nodetool compact lab queue
docker exec cass cqlsh -e "TRACING ON; SELECT id FROM lab.queue WHERE q='jobs' LIMIT 1;"
# Read 1 live rows and 0 tombstone cells <- purged (safe here only because RF = 1, one node)
docker rm -f cassOn a real multi-node cluster, setting gc_grace_seconds to 0 would risk resurrecting deleted data; the right fix is to stop deleting in a hot partition (bucket by time, use TTL with TWCS, or use a queue).
Common misconceptions
| Belief | Reality |
|---|---|
| NoSQL has no schema | The schema is your keys and your code; changing a key means rewriting data |
| Hashing spreads load evenly | It spreads keys, not traffic; a hot key is one partition |
| A Scan with a filter is a query | The filter runs after the read; you pay for the table |
| DynamoDB is the Dynamo paper | A separate managed service sharing the name and partitioning idea |
QUORUM makes Cassandra ACID | It gives read-your-writes per partition, not transactions |
| Raising provisioned capacity fixes a hot key | The per-partition ceiling (3,000 reads / 1,000 writes per second) stays |
| Cassandra deletes free space immediately | Tombstones live for gc_grace_seconds, and reads scan them |
| Cassandra repairs itself | Hints are best effort; repair is run by the operator |
| Single-table design is mandatory | It is one documented choice, with readability costs |
| DynamoDB transactions are interactive SQL transactions | Fixed batches of up to 100 actions, 2x cost, all-or-nothing |
| A GSI read is as fresh as a table read | GSIs are eventually consistent; ConsistentRead is not supported on them |
| Multi-region means strongly consistent | Default is asynchronous with last-writer-wins |
| PostgreSQL cannot scale | It scales further than most teams need; add a wide-column store only for the workload that outgrows it |
| TTL deletes on time | DynamoDB deletes within days, Cassandra leaves tombstones |
Cheat sheet
| Topic | What to remember |
|---|---|
| Partition key | Hashed; decides the node; name it in every query |
| Sort / clustering key | Orders items inside a partition; range reads are contiguous |
| Query-first | Write the queries, then the tables; duplicate on purpose |
| Hot partition | Ceiling 3,000 reads / 1,000 writes per partition per second in DynamoDB; shard with a suffix |
| Read unit / write unit | 4 KB strong (or 2 eventual) / 1 KB; transactions double it |
| On-demand vs provisioned | Pay per request vs reserve a rate; on-demand doubles the previous peak instantly |
| Single-table | One partition key per screen, items told apart by SK prefixes |
| GSI vs LSI | GSI: own key, eventual, throttles the table if under-provisioned; LSI: same PK, strong, 10 GB per PK |
| Transactions | DynamoDB: 100 actions, ClientRequestToken; Cassandra: LWT = Paxos, per partition, sparingly |
| Consistency | R + W > N; LOCAL_QUORUM is the multi-DC workhorse; ConsistentRead costs 2x |
| Tombstones | Delete = marker for gc_grace_seconds (10 days); never use a table as a queue |
| Repair | Operator-run Merkle comparison inside the grace period |
| TTL | DynamoDB deletes within days, free of write units; Cassandra TTL = tombstone, use TWCS |
| Streams | DynamoDB: 24 hours, exactly once, per-item order; Cassandra CDC: you parse commit-log segments |
| Multi-region | Global tables: MREC default, MRSC opt-in, last-writer-wins; Cassandra: LOCAL_QUORUM per DC |
| Use PostgreSQL when | Queries are ad hoc, data fits, you need joins and constraints |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does a low-cardinality partition key (like status) cause throttling even when the table is mostly idle? Must-know
Answer
Answer: All its items hash to one partition, which has a per-partition ceiling (1,000 writes, 3,000 reads per second in DynamoDB). Table-level capacity does not lift it. Fix the key or shard it with a suffix.
2 — With replication factor 3, which read and write levels guarantee that a read sees the latest acknowledged write? Important
Answer
Answer: Any pair with R + W > 3, such as QUORUM and QUORUM (2 + 2). ONE and ONE (1 + 1) does not overlap.
3 — What is the difference between a sloppy quorum and a strict quorum? Good to know
Answer
Answer: A sloppy quorum uses the first N healthy nodes of the preference list, even ones that are not the normal replicas, and stores a hint for the intended node. A strict quorum uses only the real replicas. Sloppy is more available but can miss the nodes that took the latest write.
4 — How do Dynamo and Cassandra resolve conflicting writes? Important
Answer
Answer: Dynamo keeps divergent versions with vector clocks and lets the client merge. Cassandra keeps the cell with the newest timestamp (last-write-wins), per cell. DynamoDB global tables use last-writer-wins.
5 — Why does a DynamoDB GSI query sometimes miss an item you just wrote? Must-know
Answer
Answer: GSIs are updated asynchronously and are always eventually consistent; ConsistentRead is not available on them. Read the base table by key when you need the latest.
6 — What does a TransactWriteItems call cost, and what are its limits? Important
Answer
Answer: Twice the capacity units of normal writes (prepare and commit), up to 100 actions and 4 MB, no two actions on the same item, idempotent for 10 minutes with a ClientRequestToken. Failure returns TransactionCanceledException with ordered cancellation reasons.
7 — Why is INSERT ... IF NOT EXISTS expensive in Cassandra? Important
Answer
Answer: It runs a Paxos round between the replicas (several round trips) to get linearizable semantics for one partition, so use it sparingly.
8 — A Cassandra table used as a queue becomes slow to read. Why, and what do you do? Must-know
Answer
Answer: Deletes are tombstones kept for gc_grace_seconds; reads scan past them (the lab shows 4,999 tombstones for 1 live row). Use a real queue, or time-bucket partitions with TTL and TWCS.
9 — Why must Cassandra repair run at least once per gc_grace_seconds? Important
Answer
Answer: If a replica missed a delete and the tombstone is purged elsewhere first, the old row can reappear. Repair delivers the tombstone before it expires.
10 — What is single-table design, and what does it cost? Must-know
Answer
Answer: Several entity types share one table and partition key (an item collection), so one Query returns everything a screen needs. It costs readability, harder analytics and migrations, and a single blast radius.
11 — DynamoDB global tables: what happens when two Regions write the same item concurrently? Important
Answer
Answer: Replication is asynchronous and last-writer-wins, so one write is lost. Use a home region per record, or MRSC if you need strong consistency across Regions.
12 — When is PostgreSQL enough? Must-know
Answer
Answer: When queries are ad hoc, the data and writes fit one primary (with replicas and partitioning), and you need joins and constraints. A wide-column store is for known key-based access beyond one primary's reach, or active-active multi-region.
Glossary
| Term | Meaning |
|---|---|
| Partition key | The key part that is hashed to choose where an item lives |
| Sort key / clustering key | The key part that orders items inside a partition |
| Item collection | All DynamoDB items sharing one partition key |
| Partition | The unit of placement and throughput; a replica set holds it |
| Token | The hash value of a partition key (Cassandra Murmur3) placing it on the ring |
| Virtual node (vnode) | One of many token ranges a physical node owns |
| Preference list | The ordered nodes responsible for a key (Dynamo) |
| Replication factor (RF, N) | Number of copies of each partition |
| Consistency level | How many replicas must respond to a request |
| Quorum | A majority of replicas (n/2 + 1) |
LOCAL_QUORUM | A majority in the coordinator's datacenter |
EACH_QUORUM | A majority in every datacenter |
| Sloppy quorum | Using the first N healthy nodes instead of strict replicas |
| Hinted handoff | Storing a write for a down replica and delivering it later |
| Vector clock | A list of (node, counter) pairs capturing causality between versions |
| Last-write-wins (LWW) | Conflict rule: the newest timestamp wins |
| Merkle tree | A hash tree used to find differing ranges between replicas |
| Anti-entropy repair | Background comparison and streaming that makes replicas agree |
| Gossip | Peer-to-peer exchange of membership and failure state |
| Tablet | Bigtable's contiguous row range served by one tablet server |
| SSTable | Immutable sorted file written from a memtable |
| Memtable | In-memory sorted write buffer flushed to an SSTable |
| Chubby | Google's distributed lock service used by Bigtable |
| Compaction | Background merging of SSTables |
| Tombstone | A deletion marker kept for gc_grace_seconds |
gc_grace_seconds | Cassandra's tombstone grace period (default 864000) |
| Read unit / write unit | DynamoDB billing and throttling units (4 KB read, 1 KB write) |
| On-demand / provisioned | Pay per request, or reserve a per-second rate |
| Adaptive capacity | DynamoDB automatically giving hot partitions more throughput |
| GSI | Global secondary index: own key, spans partitions, eventually consistent |
| LSI | Local secondary index: same partition key, different sort key, 10 GB per key |
| SAI | Storage-attached index in Cassandra 5.0 |
| Single-table design | Several entity types in one table, told apart by key prefixes |
TransactWriteItems | DynamoDB's all-or-nothing write of up to 100 actions |
| LWT | Cassandra lightweight transaction (IF conditions) on Paxos |
| Paxos | Consensus protocol Cassandra uses for LWT |
ClientRequestToken | Idempotency token for a DynamoDB transaction |
| TTL | Per-item expiry |
| TWCS | Time Window Compaction Strategy |
| DynamoDB Streams | Ordered, 24-hour change log of a table |
| CDC | Change data capture; in Cassandra, commit-log segments exposed per table |
| Global table | DynamoDB multi-Region, multi-active table (MREC or MRSC) |
| MREC / MRSC | Multi-Region eventual / strong consistency modes |
NetworkTopologyStrategy | Cassandra's per-datacenter replication placement |
| Hot partition | A partition receiving far more traffic than average |
| Denormalization | Storing the same fact in several tables or items so each query reads one place |
| Consistent hashing | Placing keys and nodes on a ring so that adding a node moves only a neighbouring slice |
| Query-first modeling | Designing one table or key schema per query pattern, copying data between them |
| Celebrity problem | One very popular key concentrating traffic on a single partition |
| Write sharding | Appending a suffix to a hot key on write and querying all suffixes on read |
| Read repair | Writing the newest version back to a stale replica that a read noticed |
| Eventually consistent read | A read that may miss the latest write (DynamoDB default, Cassandra at ONE) |
| Strongly consistent read | A read that reflects all prior successful writes (ConsistentRead, Cassandra QUORUM after a QUORUM write) |
| Cost model | How a store charges: per request unit (DynamoDB) or per machine (Cassandra) |
References
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007. PDF
- Chang et al., "Bigtable: A Distributed Storage System for Structured Data", OSDI 2006. PDF
- Apache Cassandra: Data Modeling introduction, Dynamo architecture, Guarantees, Compaction and tombstones, Hints, Repair, CDC, DML (LWT, TTL), Indexing concepts, Native protocol v5
- Amazon DynamoDB Developer Guide: Core components, Partitions and data distribution, Partition key design, Read consistency, Burst and adaptive capacity, On-demand capacity mode, Throughput capacity, Data modeling foundations, Secondary indexes, Transactions, Streams, Global tables, TTL, Quotas, Error handling, Query API, DynamoDB Local
- AWS SDK for Go v2:
service/dynamodb; gocql:github.com/gocql/gocql; AWS SDK for PHP:Marshaler - Laravel 13 documentation: Cache; community package: baopham/laravel-dynamodb