Every non-relational family stores together, in the order wanted, what one planned question reads, so that question stays one cheap read at any scale; the price is that a question you did not plan becomes a scan, a new table or impossible. That is why Postgres stays the default until a measurement says otherwise.
Fig. 1 puts the six families side by side; in each, the part one planned question reads turns orange and streams to the app. The shapes are drawn to explain (illustrative); the numbers are this page's measurements.
CHAT#7 sit there together in sort-key order, so a Query returns the newest ones in one request.Cheap: counters, rate limits, leaderboards, queues hit thousands of times a second; pick the data structure that answers the question (a sorted set for ranks); every command is atomic.
Hard: data must fit in memory; replication is asynchronous, so a failover lost acknowledged writes here.
Postgres still does it: a counter row with UPDATE ... SET n = n + 1, a job queue with SKIP LOCKED, at low rates.
Cheap: any planned question is one request at any scale, with no servers to run; list the access patterns first, then choose partition and sort keys (often one table for everything).
Hard: a question you did not plan becomes a scan of the whole table; one busy key is capped at 1,000 writes a second.
Postgres still does it: you are not on AWS at that scale, or your questions still change every week.
Cheap: records whose shape varies, read and written as one unit; embed what is read together, reference what grows without bound.
Hard: a document is capped at 16 MB; appends grow the document; cross-document invariants need transactions.
Postgres still does it: almost always: a jsonb column next to normal columns (measured in section 5).
Cheap: writes beyond one machine, many regions, no single point of failure; one table per query, the partition key groups what it reads, the clustering key sorts it.
Hard: no joins, no ad hoc queries; deletes leave tombstones that later reads must skip.
Postgres still does it: while one server keeps up with the writes: the root measured 2,133 to 9,212 small write transactions a second on this laptop, depending on whether each commit is really flushed to disk.
Cheap: appends in time order, recent time ranges, rollups, dropping whole partitions for retention.
Hard: anything that is not a time range; high cardinality (a label per user) explodes memory.
Postgres still does it: native partitioning plus a rollup table, measured in section 7.
Cheap: questions of unknown or large depth over connected data: paths, fraud rings, patterns written in Cypher.
Hard: another system to run; a fixed one or two hops is no faster than Postgres.
Postgres still does it: fixed one or two hops: a join per hop is fast (measured in section 8).
Fig. 1 above draws the layout of each family. Systems named are the ones run for this page; their versions and licences are in one dated table in Depth.
You need: the root Topic: databases, Reading sections 1 to 6 (the chat product, indexes, transactions, the families in one card each); its Database atlas tab compares about 60 systems on licence, consistency and scaling, with sources, and is cited here as "root atlas". Consistency models and quorums in general are Distributed systems fundamentals; LSM-trees and compaction internals are Storage engines and indexes; Redis as a cache is Caching; search and vector stores are Search and vector databases; graphs as a retrieval method for LLMs (GraphRAG) are GraphRAG and structured retrieval.
Results marked measured were recorded for this page on a laptop (an Apple M1 Pro, 16 GB) on 4 and 5 October 2026 against real servers running locally; illustrative marks drawings made to explain a shape. A laptop has no network between client and server, so absolute timings are best cases; the counts (pages, rows, items, partitions) are what carries over to production.
A relational database is designed from the data (each fact stored once: normalisation) and answers any question by joining at query time. A join needs the rows of both tables in one place, which is why it lives on one machine. The non-relational families turn the design around: you write down the access patterns first, then store the data so that each question reads one contiguous piece of storage, by giving every record a partition key (which group, and so which machine) and a sort key (its order inside the group). Data needed by two questions is often stored twice: denormalisation. The chat product's questions run through the whole page:
| Access pattern | Knows | Wants | How often |
|---|---|---|---|
| Open a chat | chat id | its newest 50 messages, newest first | every page view |
| Send a message | chat id, user id | append one message; move the chat to the top of the list | every message |
| Chat list | user id | the user's chats, most recently active first | every page view |
| Log in | the user | every login | |
| Rate limit | user id | may this user send another request now? | every request |
| Usage | user id, month | tokens used per day | billing page |
| Operations | a time range | latency and tokens per model, per minute | dashboards, every few seconds |
| Admin | a model, a day | every message of that model that day | rarely |
The first three are real EXPLAIN (ANALYZE, BUFFERS) runs on PostgreSQL 16.2; the fourth is the same rows in Apache Cassandra 5.0.9 in a table designed for this question, read with tracing on. The strip is the table's data on disk to scale: each cell is pages, lit cells were read. Measured: no index 19,347 page reads, 38 ms; index 57 page reads (49 table pages), 0.129 ms; after CLUSTER 9 page reads (1 table page), 0.043 ms.
Opening a chat is the chat product's most frequent read. The table is the root page's 1M-message table (same generator and seed) plus 20 long-running chats holding 2% of the messages, so chat 7 has measured messages over days. Messages are appended in time order, so a long chat's rows end up scattered: they sit on different 8 KB pages out of . Predict before the steps play: with an index on (chat_id, created_at), how many table pages does Postgres read for 50 rows?
Pick a layout with the buttons on the figure; its steps:
An index tells the database where each of chat 7's rows is, but if they are scattered it still reads one page per row: . Putting a chat's rows next to each other (CLUSTER rewrites the table in index order) makes the same 50 rows one page. That is the whole idea of a partition in a wide-column store or DynamoDB: rows one question reads together are stored together, sorted the way the question wants, and the layout is maintained on every write instead of by an occasional rewrite.
CLUSTER took seconds here but locks the table and is not maintained: new rows land at the end again, so it is a one-off, not a design. The Cassandra table answers this question and no other: "every message by message id" needs another table.Some questions are tiny and asked constantly: "has this user sent more than 20 requests this minute?", "what rank is this player?", "is there a job waiting?". Redis keeps every key and value in memory, and a value is one of a handful of data structures, each with its own commands. The server executes commands one at a time on a single thread, so every command is atomic: no other client's command runs halfway through it. Measured here: Redis 8.8.0 in its default configuration unless stated.
| Structure | What it holds | Commands | Real uses in the chat product |
|---|---|---|---|
| String | bytes or a number | SET, GET, INCR, SET key val NX PX 30000 | a counter; a short lock ("only one worker summarises chat 7") |
| Hash | field to value map | HSET, HGET, HINCRBY | a session; one rate-limit bucket (tokens, last refill) |
| List | ordered sequence | LPUSH, BRPOP | a simple work queue (no acknowledgement: a crashed worker loses its job) |
| Set | unique members | SADD, SISMEMBER | who is online in a shared chat |
| Sorted set | unique members, each with a score, kept in score order | ZADD, ZINCRBY, ZRANGE, ZREVRANK | leaderboards; sliding-window rate limits; delayed jobs scored by run time |
| Stream | an append-only log of entries with ids | XADD, XREADGROUP, XACK, XAUTOCLAIM | jobs with acknowledgement and redelivery (summaries, embeddings) |
Speed is mostly the round trip: one GET took a median 52.1 µs (p99 121 µs) from Python, almost all of it client library and loopback, so one client does about 16,000 to 18,000 operations a second and 50 clients that pipeline 16 commands per round trip (send many, then read all replies) over 520,000. In production the network dominates (Jeff Dean's classic figure is 0.5 ms for a round trip inside one data centre, and Microsoft aims for under about 2 ms between availability zones: the system design page's Numbers to know tab), so the habit that matters is fewer round trips: pipelines, multi-key commands and scripts.
50 clients with one request in flight each did about 33,000 to 35,000 operations a second (redis-benchmark, the tool that ships with Redis). Redis 8 also ships JSON documents, vector sets, time series and a query engine in the main server; HyperLogLog (approximate counts of unique items), bitmaps and geo indexes have existed for years. Each is a reason to keep more state in a store whose durability is weaker than your database's (below).
A sorted set is a hash table (member to score) plus a skip list, a sorted linked list with "express lane" links, so a member's position takes about log2(N) steps (Redis sorted sets: "most sorted set operations are O(log(n))"). In Postgres a rank is a count of the players above you, and the index visits one entry per player above. Measured with 100,000 players:
measured Postgres 16.2, index on (score DESC), SELECT count(*) FROM scores WHERE score > (SELECT score FROM scores WHERE user_id = $1): rank 3 took 6 page reads, rank 50,000 took 142 page reads, 4.67 ms; rank 95,359 took 266 page reads, 8.98 ms (server time). Redis ZREVRANK: median 91 µs wherever the player stands, from the client, so it includes the round trip. The top 10 is cheap in both: 3 page reads, 0.059 ms in Postgres, median 99 µs for ZRANGE lb 0 9 REV WITHSCORES. The set holds 100,000 members in 8.9 MB (about 93 bytes each, MEMORY USAGE) and takes score updates (ZINCRBY) at about 10,500 a second from one client.
A rate limiter decides, on every request, whether a user may make another one. The obvious code reads the remaining allowance, decides in the application and writes back; run by many servers at once, two requests read the same allowance before either writes, and both pass. Predict: 16 processes each make 50 attempts against an allowance of 20; how many get through?
The script is a token bucket: up to capacity tokens, refilled at a steady rate, one taken per request, so bursts up to the capacity and a long-run average equal to the refill rate. It uses the server's clock (TIME) so every app server agrees on "now", and passes the bucket's name in KEYS, which Redis Cluster needs to route the script to the server that owns the key. Choosing among limiter algorithms and where limits sit in a system is Reliability engineering's and Capacity planning and performance's.
| Algorithm | Redis implementation | Measured, one client | Behaviour |
|---|---|---|---|
| Fixed window | INCR user:7:<minute> plus EXPIRE | 7,623 checks/s | cheapest; a burst at the end of one minute and the start of the next can pass twice the limit |
| Sliding window log | a sorted set of request times: trim older than 60 s, add, count (in MULTI) | 4,645 checks/s | exact; one entry per request, so memory grows with the limit |
| Token bucket | the Lua script above, one hash per user | 8,155 checks/s (21,147 with 8 clients) | smooth; bursts up to the capacity; two numbers per user |
All three are round-trip bound on this laptop (one check per round trip).
"Read, decide, write" in the application let 188 of 800 attempts through a limit of 20. The same limit as one Lua script inside Redis let exactly 20 through, because "while executing the script, all server activities are blocked during its entire runtime" (Redis docs, scripting with Lua).
Redis writes to disk in two optional ways (Redis persistence). An RDB snapshot is a point-in-time copy written by a forked child every so often ("you should be prepared to lose the latest minutes of data"). The append-only file (AOF) logs every write; with appendfsync everysec, the default when AOF is on, it is flushed once a second, so a power cut loses about a second of writes; with always it is flushed before each reply. Measured (SET throughput from redis-benchmark, then a writer incrementing a counter for 3 seconds before kill -9):
RDB only: 40,255 acknowledged, all lost (no snapshot had been taken yet); AOF everysec: 50,324 acknowledged, 0 lost. A kill -9 is a process crash, not a power cut: the operating system still holds what Redis wrote, which is why AOF lost nothing. On macOS a flush does not force the drive's own cache, so always is cheaper here than on a Linux server with a real flush.
Redis copies writes to its replicas after replying to the client: replication is asynchronous. Fig. 2 replays the measured run: a primary and a replica on this laptop, the replica paused (as a long garbage-collection pause or a network problem would), 10 KB writes, the primary killed, the replica promoted.
WAIT returned 1.WAIT 1 500 returned 0: no replica confirmed, and asking does not make the writes safer.kill -9 on the primary: its memory, holding every acknowledged write, is gone.The WAIT 1 500 call after the writes returned 0: it reports how many replicas confirmed, it does not make the writes safe ("WAIT does not make Redis a strongly consistent store", Redis WAIT). Jepsen measured the same with Sentinel failover in 2013 (56% of acknowledged writes lost; root atlas). So Redis must not be the only copy of anything you cannot rebuild.
A list makes a queue, but a worker that pops a job and crashes loses it. A stream is an append-only log; a consumer group hands each entry to one consumer and keeps it in a pending entries list until the consumer acknowledges it with XACK; another worker can claim an idle pending entry with XAUTOCLAIM. That is at-least-once delivery: a job can run twice, so it must be safe to repeat. Durable logs, the outbox pattern and Kafka are Queues, streams and async work's; a Redis stream is the small version, with Redis's durability.
KEYS *, a long script, a ZRANGE returning a million members) stalls every client. Durability and replication are weaker than a database's by default, as measured. Redis Cluster shards keys over 16,384 hash slots, and a multi-key command or script works only when all its keys are in one slot (use hash tags such as {user:7}:bucket). The licence changed in 2024 and Valkey forked (dated table in Depth); Valkey speaks the same protocol and commands as Redis 7.2, so the code here works on both.UPDATE ... SET n = n + 1 is atomic); a job queue with SELECT ... FOR UPDATE SKIP LOCKED (measured on Transactions and concurrency); a rate limit at tens of requests a second; top-N lists. Redis as a cache in front of Postgres (cache-aside, eviction, invalidation, stampedes) is Caching's subject.Suppose the chat product needs a store that grows without limit, survives the loss of a data centre, has no servers, upgrades or vacuum to manage, and every request already knows its key. That is what Amazon DynamoDB sells: a managed, partitioned key-value and document store, billed per request or per reserved capacity.
GetItem (the full key: one item), Query (one partition key, optionally a sort key condition such as begins_with or between; items in sort order, up to 1 MB per page) and Scan (every item in the table). Nothing else: no joins, no query on a non-key attribute without an index.With no joins, a screen that needs a user, their chats and a chat's messages would take several requests if each kind of item had its own table. Single-table design puts every kind of item in one table, with generic key strings (PK, SK) holding a type prefix and an id, chosen so that the items one screen needs share a partition key and come back in one Query, sorted (Alex DeBrie, The What, Why, and When of Single-Table Design, 2020-02-05). From the access patterns of section 1:
PK = CHAT#<chatId>, SK = MSG#<createdAt>#<messageId> (an ISO timestamp sorts correctly as a string; the id breaks ties). Query PK = CHAT#7, SK begins_with MSG#, descending, limit 50.PK = USER#<userId>, SK = USAGE#<day>, updated with an atomic ADD; Query SK begins_with USAGE#2025-09. The profile (SK = PROFILE) shares the partition, so one Query can fetch both.PK = USER#<userId>, SK = CHAT#<chatId>, sorted by id; a global secondary index (GSI1) re-keys them: GSI1PK = USER#<userId>, GSI1SK = LAST#<lastMessageAt>#<chatId>. Sending a message updates GSI1SK, and the chat moves to the top.PK = EMAIL#<email> holds the user id; registration writes the user and the lookup item in one transaction, each with attribute_not_exists(PK), so a duplicate email fails.Try it: start from Relational habit (one kind of item per table, keyed by its own id) and predict how many questions become scans; then switch to Single-table design. Change only the message key to MSG#{messageId} and watch "latest 50 messages" collapse into a scan.
Every planned question is one request that reads only the items it returns. The wrong ways show what a missing key costs: a Scan with a filter for chat 7 read 1,000 items in its first page and returned none of them (the filter runs after the read, and you pay for every item read), and answering the admin question by scanning read all 54,775 items in 9 pages of 1 MB for 1,111.5 read units. At a billion items the same scan reads a billion items.
The table as DynamoDB stores it: a sample of items under the current design, grouped by partition key and sorted by sort key, the way a Query sees them; rows the selected question reads are highlighted. Rules are DynamoDB's own, checked on DynamoDB Local; item counts use the measured load: .
Measured on DynamoDB Local 3.3.1 (AWS's downloadable version of the API) with the chat data: 400 users, 2,999 chats, 49,517 messages, 54,775 items in all. Local runs the real API, key rules and capacity accounting, but not the service's partitions, throughput limits or latency, so only counts are shown.
A global secondary index is a second copy of chosen attributes under a different key, maintained by DynamoDB asynchronously ("eventually consistent fashion ... within a fraction of a second, under normal conditions", AWS, GSI): a chat list read right after sending a message can still show the old order, and a strongly consistent read on it is refused. Each index is paid on every write: changing an indexed key costs two index writes (delete the old entry, put the new one), and an index short of write capacity throttles writes to the table.
A table has at most 20 GSIs by default and 5 local secondary indexes (same partition key, different sort key, strongly consistent, but they cap an item collection at 10 GB and stop adaptive capacity from splitting it).
Measured: one message put cost 1 write unit (a message item is about 173 bytes as DynamoDB counts size); the transaction that writes the message and moves the chat to the top of GSI1 cost 8 write units as DynamoDB Local accounted it. Registering a second account with an existing email failed with TransactionCanceledException, reasons [None, ConditionalCheckFailed]: the user item would have been fine, the email item already existed, so neither was written. An item over 400 KB was refused; a long document or file goes to S3 with its key stored in the item.
All of one chat's messages share a partition key, so one very busy group chat can take at most 1,000 one-KB writes a second. DynamoDB keeps up to 300 seconds of unused capacity for bursts, and adaptive capacity moves busy items onto partitions of their own, "provided that traffic does not exceed ... the partition maximum capacity" (AWS, burst and adaptive capacity). Past that the fix is write sharding: spread one hot key over CHAT#7#0 to CHAT#7#9 and have readers query all ten and merge. Move the write rate past 1,000, then add shards:
Two billing modes: on-demand per request (simplest, right for spiky or unknown traffic) and provisioned reserved units per hour with auto scaling (cheaper for steady, predictable traffic); dated prices are in the calculator note above and the table in Depth. Discord hit the same per-key wall in Cassandra with its busiest channels (section 6).
Some records have no fixed shape: a tool call carries different arguments per tool; a user's settings grow a field every month. A document stores the record as one nested JSON-like value, read and written as a unit. MongoDB keeps documents in collections, in BSON (binary JSON with real dates and integers), each with a unique _id; any field can be indexed, including fields inside arrays; queries use a JSON query language or an aggregation pipeline of stages. Underneath, WiredTiger keeps compressed B-trees and a journal; a replica set has one primary and copies; sharding splits a collection by a shard key you choose (root atlas). Measured here: MongoDB 8.0.23 as a one-member replica set, because transactions need one.
MongoDB's guidance: embed when you "query pieces of information together" and update them together; reference when "the child side of the relationship has high cardinality" or "your embedded data grows without bounds" (MongoDB, embedding vs references). A chat's messages are the textbook hard case: always read together, and growing without bound. Both shapes were loaded with the same 1M messages. Predict: which shape reads fewer bytes to show chat 7's newest 50?
Then the hard limit: a BSON document may not exceed 16 MiB (MongoDB limits). Pushing messages of about 1 KB into one chat, the th fit (the document reached bytes) and the next failed with Resulting document after update is larger than 16777216 (error 10334): the limit was hit at 15,220 messages. Appends also slow as the array grows: a $push took 6.2 ms into a 10-message chat and 13.1 ms into a 20,000-message chat of 3.4 MB, against 6.0 ms to insert one referenced message. A busy group chat would hit it in weeks, and long before that every read drags the whole history along.
The design pros use: the chat document holds its metadata and perhaps the last few messages for the chat list (embedding a bounded subset); messages are referenced, one document each or grouped in fixed-size "buckets" of, say, 100 per document (MongoDB's bucket pattern). Tool-call arguments, whose shape varies and which are always read with their message, are embedded in the message. Every write here took several milliseconds because the default write concern (w: "majority", measured: ) waits for the journal to be flushed before acknowledging.
measured MongoDB 8.0.23. Referenced: 50 index keys and 50 documents of about 188 bytes, median ms. Embedded: 1 document examined, but it is KB holding all messages, median ms. Bars are drawn to one scale per row; the lower row is the document-size limit (16 MiB) with real documents marked.
{ _id: 412345, chat_id: 7, role: "user", model: "large",
tokens: 42, content: "...", created_at: ISODate(...) }
index: { chat_id: 1, created_at: -1 }
{ _id: 7, title: "Chat 7",
messages: [ { id: ..., role: "user", ... }, ... ] }
read: find({_id: 7}, {messages: {$slice: -50}})
$push into the array: ms into a 10-message chat, ms into chat 7, ms into a 20,000-message chat ( MB)Indexes are B-trees on one or more fields, used for equality, ranges and sorts. For compound indexes MongoDB's rule of thumb is ESR: equality fields first, then sort fields, then range fields (MongoDB, the ESR guideline); {chat_id: 1, created_at: -1} is equality then sort. An index on an array field indexes every element (a multikey index). Tokens per model per day over all 1M messages:
It took ms and returned groups; the same question in Postgres took ms on plain columns and ms on jsonb documents. Neither is the tool for analytics at scale (section 7 and the analytics child page).
A write to one document is atomic; multi-document transactions run with snapshot isolation (since 4.0 on replica sets, 4.2 on sharded clusters), at most 60 seconds by default (root atlas; MongoDB limits). Measured: two transactions updating user 7's document at once: the second failed immediately with WriteConflict (code ), labelled . MongoDB does not make the second writer wait as Postgres does; it aborts it and expects the client to retry the whole transaction, which the drivers' with_transaction helper does for that label. A collection can carry a $jsonSchema validator: one requiring chat_id and role in user, assistant or tool refused {role: "admin"} with . Without one, "no schema" becomes several schemas that every reader must handle.
Moving one credit from user 7 to user 12 in a transaction committed ( and credits). Reads use read concern "" by default, which can return data that a failover later rolls back, and Jepsen found in 2020 (4.2.6) that transactions did not give snapshot isolation at the default settings (root atlas). The docs advise modelling so that most operations touch one document.
jsonb is a binary JSON column type you can index and query next to ordinary columns, inside ordinary transactions. Measured on PostgreSQL 16.2 with the same messages three ways: plain columns, one jsonb document per message, one jsonb document per chat holding its messages array.
The jsonb-per-message table is times the size of the plain columns, because every row repeats its field names; a GIN index (an index of every key and value inside each document) answered a containment query (doc @> '{"model": "large", "role": "user", "tokens": 42}') in ms for matches, with a MB index. Appending to the jsonb-per-chat document rewrites the whole value, which the write-ahead log makes visible: bytes of log per message appended to chat 7's document against for a 10-message chat (averages over 200 appends). Inserting a message as its own row took ms whatever the chat's size.
$lookup stages; growing arrays hit the 16 MB limit and make every write handle more; multi-document invariants need transactions that abort on conflict and must be retried.jsonb column, with a GIN or expression index if you query inside it. MongoDB earns its place when most data really is document-shaped, read and written whole, and the team wants its built-in sharding or Atlas's managed service.Suppose messages arrive faster than one primary can write them, users are on several continents, and losing a whole data centre must not stop anyone sending. A single-primary database cannot give all three. Apache Cassandra (and ScyllaDB, its C++ reimplementation) spreads every table over many equal machines, with no primary at all.
PRIMARY KEY ((a, b), c, d) has two parts. The partition key (a, b) is hashed to a token; the nodes form a ring in which each owns ranges of tokens, so the token decides which nodes hold the partition. The clustering columns c, d sort the rows inside it.The table measured in section 2, as created on Cassandra :
Why bucket? A partition that grows forever lives on the same few nodes, and reading, repairing or compacting it gets slower; the modelling guide says to keep partitions "below 100,000" values and "below 100MB". Discord's January 2017 design is exactly this table: ((channel_id, bucket), message_id) with "about 10 days of messages within a bucket" (Discord, How Discord Stores Billions of Messages). Here the bucket is a 10-day window too: chat 7's messages fall into partitions, the newest holding rows. Opening the chat reads the newest bucket, and the one before if it holds fewer than 50. Any other question is refused rather than run slowly: asking for one message by id returned (ALLOW FILTERING forces it through by scanning, on a real cluster every node).
Each request chooses how many of the RF replicas must answer: ONE, QUORUM (a majority: floor(RF/2) + 1), LOCAL_QUORUM (a majority inside the local data centre) or ALL (Cassandra, Dynamo architecture). Fig. 3 steps one write at QUORUM with one replica down:
INSERT of a message into partition (7, 3). Whichever node receives it becomes the coordinator for this request; there is no primary to find.commitlog_sync: periodic flushes the log every 10 seconds, so the write is not yet on disk on either node.ONE it would reply after the first answer; at ALL this write would fail, because C is down.max_hint_window (3 hours by default). After longer, C stays out of sync until read repair or a full repair copies the write.illustrative layout, RF = 3. Sources: the Dynamo architecture page above; commit log defaults from cassandra.yaml as measured here (commitlog_sync: , period ); hints from Cassandra 5.0, hints (max_hint_window "defaults to 3 h").
If the replicas a write waited for (W) and the replicas a read asks (R) must overlap, W + R > RF, every read meets at least one replica with the latest acknowledged write. The default level is ONE, so by default a read can be stale (root atlas). Predict, then try: at RF 3 with one replica down, do QUORUM writes and reads still succeed and agree? Knock out a second.
What the arithmetic does not say: conflicting writes are resolved by timestamp, last write wins, so two clients updating the same cell lose one update silently (Jepsen showed acknowledged writes lost this way in 2013; root atlas). The theory of quorums and consistency models is Distributed systems fundamentals's.
For compare-and-set ("insert only if absent") Cassandra has lightweight transactions, which run a Paxos consensus round among the replicas for each operation and so cost extra round trips. Multi-partition ACID transactions (Accord) arrive only with Cassandra 6.0, still in alpha (root atlas). Durability: the default periodic commit log acknowledges writes before they are flushed, so one node can lose up to 10 seconds of writes in a power cut; replicas on other machines are what make the write safe.
An LSM-tree cannot erase a row in place: the row may sit in several immutable files on several replicas. So a delete writes a tombstone, a marker that hides older data, kept for gc_grace_seconds (default 864,000 seconds, 10 days) so every replica learns of it; a replica that misses the delete for longer can bring the data back ("zombie" rows) (Cassandra, tombstones). Until compaction drops them, a read steps over every tombstone in its way. Measured: a partition of 130,000 messages, the newest deleted one by one, then "the latest 50":
measured: 5,000 tombstones made the read about nine times slower; 101,000 made it fail, past the default tombstone_warn_threshold: and tombstone_failure_threshold: .
Discord hit this six months into production: a public channel with millions of deleted messages and one remaining message made Cassandra "scan millions of message tombstones", causing 10-second garbage-collection pauses; they cut the grace period from 10 days to 2 and stopped re-reading empty buckets (same Discord post). The lesson: a table used like a queue (insert, read, delete) is the classic anti-pattern; expire data with a TTL in time-ordered tables, and choose compaction to match.
| Strategy | How it merges | Fits |
|---|---|---|
| SizeTiered (STCS) | merges files of similar size once there are several (here min_threshold 4, max_threshold 32) | write-heavy tables; the default, and what this table got () |
| Leveled (LCS) | keeps levels of non-overlapping files, so a read touches about one file per level | "read heavy workloads, or workloads with lots of updates and deletes" |
| TimeWindow (TWCS) | one bucket of files per time window, never merged across windows; a whole window is dropped when its TTL expires | "TTL'ed, mostly immutable time-series data" |
| Unified (UCS, new in 5.0) | one tunable strategy that can behave like tiered or levelled | "recommended for new workloads" |
Quotes from Cassandra 5.0, compaction overview.
ScyllaDB reimplements Cassandra in C++ with one shard per CPU core and no garbage collector, speaks CQL (and a DynamoDB-compatible API), and is what Discord moved to: 177 Cassandra nodes became 72 ScyllaDB nodes (the system design page's Case files, "Trillions of messages", March 2023). Its licence terms are in the dated table in Depth. Google Bigtable and HBase share the wide-column shape (row key to column families), with single-row atomicity and no multi-row transactions.
The operations dashboard wants requests per minute, median latency and tokens per model for the last hour, refreshed every few seconds, and a 30-day trend; every chat request produces one measurement. That data is append-only in time order, read by time range, and matters less as it ages: last hour in full, last month per minute (downsampling), then deleted (retention). Every time-series database exploits the same three facts: time-sliced chunks so a range touches few chunks, precomputed rollups, and expiry by dropping whole chunks instead of deleting rows. All three exist in plain Postgres, which is what was measured (5,184,000 request rows over 30 days: 4 models, 8 servers, about 2 a second).
Chunks by time turn a range into a few chunks, a chart into a rollup, and retention into a drop; Fig. 4 runs the three questions on the same rows in two layouts:
ts is just as quick here (79 pages, 2.6 ms); partitions pay off for retention and for scans of a few days.measured PostgreSQL 16.2, one big table against 30 daily partitions. A one-minute rollup table of 172,800 rows drew the 30-day hourly chart in 45.6 ms instead of 1,405 ms from the raw rows, with the same answer (checked with EXCEPT). Dropping 7 daily partitions took 0.06 s and 29,816 bytes of log; a DELETE of the same rows from one table took 1.9 s and 65 MB of log, and the table stayed 317 MB on disk even after VACUUM (the space is reused, not returned).
Because rows arrive in time order, a BRIN index (the minimum and maximum timestamp per block range) on ts is KB against MB for a B-tree. The same rows as compressed Parquet are about a tenth of the size, and DuckDB drew the 30-day chart straight from the file in ms: column stores are very good at this (Analytics owns them).
In Prometheus-style systems a series is one metric name plus one combination of label values, and every series costs memory and an index entry. "Every unique combination of key-value label pairs represents a new time series ... Do not use labels to store dimensions with high cardinality (many different label values), such as user IDs, email addresses, or other unbounded sets of values" (Prometheus naming). Series multiply. Predict what one user_id label does, then tick it:
Per-user and per-request detail belongs in logs, traces or an events table in a column store, where a row per request is normal; metrics stay aggregate. Instrumenting in practice is Observability's.
Series = product of the label value counts (an upper bound: only combinations that occur create series). Samples per day = series x 86,400 / scrape interval of 15 s. Disk per day uses Prometheus's "1-2 bytes per sample" (Prometheus storage; 2 used here); head memory per series is not documented as a fixed figure, so none is shown.
| System | How it stores data | Query language | Reach for it when |
|---|---|---|---|
| TimescaleDB (Postgres extension) | Hypertables: a table split automatically into time chunks, older chunks converted to compressed columns; continuous aggregates are rollups kept up to date for you | SQL, joins with your other tables | time-stamped data that must join your Postgres data; the two measured ideas above, automated. Compression and continuous aggregates are under the source-available Timescale License (root atlas) |
| Prometheus | its own TSDB: recent samples in memory plus a WAL, cut into immutable two-hour blocks on local disk, compacted later; default retention 15 days | PromQL | service metrics and alerting: it pulls ("scrapes") numbers from your services every few seconds. Deliberately one node; long-term storage goes to Thanos, Mimir or VictoriaMetrics (root atlas) |
| InfluxDB 3 | Arrow in memory, DataFusion as the query engine, Parquet files on object storage; a WAL flushed every second (root atlas) | SQL and InfluxQL | high-volume sensor and app metrics with many tag values, kept cheaply on object storage |
| ClickHouse | MergeTree: sorted, compressed column parts merged in the background (root atlas); a table-level TTL drops old data (ClickHouse MergeTree) | SQL | events, logs and metrics at billions of rows when you want SQL over everything; often does a dedicated TSDB's job |
Two corrections from the root atlas: Thanos (sidecar mode) uploads Prometheus's own blocks, while Mimir and Cortex receive samples by remote write and build the blocks themselves; and InfluxDB 3 is a Parquet and DataFusion engine, unlike the 1.x and 2.x engines most tutorials describe.
DROP of old partitions; TimescaleDB automates exactly this. Service metrics with alerting belong in Prometheus (or a hosted equivalent) regardless; analytics over billions of events in a column store.Some questions are about connections: "people you may know" (friends of friends), "is this account linked to a known fraud ring within four steps", "how is user A connected to user B". In tables each step is a join, and the number of steps is not known when you write the query. A property graph has nodes (a user, a chat) and relationships (FRIEND, OWNS), each with a type, a direction and properties. Queries are patterns in Cypher (Neo4j also accepts GQL, the ISO graph query language that grew out of it): MATCH (u:User {uid: $u})-[:FRIEND*1..3]-(v) RETURN count(DISTINCT v) reads "from user u, follow one to three FRIEND relationships in either direction". Neo4j stores each relationship as a record pointing directly at its two nodes and at the next relationship of each, so following one is a pointer lookup rather than an index search: index-free adjacency (root atlas; Robinson, Webber and Eifrem, Graph Databases, 2nd edition, O'Reilly 2015, chapter 6).
Fig. 5 follows one of the ten sampled users, user 24204, outward on the measured graph:
shortestPath found user 24204 to user 24891 in 4 hops (24204, 6190, 116, 4989, 24891) in 5.0 ms.A synthetic social graph grown the way real ones grow (each new user befriends 10 existing users, chosen in proportion to how many friends they already have): users, friendships, a median of friends but a most-connected user with . For 10 random users, count everyone within k hops on PostgreSQL 16.2 (two ways), Neo4j Community and Kuzu , an embedded graph engine (a library, like DuckDB). Predict which engine wins at two hops.
All four engines agree on every count. At four hops, where every engine touches nearly the whole graph, Neo4j was only than Postgres's better query. Times are measured from the client (Neo4j and Postgres over a local connection, Kuzu in process). The work is set by the answer: by 3 hops a typical user reaches about a third of the graph, by 4 nearly all of it, and every engine must touch those rows. In SQL, write one DISTINCT join per hop to keep each frontier small; a naive recursive query (whose UNION removes only exact duplicate (user, depth) rows) finished here but revisits users along many paths on denser graphs. Neo4j's planner made the same move by itself: VarLengthExpand(Pruning,BFS,All), a breadth-first expansion that drops nodes already seen.
Ask for the path instead of a count. Neo4j's shortestPath connected user to user in hops in ms with one line of Cypher. In Postgres:
The SQL that carries the path is short but explores every path rather than every user, so it slows sharply with depth; the version with a visited set must be driven from application code, one query per hop. Graph databases earn their place when such questions are the product (fraud rings, recommendation paths, permissions inherited through groups, knowledge graphs), when depth is variable or large, and when patterns over several node and relationship types ("accounts that share a device with an account that shares a card with a flagged account") would be a page of SQL. Building a graph from documents for LLM retrieval is GraphRAG and structured retrieval's.
SET n.x = n.x + 1 (Neo4j, concurrent data access). Kuzu's repository was archived by its owners, so treat it as a demonstration, not a dependency (dated table in Depth). Apache AGE adds Cypher inside Postgres, with traversals planned as joins (root atlas).| The measured problem | Postgres first | The store it justifies |
|---|---|---|
| Exact ranks for 100,000 players on every page view cost 9 ms each (section 3) | top-N from an index; ranks recomputed every minute | Redis sorted set |
| Thousands of atomic checks a second (rate limits, counters) | UPDATE ... SET n = n + 1; SKIP LOCKED queues | Redis, with a Lua script |
| Writes exceed one primary, or must survive a data-centre loss with no failover pause (sections 4 and 6) | replicas, partitioning by time, then Scaling a database | Cassandra, ScyllaDB or DynamoDB, keys from the access patterns |
| Records of varying shape, read and written whole (section 5) | columns plus a jsonb column, GIN index | MongoDB, when most data is document-shaped |
| Every dashboard query scans 30 days (section 7) | daily partitions, a rollup table, BRIN | Prometheus for metrics; a column store for events |
| Variable-depth paths and patterns are the product (section 8) | a join per hop; recursive CTE for hierarchies | Neo4j |
jsonb (section 5), partitions and rollups (section 7), a join per hop (section 8), SKIP LOCKED queues.Backups, replication and failover for Postgres itself are Running Postgres in production's; sharding Postgres and distributed SQL are Scaling a database's.
| System | Settings pros check first (each explained on this page) |
|---|---|
| Redis / Valkey | maxmemory and an eviction policy when it is a cache, noeviction when it holds data you need; appendonly yes with appendfsync everysec if losing a minute matters; replicas plus Sentinel or Cluster for failover, knowing that failover can drop acknowledged writes; no KEYS * in production (use SCAN); short scripts. |
| DynamoDB | access patterns and keys reviewed before the first write; on-demand capacity until traffic is predictable; alarms on throttled requests; Contributor Insights to find hot keys; a TTL attribute to expire items; incremental export to S3 for analytics. |
| MongoDB | write concern majority (the default since 5.0); a $jsonSchema validator per collection; one index per access pattern, ordered by ESR; no unbounded arrays; transactions short and retried on TransientTransactionError. |
| Cassandra / ScyllaDB | replication factor 3 across racks or zones, LOCAL_QUORUM for reads and writes that must agree; partitions bounded by a time bucket; repair run more often than gc_grace_seconds; alerts on tombstone warnings and large partitions; compaction chosen per table. |
| Prometheus and friends | no unbounded label values; retention and rollups set on purpose; long-term storage (Thanos, Mimir, VictoriaMetrics) only when one server's retention is not enough. |
Configuration names and documented behaviours from the sources linked in each section; a checklist, not a complete production guide.
INCR, a Lua script, a conditional write, UPDATE ... SET n = n - 1 WHERE n > 0).ONE can all return data from before your write. Read from the primary, or use a strong read where one exists, for the request right after a write.Every database above sits on a storage engine: the library that turns "put this key and value" into bytes on disk. RocksDB is an embedded LSM-tree: a write-ahead log and a memtable, sorted files, background compaction; fast writes, tunable read, write and space amplification, many knobs. It is inside CockroachDB (via Pebble, its Go port), TiKV, Kafka Streams' state stores and many others; by default its WAL is not flushed to disk on every write, so a machine crash can lose the last writes (root atlas). Storage engines and indexes measures its amplification against Postgres. LMDB is a copy-on-write B+tree in one memory-mapped file: no WAL, no compaction, readers never block and see a consistent snapshot, but one writer at a time; very fast reads from many threads or processes; commits are flushed by default.
Reach for one directly only when building a storage component (a queue, a persistent cache, an index) inside one process and you want neither a server nor SQL. Otherwise SQLite (rows, SQL, one writer) and DuckDB (columns, analytics), on the root page, are the embedded databases to use.
| System | Version used or current | Licence and dated facts |
|---|---|---|
| Redis | 8.8.0 measured | BSD until 7.2; dual source-available licence (RSALv2 or SSPLv1) from 7.4 on 20 March 2024; Redis 8 added AGPLv3 as a third option on 1 May 2025. Redis 8-only features (built-in JSON, vector sets, the query engine) do not exist in Valkey under those names. |
| Valkey | fork of Redis 7.2.4 | BSD, launched by the Linux Foundation on 28 March 2024, backed by AWS, Google Cloud, Oracle and others |
| DynamoDB | DynamoDB Local 3.3.1 measured | US East (N. Virginia), standard table class, read 4 October 2026: on-demand $0.625 per million write units and $0.125 per million read units (on-demand pricing); provisioned $0.00065 per write unit-hour and $0.00013 per read unit-hour (provisioned pricing); storage $0.25 per GB-month |
| MongoDB | 8.0.23 measured; 9.0 generally available 28 September 2026 | server under the SSPL (source-available) since 16 October 2018 |
| Cassandra | 5.0.9 measured; 6.0 in alpha (Accord transactions) | Apache 2.0 |
| ScyllaDB | 2025.1 onward | AGPL open-source edition ended with 6.2; one source-available product, free only within 10 TB and 50 vCPUs (licence v1.1, April 2026) |
| Neo4j | Community 2026.09.0 measured | Community is GPLv3; clustering is Enterprise-only |
| Kuzu | 0.11.3 measured (last release) | GitHub repository archived by its owners on 10 October 2025; still works, receives no fixes (kuzudb/kuzu) |
| Time-series systems | TimescaleDB 2.30, Prometheus 3.15, InfluxDB 3.11, ClickHouse 26.9 | TimescaleDB compression and continuous aggregates under the Timescale License |
| Embedded engines | RocksDB 11.8; LMDB 1.0.0 released 30 June 2026 after the long 0.9 line |
From the root page's Database atlas (sources there) unless linked.
src/measure and src/inputs folders. Facts about other systems come from the root page's Database atlas (checked on 4 October 2026) unless linked.Every link opens in a new tab; times are estimates for a careful first read. Links checked on 4 and 5 October 2026.
The root: one chat product's data from a file to a fleet. Its map gives each family in one row (what it keeps together, what that makes cheap, its price); the Database atlas tab compares about 60 systems (licence, consistency, Jepsen results, scaling, versions) with sources; SQL playground and Query plans run on the same chat data. About 27 minutes, plus the tabs.
Normalisation, keys, jsonb and recursive CTEs in depth: the relational side of every comparison here. Child page, about 48 minutes.
Isolation levels, lost updates and SKIP LOCKED queues, measured on Postgres and MySQL. Child page, about 43 minutes.
B-trees against LSM-trees with RocksDB measured: the engines under Cassandra, DynamoDB, MongoDB and Redis's persistence. Child page, about 42 minutes.
EXPLAIN, statistics and slow queries: how to make Postgres do the job before reaching for another store. Child page, about 45 minutes.
Redis as a cache: layers, cache-aside, eviction, invalidation, stampedes, LLM caches. Child page, about 43 minutes.
Inverted indexes, BM25, ANN indexes and pgvector: the two families this page leaves out. Child page, about 33 minutes.
Where the admin question and the 30-day charts go. Child page, about 46 minutes.
Read replicas, sharding Postgres and distributed SQL: the relational answer to "writes outgrow one machine". Child page, about 45 minutes.
Backups, replication, vacuum and pooling for the source of truth. Child page, about 43 minutes.
Discord's "Trillions of messages" (hot partitions, request coalescing, Cassandra to ScyllaDB) and 32 other real architectures and outages. About 25 minutes per case.
Replication, consistency models, quorums, Raft and clocks: the theory under section 6's arithmetic. Child page.
Load, cache strategy and where rate limits sit. Child page.
Durable queues, Kafka, the outbox and change data capture: how secondary stores are kept in step. Child page.
Metrics, logs and traces in practice: Prometheus and cardinality from the user's side. Child page.
Timeouts, retries and SLOs around every store on this page. Child page.
Feature stores (an offline store plus a key-value online store) and the rest of an LLM service's data path. Child page.
Data models, storage engines, replication and partitioning: the book behind this whole topic. A book; the data models and partitioning chapters about 3 hours.
The clearest account of single-table design and when not to use it; his book, The DynamoDB Book, goes further. About 25 minutes.
How DynamoDB's partitions, Multi-Paxos replication and admission control actually work. About 1 hour.
A real wide-column design for this page's exact question, its tombstone incident, and the move to ScyllaDB. About 30 minutes for both.
Query-first modelling with worked examples, partition size guidance. About 40 minutes.
What RDB and AOF really guarantee; how scripts run atomically and what that blocks. About 30 minutes.
Embedding against referencing, and the design patterns (bucket, subset, extended reference). About 45 minutes.
Independent tests of what Redis, MongoDB, Cassandra, ScyllaDB, etcd and others really do under failures; the root atlas summarises the relevant ones. About 30 minutes per analysis.
The TSDB's blocks and WAL, the disk formula, and the cardinality rule. About 20 minutes.
Property graphs, Cypher and how a native graph store lays out records (chapter 6). A book; chapters 3 and 6 about 2 hours.