Skip to content

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 forGo to
A table you can memorise in one minuteEverything in one minute
Why these stores exist and what they costWhy they exist
The Dynamo and Bigtable papers, and how Cassandra and DynamoDB descend from themWhere it comes from
Partition key, sort key, clustering key, item collectionPartition key and sort key
How a key becomes a node: ring, tokens, vnodes, replicasPlacement on the ring
ONE, QUORUM, LOCAL_QUORUM, ALL, eventually vs strongly consistent readsTunable consistency
Sloppy quorum, hinted handoff, vector clocks, Merkle trees, gossipDynamo's failure toolkit
One table per query, denormalization, duplicationQuery-first modeling
Hot partitions, celebrity keys, write shardingHot partitions
Read and write units, on-demand vs provisioned, adaptive capacityDynamoDB capacity
Single-table design, item collectionsSingle-table design
GSI, LSI, Cassandra 2i and SAISecondary indexes
TransactWriteItems, ConditionExpression, Cassandra LWTTransactions and conditions
TTL, tombstones, deletes, compaction, repairDeletes and TTL, Compaction, Repair
DynamoDB Streams, Cassandra CDCStreams and CDC
Global tables, multi-datacenter CassandraMulti-region
What it costs, and when PostgreSQL is enoughCost models, When PostgreSQL is enough
Product-by-product comparison and error codesPer-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 laptopLab
Wrong beliefs, cheat sheet, self-check, glossaryMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The ten ideas. Every row is unpacked later.

IdeaIn plain wordsTiny exampleWhere it bites
Partition keyThe part of the primary key that is hashed to choose where the data livesPK = USER#42Low cardinality means one busy partition
Sort / clustering keyThe part that orders items inside one partitionSK = ORDER#2026-11-25A range of it is one contiguous read
Query-first modelingList the queries, then build one table per queryorders_by_user, orders_by_dayA new query is a new table and a backfill
Denormalization (denormalization)Copy the same fact into every table that needs itCustomer name stored in each order itemUpdates must touch every copy
Tunable consistencyChoose per request how many replicas must answerLOCAL_QUORUM, ConsistentReadONE can return stale data
Hot partitionOne key gets far more traffic than its shareA celebrity feed, today's dateThrottling while the table idles
Single-table designSeveral entity types under one partition key in one tableUSER#42 holds profile, orders, addressesOnly the author can read the schema
TombstoneA delete is a marker, not an eraseCassandra DELETE writes a markerReads scan past markers
Transaction / LWTConditional or multi-item atomic writes, at a costTransactWriteItems, IF NOT EXISTS2x capacity in DynamoDB, Paxos rounds in Cassandra
Multi-regionReplicas in several regions or datacentersGlobal tables, NetworkTopologyStrategyConcurrent writes resolve last-writer-wins

DynamoDB against Cassandra, side by side.

AxisDynamoDBApache Cassandra / ScyllaDB
Who runs itAWS, fully managed, serverlessYou (or a managed offering)
Key vocabularyPartition key, sort keyPartition key, clustering key
PlacementInternal hash, hidden partitionsMurmur3 tokens on a visible ring, vnodes
ConsistencyEventually consistent default, ConsistentRead per requestONE ... ALL, LOCAL_QUORUM, EACH_QUORUM per query
Conditional writesConditionExpression, TransactWriteItemsIF NOT EXISTS / IF (Paxos), batches
Secondary access pathsGSI (eventually consistent), LSI (strong, 10 GB per key)Local 2i, SAI, materialised views, query tables
Capacity modelRead/write units, on-demand or provisionedNodes, you size the cluster
Change feedDynamoDB Streams (24 hours)CDC commit-log segments
Multi-regionGlobal tables (MREC or MRSC)Multi-datacenter replication, per-query CL

The three things to do.

SituationDo this
Designing a new tableWrite the access patterns first, choose a high-cardinality partition key, and put the sort order you read in the sort key
One key is hotShard 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 constraintsUse 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 upYou get
Joins, ad-hoc WHERE, cross-partition constraintsReads 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 defaultAvailability when nodes or regions fail
A schema the database enforcesA schema your key design and your code enforce
The freedom to ask a new question laterPredictable 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:

ProblemTechnique in the paperAdvantage
PartitioningConsistent hashingIncremental scalability
High availability for writesVector clocks with reconciliation during readsVersion size is decoupled from update rates
Handling temporary failuresSloppy quorum and hinted handoffHigh availability and durability when some replicas are unavailable
Recovering from permanent failuresAnti-entropy using Merkle treesSynchronises divergent replicas in the background
Membership and failure detectionGossip-based membership protocolAvoids 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).

text
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 it

Real 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:

ComponentWhat it doesWhere you meet it today
TabletA contiguous row range; "each table consists of just one tablet" at first and splits automatically, each approximately 100-200 MB by defaultHBase regions; Cassandra partition ranges; DynamoDB partitions
Tablet serverServes a set of tablets and handles reads and writesHBase RegionServer
MasterAssigns tablets to servers, detects live servers, handles schema changesHBase Master
ChubbyA distributed lock service that holds the root of the tablet location tree, tracks tablet servers, and stores schema and ACLsZooKeeper in HBase; Cassandra uses gossip instead
SSTable"a persistent, ordered immutable map from keys to values" fileCassandra SSTables, RocksDB, HBase HFiles
Memtable + commit logWrites go to a log and an in-memory sorted buffer, flushed to a new SSTableCassandra commit log and memtable
CompactionMerges SSTables; a major compaction rewrites all into oneStorage Engines
Three-level locationChubby file, then the root METADATA tablet, then other METADATA tablets, then user tabletsHBase 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.

text
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-3

Real 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 ​

ConcernDynamo paperBigtable paperCassandraDynamoDB
MasterNoneOne master + ChubbyNoneHidden, managed
PlacementConsistent hashing, preference listSorted row ranges (tablets)Murmur3 token ring, vnodesInternal hash on the partition key
Data modelOpaque value per keyRow, column family, column, timestampPartition key, clustering columns, columnsItems with attributes, partition key, sort key
ConflictsVector clocks, client mergesSingle writer per tabletLast-write-wins by timestamp per cellLast-writer-wins in global tables
StoragePluggable (BDB, MySQL)SSTables, memtable, GFSSSTables, memtable, commit logManaged, hidden
MembershipGossipMaster + ChubbyGossipManaged

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).

text
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 table

Real scenarios: chat messages by (room, time); orders by (user, time); telemetry by (device, day); a catalogue by (category, product).

What provides it:

ConceptDynamoDBCassandra / ScyllaDBBigtable / HBase
Distribution keyPartition key (hash)Partition key (Murmur3 token)Row key (range, sorted)
In-partition orderSort keyClustering columns, CLUSTERING ORDER BYRow key order, column qualifiers
Range scan by keyOnly inside one partitionOnly inside one partition (ALLOW FILTERING otherwise)Across rows, because rows are globally sorted
Composite keysPK and SK strings, prefixes by conventionComposite 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.

sql
-- 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.

N1N2N3N4tokenhash ringtoken space wrapskey lands before N1: walk clockwise, take N1, N2, N3 (RF = 3)row: PK = USER#42SK = ORDER#2026-11-25T10:00Zhash(PK) = token (Murmur3 / internal hash)owner = first node clockwise of tokenreplicas on RF distinct nodesany can answer; CL/quorum decides how manyinside the partition: sorted by SKa range of SK = one contiguous readAdding a node moves only the neighbouring arc
text
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 stay

Real 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:

ProductPlacementReplication unitVisible to you?
CassandraMurmur3 partitioner, num_tokens vnodes per node (16 in the 5.0 default config the lab uses)Keyspace replication factor, NetworkTopologyStrategynodetool ring, nodetool describering
ScyllaDBSame ring idea, plus shard-per-core ownership of tokens inside a nodeSamenodetool ring
DynamoDBInternal hash of the partition key to partitionsAutomatically replicated across multiple Availability Zones in a Region (managed)No: partitions are hidden
Bigtable / HBaseSorted row ranges, no hashTablets served by one server, data replicated by the filesystemTablet or region boundaries
Redis Cluster16384 hash slotsReplica per masterCLUSTER 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:

LevelReplicas that must respondUse it for
ANYOne replica, or the coordinator stores a hint (writes only)Fire-and-forget logs where loss is acceptable
ONE / LOCAL_ONEOne replica (LOCAL_ONE: one in the local datacenter)Fast reads that may be stale; high-volume writes
QUORUMA majority of all replicas (n/2 + 1)Read-your-writes in a single datacenter cluster
LOCAL_QUORUMA majority in the coordinator's datacenterThe usual multi-datacenter default: strong inside one DC, no cross-DC latency
EACH_QUORUMA majority in every datacenterWrites that must be durable in every DC (slow, fails if one DC is unreachable)
ALLEvery replicaRare: 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).

text
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 -> v2

Real 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:

ProductDefaultStrongestPer request?
Cassandra / ScyllaDBSet by the driver or by cqlsh, not by the server (gocql: Quorum)ALL, or SERIAL / LOCAL_SERIAL for conditional writesYes, per statement
DynamoDBEventually consistent readConsistentRead: true on table and LSI; transactional APIsYes, per read call
RedisSingle primary; replicas are asyncWAIT for replica acks (not a guarantee)Per command
MongoDBRead concern local, write concern w:1/majority by versionmajority read and write concernYes
PostgreSQLOne primary, synchronous replicas optionalSynchronous commit to standbysPer transaction
CockroachDBSerializableSerializable (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.

go
// 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:

MechanismWhat it doesDynamo paperCassandraDynamoDB
Sloppy quorumReads 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””YesNo: quorum is strict over the real replicas; ANY is the only level that accepts a hint as an ackHidden
Hinted handoffA node that took a write for a down replica stores it with a hint and delivers it when that replica returnsYesYes: coordinators store hints on their local filesystem and replay them; max_hint_window is 3 hours by default in the 5.0 configHidden
Vector clocks"A vector clock is effectively a list of (node, counter) pairs", one per version, to tell a causal successor from a parallel branchYes; capped in size by truncationNo: last-write-wins by cell timestampNo: last-writer-wins
Read repairReads that find stale replicas write the newest version backYes (on read)Yes (at QUORUM and above, or by chance)Hidden
Merkle-tree anti-entropyReplicas hash ranges of their data into a tree; "each branch of the tree can be checked" without reading everything, and only differing ranges are exchangedYesnodetool repair compares Merkle treesHidden
GossipNodes exchange membership and failure state with random peers, no central registryYesYes (nodetool gossipinfo)Hidden
clientcoordinatornode Anode Bnode Cnode Dpreference list: A, B, Cnext healthy node1 put(k, v, context) -> coordinator (first node of the preference list, or any node that forwards)2 coordinator sends the write to the first N = 3 HEALTHY nodes of the list; A is unreachable3 B and C store it; D stores it with a hint: "intended for A" (sloppy quorum: W = 2 acks are enough)4 coordinator answers the client after W acks; availability is preserved5 A comes back; D notices (gossip), delivers the hinted replica to A, then deletes its local copy6 hints are best effort: a Merkle-tree comparison (anti-entropy repair) closes the gaps hints misshinted handoff (later)Trade-off: R + W > N gives overlapping quorums only for a strict quorum. With a sloppy quorum the nodes thatanswered a read may not include the nodes that took the write, so stale reads and divergent versions are possible.
text
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.

text
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 name

Real 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:

ProductHow duplication is writtenKeeping copies in step
CassandraBATCH (logged batch is atomic per call, not isolated), or app writes each tableIdempotent writes; repair; accept short divergence
DynamoDBTransactWriteItems (up to 100 actions), or a stream consumer builds the second viewDynamoDB Streams to Lambda or a worker; GSIs do the copy for you, asynchronously
PostgreSQLOne normalised table plus indexes or materialised viewsThe database does it, transactionally
MongoDBEmbedding plus occasional referencesApplication 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.

sql
-- 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.

Bad key: PK = status ("pending")1,000 WCUP11800P220P310P45P55P65one partition throttled, the rest idleGood key: PK = user id, or sharded suffix1,000 WCUP1320P2290P3310P4300P5330P6280same total, spread: none near the ceilingAdaptive capacity moves spare capacity toward a hot partition, but cannot exceed the per-partition ceiling.Celebrity fix: write to KEY#00..KEY#15 (random or hashed suffix), read all 16 and merge.
text
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:

TechniqueHowCost
High-cardinality keyUSER#<id>, DEVICE#<id> instead of STATUS#pendingNone, if you do not need to list by status
Composite keyAdd a bucket: (day, hour) or (device, day)A query spans several keys
Write shardingRandom or hash suffix KEY#00..15; read all and mergeN reads per query; counts need aggregation
Adaptive capacityDynamoDB "works by automatically increasing throughput capacity for partitions that receive more traffic", isolating hot itemsBounded by table throughput and the per-partition ceiling; helps skew, does not remove it
CachingDAX or an application cache in front of hot readsStaleness, invalidation
Time bucketingCassandra partitions per (sensor, day) so partitions stay boundedMore partitions to read for a range
Pull instead of pushDo not fan out the celebrity; merge at read timeRead-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.

go
// 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).

ModeHow you payScalingFits
On-demandPer read or write request unit; nothing when idleNew 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 allocatedSpiky, unknown or new workloads; the documented default
ProvisionedFor the capacity you reserve per hour, used or notYou set read and write units (optionally with auto scaling); exceeding them returns ProvisionedThroughputExceededExceptionSteady, 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".

text
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: 4

Real 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:

ProductCapacity modelThrottling signal
DynamoDBRead/write units, on-demand or provisionedProvisionedThroughputExceededException, ThrottlingException; SDKs retry with backoff
Cassandra / ScyllaDBNodes: you add machinesTimeouts, Unavailable, dropped mutations, pending compactions
BigtableNodesLatency rising with CPU
PostgreSQLOne server's CPU, IOPS, connectionsQueueing, 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.

PKSKattributespartitionUSER#42PROFILEname, email, planUSER#42ORDER#2026-11-25#o-9total 120, status paidUSER#42ORDER#2026-11-24#o-7total 40, status shippedUSER#42ADDRESS#homestreet, cityUSER#77PROFILEname, email, planUSER#77ORDER#2026-11-20#o-3total 15, status paiditem collection USER#42item collection USER#77One Query: PK = "USER#42" (optionally AND begins_with(SK, "ORDER#"))reads the profile, orders (sorted by SK) and addresses of one user in a single round tripcost: heterogeneous items in one table; the schema lives in key prefixes, so document themlimit with an LSI on the table: 10 GB per partition-key value
text
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 = 10

Real 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:

ChoiceStrengthWeakness
Single tableOne request per screen, smoother traffic, one capacity pool and one set of alarmsOpaque schema, hard analytics, harder migrations, one blast radius
One table per entityObvious schema, per-table capacity and TTL, simpler streamsMore round trips; joins in application code
CassandraTables 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:

IndexKeyConsistencyLimits and cost
DynamoDB GSIOwn partition key and sort key; spans all partitions; separate storageAlways 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 LSISame partition key as the table, different sort keyStrong or eventual reads5 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 replicaOnly 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 typesLocal to the node"the most appropriate indexing method for most use cases"; still not a substitute for the right partition key
Cassandra materialised viewA server-maintained second table with another keyMaintained by Cassandra, eventually consistentDisabled by default in the 5.0 config (materialized_views_enabled=false in the lab output); many teams write the second table themselves
text
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 key

Real 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 TransactWriteItemsCassandra 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 totalOne partition: INSERT ... IF NOT EXISTS, UPDATE ... IF col = ?, DELETE ... IF
ActionsPut, Update, Delete, ConditionCheck; the same item cannot appear twiceA single conditional statement (or a conditional batch within one partition)
IsolationSerializable between transactional operations; read-committed for a BatchGetItem as a unitLinearizable per partition ("Lightweight transactions with linearizable consistency" is a listed guarantee)
MechanismTwo underlying reads or writes per item (prepare and commit)Paxos rounds between replicas; SERIAL or LOCAL_SERIAL consistency
CostTwice the capacity units of a normal operation"non-negligible performance cost, because Paxos is used"; use sparingly
IdempotencyClientRequestToken, valid for 10 minutes; same token with different parameters returns IdempotentParameterMismatchThe statement is naturally conditional; retries return [applied] = false
FailureTransactionCanceledException with ordered CancellationReasons (SDKs do not retry it); TransactionConflictException for a plain write that collides with a transactionTimeout during Paxos leaves the outcome unknown until read at SERIAL
text
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 row

Real 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:

NeedDynamoDBCassandraPostgreSQL
Single-item compare-and-setConditionExpression on PutItem / UpdateItem (cheap)UPDATE ... IF (Paxos, expensive)UPDATE ... WHERE version = ? or SELECT ... FOR UPDATE
Multi-item atomic writeTransactWriteItemsNot across partitions in 5.0 (logged batch is atomic but not isolated)Ordinary transaction
Unique constraintItem whose key is the unique value, attribute_not_existsIF NOT EXISTS on a lookup tableUNIQUE constraint
Aggregate across rowsNot available; maintain counters or use streamsCounters (not idempotent), or SELECT then computeSUM() 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 TTLCassandra TTL
Set byA Number attribute holding a Unix epoch time (seconds), named in the table's TTL settingUSING TTL <seconds> per write, or default_time_to_live per table
CostThe deletion consumes no write capacityExpiry writes a tombstone (see below)
Visible after expiry?Yes, until the background deletion; filter with a conditionNo (reads treat it as dead), but the tombstone is read until purged
Side effectsDeletions appear in DynamoDB Streams as service deletions, and in indexes like normal deletesA 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).

text
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 dropped

Real 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:

TechniqueHow
Do not use the table as a queueUse a real queue (RabbitMQ or Kafka) or partition by time and drop whole partitions
Time-window compaction with TTLWhole expired SSTables are dropped without scanning
Never write nullsOmit the column on insert; use UNSET bind values in drivers
Bound partitionsTime-bucket the partition key so scans stay short
Tune gc_grace_seconds carefullyLowering 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 periodSee 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 forTrade-off
Size-tiered (STCS)Write-heavy, generalSpace spikes during a merge
Leveled (LCS)Read-heavy, many updatesMore write amplification
Time-window (TWCS)TTL time seriesDo not update old windows
Unified (UCS, 5.0)One strategy that adaptsNewer

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."

text
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 first

DynamoDB 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 StreamsCassandra CDC
EnablePer table, with a StreamViewType that cannot be edited once setWITH cdc = true per table; cdc_enabled: true and cdc_raw_directory in the node config
ContentKEYS_ONLY, NEW_IMAGE, OLD_IMAGE, NEW_AND_OLD_IMAGESCommit-log segments of mutations; you parse them
Retention24 hoursUntil 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 orderPer replica; duplicates across replicas, so consumers de-duplicate
ConsumersAWS Lambda triggers, the Kinesis adapter, FlinkDebezium and similar connectors
text
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 tablesCassandra multi-datacenter
Model"fully managed, multi-Region, and multi-active"; any replica can serve reads and writesKeyspace with NetworkTopologyStrategy, a replication factor per datacenter
ConsistencyMREC (multi-Region eventual consistency, the default) or MRSC (multi-Region strong consistency); cannot change after creationPer query: LOCAL_QUORUM (local), EACH_QUORUM (all DCs), QUORUM (global majority)
ConflictsLast-writer-winsLast-write-wins by cell timestamp
TransactionsACID only in the Region where the write was made; other Regions "may observe partially completed transactions" while changes replicateLWT with LOCAL_SERIAL scope or SERIAL across DCs
Operational costPer-Region replicated write units and storageYour own inter-DC bandwidth and repair
text
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 table

Real 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 driverDynamoDBCassandra / ScyllaDB
ReadsRead units; strong reads cost 2x; Scan reads everything; filters do not reduce the billCluster CPU and I/O; reads at QUORUM touch more replicas
WritesWrite units, per 1 KB; a GSI multiplies writes; a transaction doubles them; global tables replicate every writeReplication factor multiplies writes; LOCAL_QUORUM waits for fewer remote acks
StoragePer GB; indexes store copiesDisks times replication factor; compaction needs free space
IdleNothing in on-demand; reserved in provisionedMachines always run
PeopleAlmost no operationsRepair, upgrades, compaction tuning, capacity planning
Scaling stepsAutomatic, subject to the quotas aboveYou 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.

text
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 too

When 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.

Queries known up front?No: exploratory, ad hocPostgreSQLData and writes fit one machine?Yes: PostgreSQLreplicas, partitioningNeed joins, multi-row rules, reports?Yes: PostgreSQL, shard if neededCitus or app-level shardingAlways-on multi-region writes?Managed, small teamDynamoDB (global tables)Self-hosted, tunable CLCassandra / ScyllaDBWide-column / key-value fitswhen queries are few and known,volume exceeds one primary andavailability beats joins.Otherwise extra tables, backfillsand dual writes cost more.
SignalPostgreSQL (or MySQL InnoDB, SQL Server, Oracle) is enoughA wide-column / key-value store earns its place
QueriesExploratory, reporting, many joinsFew, known, key-based
Data sizeUp to a few TB on one node, with partitioning to tens of TBBeyond what one primary and its replicas can hold or write
WritesThousands per second on one primarySustained write rates one primary cannot absorb
ConsistencyNeeds transactions across entities, constraintsSingle-key or single-partition correctness is enough
AvailabilitySingle region with failoverActive-active multi-region, no maintenance window
TeamKnows SQL, small ops capacityHas operators for Cassandra, or buys DynamoDB's operations
Cost of a wrong choiceA new query is an indexA 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 ​

PropertyDynamoDBCassandraScyllaDBBigtable / HBaseRedisMongoDBPostgreSQL
ModelItems with attributes, PK + SKPartition + clustering rows (CQL)Same as Cassandra (CQL, plus a DynamoDB-compatible API)Sorted sparse map of row, column family, qualifier, timestampKey to data structureJSON documentsRelational rows
DistributionHash on partition keyMurmur3 token ringSame ring, shard per CPU coreRange of row keys (tablets / regions)16384 hash slots in Redis ClusterShard key (hash or range)One primary; partitioning or Citus for more
MasterManagedNoneNoneMaster + lock servicePrimary per shardPrimary per replica setPrimary
Default readEventually consistentSet by clientSet by clientStrong per rowPrimaryPrimary, local concernPrimary
Cross-key transactionTransactWriteItems, 100 actionsNone in 5.0 (LWT per partition)None (LWT per partition)Single-rowMULTI on one shardMulti-document, snapshotFull ACID
Secondary indexGSI, LSI2i, SAI2i, global 2i, viewsApplication-builtApplication-built / search modulesBuilt in, any fieldBuilt in (B-tree, GIN, GiST)
Conflict ruleLast writer (global tables)Last write by cell timestampSameSingle writer per tabletSingle writerSingle primarySerializable options
DeletesItem removedTombstone, gc_grace_secondsTombstoneDelete markers until compactionImmediateImmediate (WiredTiger)Dead tuples until VACUUM
Change feedStreams (24 h)CDCCDCReplication / change streams (version-specific)Keyspace notifications, StreamsChange streamsLogical decoding
Best atServerless key access at any scaleWrite-heavy, multi-DC, self-hostedSame, lower latency per coreHuge sorted scans, time seriesCache, counters, queuesFlexible documentsEverything 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."

StoreHow
PostgreSQLUNIQUE (username); a second insert fails with 23505
MySQL InnoDBUNIQUE KEY; error 1062
SQL Server / OracleUnique constraint or unique index
SQLiteUNIQUE; SQLITE_CONSTRAINT
MongoDBUnique index; E11000 duplicate key
RedisSET username:ana id NX
DynamoDBA lookup item USERNAME#ana with attribute_not_exists(PK); both in one TransactWriteItems with the user item
CassandraA lookup table usernames (name PRIMARY KEY, ...) with INSERT ... IF NOT EXISTS (Paxos)
CockroachDBUNIQUE index; serializable, retry 40001

Mechanics ​

Knobs and limits ​

SettingMeaningValue
DynamoDB partition ceilingRead / write units per partition per second3,000 / 1,000
DynamoDB read unitOne strongly consistent read of 4 KB, or two eventually consistent4 KB
DynamoDB write unitOne write of 1 KB1 KB
Query / Scan pageUp to 1 MB of data, then LastEvaluatedKey1 MB
TransactWriteItemsActions and total size100 actions, 4 MB; capacity is doubled
ClientRequestTokenIdempotency window10 minutes
GSIs / LSIs per tableDefaults20 (adjustable) / 5 (not)
LSI item collectionPer partition key value10 GB, including indexes
On-demand startNew table sustained rate4,000 writes and 12,000 reads per second; up to double the previous peak instantly
DynamoDB Streams retentionHow long records stay readable24 hours
Cassandra gc_grace_secondsTombstone grace864000 (10 days)
Cassandra tombstone_warn_thresholdLog a warning1000
Cassandra tombstone_failure_thresholdFail the read100000
Cassandra max_hint_windowHow long a node stores hints for a down peer3 hours
Cassandra num_tokensVnodes per node16 in the 5.0 default configuration
Cassandra cas_contention_timeoutLWT contention wait1000 ms
Cassandra batch_size_warn_threshold / batch_size_fail_thresholdBatch size5 KiB / 50 KiB
gocql ClusterConfig.ConsistencyDefault levelQuorum

Error codes you will catch ​

ErrorStoreMeaningRetry?
ProvisionedThroughputExceededExceptionDynamoDBExceeded provisioned throughput of a table or GSIYes, with exponential backoff (SDKs do it); fix the key if it persists
ThrottlingExceptionDynamoDBRate of requests exceeds allowed throughput (also control plane)Yes, with backoff
ConditionalCheckFailedExceptionDynamoDBYour ConditionExpression evaluated to falseNo: a business answer
TransactionCanceledExceptionDynamoDBAn action in TransactWriteItems or TransactGetItems was rejected; CancellationReasons ordered like the requestOnly if the reason is TransactionConflict or throttling; the SDK does not retry it
TransactionConflictExceptionDynamoDBA plain write collided with an ongoing transaction on the same itemYes, with backoff
IdempotentParameterMismatchDynamoDBSame ClientRequestToken, different parametersNo: a bug
ItemCollectionSizeLimitExceededExceptionDynamoDBLSI item collection above 10 GBNo: change the key
ValidationExceptionDynamoDBMissing parameter, bad type or range, wrong key schemaNo
Unavailable (0x1000)CassandraNot enough live replicas for the consistency levelMaybe at a lower level; fix the cluster
Write_timeout (0x1100)CassandraCoordinator did not get enough acks in time; the write may still applyOnly if idempotent
Read_timeout (0x1200)CassandraNot enough replicas answered in timeYes, if the query is safe
CAS_WRITE_UNKNOWN (0x1700)CassandraA contended LWT was partly done; the outcome is unknownRead at SERIAL, then decide
Write_failure (0x1500)CassandraA non-timeout failure on a replicaInvestigate

Where the request goes ​

text
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 later

Solving the classic problems ​

Problem: queries that scan ​

SolutionHowAdvantageCost
Name the partition keyQuery with KeyConditionExpressionOne partition, cost proportional to the resultYou must know the key
Add a GSIIndex on the other attributeNew access pathEventual consistency, write cost
Another table or itemDuplicate under a different keyFull control, strong readsYou maintain the copy
Do not use Scan + FilterExpressionThe filter runs after the readNoneWhole-table cost

The before and after code:

go
// 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":

go
// 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.

go
// 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
// 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
<?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 ​

NeedPreferred solutionAlternative
Create only if absentPutItem with attribute_not_exists(PK); Cassandra IF NOT EXISTSA lookup table keyed by the unique value
Decrement stock safelyUpdateItem with ConditionExpression stock >= :qTransactWriteItems with the order Put
Several items togetherTransactWriteItems (100 actions)Saga with compensations (microservices)
Retry-safeClientRequestTokenA request id as the key

Go (aws-sdk-go-v2), building the transaction and mapping the error to a decision:

go
// 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
<?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.)

go
// 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
<?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
<?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
<?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 ​

ApproachVerdict
Cassandra table with insert-process-deleteAnti-pattern: tombstones, slow reads
Time-bucketed partitions plus TTL plus TWCSWorks for expiring work items
DynamoDB table with status and TTLPossible, 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 LOCKEDExcellent up to a large scale (isolation levels)

Retries and failure handling ​

RuleWhy
Let the SDK retry throttling with exponential backoff and jitterDocumented practice for ProvisionedThroughputExceededException
Never retry ConditionalCheckFailedExceptionIt 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 aregocql may retry or speculatively execute idempotent queries
After CAS_WRITE_UNKNOWN read at SERIALThe LWT may have applied
Cap retries and add a jittered backoffRetry storms deepen throttling
go
// 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 ​

WorkloadRecommended storeExtra techniqueReason
Session, cart, profile by idDynamoDB on-demand or RedisTTLOne key per request, spiky traffic
Multi-region SaaS, small teamDynamoDB global tablesHome-region writesManaged multi-active replication
Write-heavy time series, self-hostedCassandra or ScyllaDB with TWCSBucketed partitions, TTLLinear write scale, cheap deletes by window
Feeds and timelinesCassandra or DynamoDBOne table per timeline, fan-out strategyKnown read patterns
Orders, payments, inventory with constraintsPostgreSQLFOR UPDATE, constraintsTransactions and joins
Reporting, analyticsPostgreSQL or a columnar storeReplicas or OLAPAd-hoc queries
Unique usernames at scaleDynamoDB lookup item with a conditionTransaction with the user itemCheap conditional write
QueueA message brokerTombstones 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.

text
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 nothing

Each 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 with ConsistentRead or QUORUM / 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 ​

LoadWhat changesConsequence
1x (one table, modest traffic)On-demand DynamoDB, or a three-node Cassandra RF 3 with LOCAL_QUORUMCheap and simple; design keys now because changing them later means a rewrite
10x (hot keys appear)Write sharding, GSIs for second paths, caching, bounded partitionsWatch 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 tablesConflict 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.

bash
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:8100

1. 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.

go
// 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)
}
bash
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.

bash
go run ./shard
# DATE#2026-11-25#00 615
# DATE#2026-11-25#01 625
# DATE#2026-11-25#02 608
# 16 queries per read

Stop the container: docker rm -f ddb.

3. Cassandra tombstone demo. Start Cassandra and build a queue-shaped partition: 5,000 inserts, 4,999 deletes.

bash
docker run --rm -d --name cass cassandra:5.0
# wait until:  docker exec cass cqlsh -e "select release_version from system.local"
sql
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;
bash
# 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.

bash
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 cass

On 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 ​

BeliefReality
NoSQL has no schemaThe schema is your keys and your code; changing a key means rewriting data
Hashing spreads load evenlyIt spreads keys, not traffic; a hot key is one partition
A Scan with a filter is a queryThe filter runs after the read; you pay for the table
DynamoDB is the Dynamo paperA separate managed service sharing the name and partitioning idea
QUORUM makes Cassandra ACIDIt gives read-your-writes per partition, not transactions
Raising provisioned capacity fixes a hot keyThe per-partition ceiling (3,000 reads / 1,000 writes per second) stays
Cassandra deletes free space immediatelyTombstones live for gc_grace_seconds, and reads scan them
Cassandra repairs itselfHints are best effort; repair is run by the operator
Single-table design is mandatoryIt is one documented choice, with readability costs
DynamoDB transactions are interactive SQL transactionsFixed batches of up to 100 actions, 2x cost, all-or-nothing
A GSI read is as fresh as a table readGSIs are eventually consistent; ConsistentRead is not supported on them
Multi-region means strongly consistentDefault is asynchronous with last-writer-wins
PostgreSQL cannot scaleIt scales further than most teams need; add a wide-column store only for the workload that outgrows it
TTL deletes on timeDynamoDB deletes within days, Cassandra leaves tombstones

Cheat sheet ​

TopicWhat to remember
Partition keyHashed; decides the node; name it in every query
Sort / clustering keyOrders items inside a partition; range reads are contiguous
Query-firstWrite the queries, then the tables; duplicate on purpose
Hot partitionCeiling 3,000 reads / 1,000 writes per partition per second in DynamoDB; shard with a suffix
Read unit / write unit4 KB strong (or 2 eventual) / 1 KB; transactions double it
On-demand vs provisionedPay per request vs reserve a rate; on-demand doubles the previous peak instantly
Single-tableOne partition key per screen, items told apart by SK prefixes
GSI vs LSIGSI: own key, eventual, throttles the table if under-provisioned; LSI: same PK, strong, 10 GB per PK
TransactionsDynamoDB: 100 actions, ClientRequestToken; Cassandra: LWT = Paxos, per partition, sparingly
ConsistencyR + W > N; LOCAL_QUORUM is the multi-DC workhorse; ConsistentRead costs 2x
TombstonesDelete = marker for gc_grace_seconds (10 days); never use a table as a queue
RepairOperator-run Merkle comparison inside the grace period
TTLDynamoDB deletes within days, free of write units; Cassandra TTL = tombstone, use TWCS
StreamsDynamoDB: 24 hours, exactly once, per-item order; Cassandra CDC: you parse commit-log segments
Multi-regionGlobal tables: MREC default, MRSC opt-in, last-writer-wins; Cassandra: LOCAL_QUORUM per DC
Use PostgreSQL whenQueries are ad hoc, data fits, you need joins and constraints

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Partition keyThe key part that is hashed to choose where an item lives
Sort key / clustering keyThe key part that orders items inside a partition
Item collectionAll DynamoDB items sharing one partition key
PartitionThe unit of placement and throughput; a replica set holds it
TokenThe 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 listThe ordered nodes responsible for a key (Dynamo)
Replication factor (RF, N)Number of copies of each partition
Consistency levelHow many replicas must respond to a request
QuorumA majority of replicas (n/2 + 1)
LOCAL_QUORUMA majority in the coordinator's datacenter
EACH_QUORUMA majority in every datacenter
Sloppy quorumUsing the first N healthy nodes instead of strict replicas
Hinted handoffStoring a write for a down replica and delivering it later
Vector clockA list of (node, counter) pairs capturing causality between versions
Last-write-wins (LWW)Conflict rule: the newest timestamp wins
Merkle treeA hash tree used to find differing ranges between replicas
Anti-entropy repairBackground comparison and streaming that makes replicas agree
GossipPeer-to-peer exchange of membership and failure state
TabletBigtable's contiguous row range served by one tablet server
SSTableImmutable sorted file written from a memtable
MemtableIn-memory sorted write buffer flushed to an SSTable
ChubbyGoogle's distributed lock service used by Bigtable
CompactionBackground merging of SSTables
TombstoneA deletion marker kept for gc_grace_seconds
gc_grace_secondsCassandra's tombstone grace period (default 864000)
Read unit / write unitDynamoDB billing and throttling units (4 KB read, 1 KB write)
On-demand / provisionedPay per request, or reserve a per-second rate
Adaptive capacityDynamoDB automatically giving hot partitions more throughput
GSIGlobal secondary index: own key, spans partitions, eventually consistent
LSILocal secondary index: same partition key, different sort key, 10 GB per key
SAIStorage-attached index in Cassandra 5.0
Single-table designSeveral entity types in one table, told apart by key prefixes
TransactWriteItemsDynamoDB's all-or-nothing write of up to 100 actions
LWTCassandra lightweight transaction (IF conditions) on Paxos
PaxosConsensus protocol Cassandra uses for LWT
ClientRequestTokenIdempotency token for a DynamoDB transaction
TTLPer-item expiry
TWCSTime Window Compaction Strategy
DynamoDB StreamsOrdered, 24-hour change log of a table
CDCChange data capture; in Cassandra, commit-log segments exposed per table
Global tableDynamoDB multi-Region, multi-active table (MREC or MRSC)
MREC / MRSCMulti-Region eventual / strong consistency modes
NetworkTopologyStrategyCassandra's per-datacenter replication placement
Hot partitionA partition receiving far more traffic than average
DenormalizationStoring the same fact in several tables or items so each query reads one place
Consistent hashingPlacing keys and nodes on a ring so that adding a node moves only a neighbouring slice
Query-first modelingDesigning one table or key schema per query pattern, copying data between them
Celebrity problemOne very popular key concentrating traffic on a single partition
Write shardingAppending a suffix to a hot key on write and querying all suffixes on read
Read repairWriting the newest version back to a stale replica that a read noticed
Eventually consistent readA read that may miss the latest write (DynamoDB default, Cassandra at ONE)
Strongly consistent readA read that reflects all prior successful writes (ConsistentRead, Cassandra QUORUM after a QUORUM write)
Cost modelHow a store charges: per request unit (DynamoDB) or per machine (Cassandra)

References ​

Built by Morteza Negahi