Choosing a database: a decision framework
Profile the workload against the three jobs, price the operations you are signing up for, measure how far Postgres goes, and write the decision down so it can be revisited
The shop runs on one Postgres 17 primary with a replica. Four new requirements arrive. Which one is the weakest fit for that Postgres, and the most likely to need a different engine?
The first chapter of this course said every database is a set of trade-offs around three jobs: keeping committed data (durability), letting many writers work at once (concurrency), and finding data by content (queries). Module three has been a tour of the engines that make different trades. This chapter turns the tour into a procedure you can run on a real requirement, and then makes you run it six times.
Start with the workload, not the product
A request arrives as a product name (“we need Elasticsearch”, “let’s use DynamoDB”) or as a feeling (“Postgres will not scale”). Translate it back into a workload before discussing products. For each data set the system will hold, answer these with numbers:
| question | what to measure or estimate | what an extreme answer rules out |
|---|---|---|
| Durability: what happens if the last second of writes is lost? A day? Everything? | the cost of loss; whether the data can be rebuilt from elsewhere | “never lose a committed write” rules out async-only replication and caches as a system of record |
| Concurrency: how many writes per second, now and in two years? Do writers contend for the same rows? | peak writes/s, growth rate, hot keys | more than one large primary can take rules out a single-node engine; heavy contention rules out optimistic schemes that retry a lot |
| Transactions: which entities must change together, atomically? | the invariants (an order total equals its lines; a balance never goes negative) | invariants across many entities rule out stores without multi-item transactions, or make sharding by a key that splits them expensive |
| Query shape: point lookups, ranges, scans and aggregates, search, graph traversal, similarity? | the top ten queries by frequency and by cost | a dominant aggregate scan points to a column store; ranked text relevance to a search engine |
| Size: rows and bytes, now and in two years | total, and the hot working set | a working set larger than one machine’s memory changes the latency of everything |
| Latency: p99 targets per query class | the user-facing budget | single-digit milliseconds rules out anything that crosses regions synchronously |
| Geography: where are writers and readers? Data residency? | regions, legal constraints | writes accepted in several regions rule out single-primary designs |
| Team: who runs it at 3 a.m.? | existing expertise, on-call size | anything nobody on the team has restored from backup |
Three questions do most of the work: the durability need, the write rate with its growth, and the dominant query shape. The rest usually confirm or veto.
The map
With a profile in hand, each engine family is a known set of trades. Every row is a chapter you have read:
| family | what it is good at | what it gives up | examples | in this course |
|---|---|---|---|---|
| relational, single primary | transactions across rows and tables, ad hoc queries, constraints | write scale beyond one machine; scans at warehouse scale | Postgres, MySQL | module one and two |
| relational, sharded | the above, per shard key, with horizontal write scale | cross-shard transactions and joins become expensive; operations multiply | Citus, Vitess | partitioning and sharding |
| distributed SQL | serializable transactions across ranges and regions, automatic rebalancing | per-transaction latency includes consensus; a different engine to learn | CockroachDB, Spanner, TiDB | distributed transactions |
| key-value | sub-millisecond point access, simple scaling | queries other than by key; often durability | Redis, DynamoDB | key-value and document stores |
| document | aggregates stored together, flexible schema | joins across documents, multi-document invariants are harder | MongoDB | same chapter |
| wide-column | very high write rates, partition-local reads, multi-datacentre | ad hoc queries, transactions, deletes (tombstones) | Cassandra, ScyllaDB, Bigtable | wide-column stores |
| columnar | scans and aggregates over billions of rows | point updates, single-row latency | ClickHouse, DuckDB, warehouses | columnar and analytics |
| search, graph, time-series, vector | relevance ranking, traversals, time-bucketed metrics, nearest neighbours | general-purpose queries and transactions | Elasticsearch, Neo4j, TimescaleDB, pgvector | specialist engines |
| cache | latency and offloading reads | it is a copy: staleness, and the database now depends on it | Redis, Memcached | caching in front |
Read the table as a list of things to give up. Every row past the first trades away some of what the relational model gives for free, and the decision is whether the workload needs what is being gained more than what is being lost.
Postgres for everything, and where it stops
There is a well-known argument that a small or medium team should run Postgres for nearly everything: queues, caches, search, documents, vectors, time series. The argument is strongest on operations: one backup system, one replication setup, one set of access controls, one engine to understand deeply, transactions across all of it. Stonebraker and Pavlo’s 2024 survey makes the historical version of the case: every data model that challenged relational databases over fifty years (key-value, document, column, graph, MapReduce) was either absorbed by SQL systems as a feature or stayed in a niche.
The counter-argument is as old. Stonebraker’s own 2005 paper, “One size fits all: an idea whose time has come and gone”, showed specialised engines (column stores, stream processors) beating general-purpose ones by an order of magnitude or more on their workloads. Both are true. The question is where your workload sits. Here is where Postgres stops, roughly, on one large primary:
| job | how Postgres does it | where it usually stops |
|---|---|---|
| job queue | SELECT ... FOR UPDATE SKIP LOCKED, or a library built on it |
low thousands of jobs/s sustained; every job is a dead tuple, so vacuum and long transactions decide throughput |
| session or cache store | UNLOGGED table, primary-key access |
tens of thousands of ops/s; Redis does hundreds of thousands with pipelining, at a fraction of the CPU |
| documents | jsonb with GIN indexes |
fine for most uses; large documents rewritten on every small change (TOAST) |
| full-text search | tsvector, GIN, websearch_to_tsquery, pg_trgm for typos |
ranking quality (no BM25 out of the box), facets and highlighting at scale, tens of millions of documents |
| vectors | pgvector with HNSW |
tens of millions of vectors on one node, and filtered searches; the specialist engines chapter has the numbers |
| time series | partitions by time, BRIN indexes, TimescaleDB | high-cardinality ingest of millions of points a second |
| analytics | parallel scans, aggregates, materialised views | interactive queries over hundreds of millions of rows; 10 to 50 times slower than a column store in the columnar chapter |
| writes | one primary | tens of thousands of write transactions per second, then sharding |
Inside those limits, adding an engine buys little and costs a lot. Past them, staying costs more than it saves. The lab measures the first three rows on the shop so you know where the lines are on your own hardware.
The costs that do not appear in a benchmark
A benchmark compares engines on one query. A decision has to price the rest.
- Operations. Each engine needs backups that someone has restored, upgrades, monitoring and alerting, capacity planning, a security review, credentials management and people on call who understand it. Count the engines your team already runs and ask who is the expert in each.
- Keeping copies consistent. A second store almost always holds data whose system of record is elsewhere: products copied into a search index, orders into a warehouse. That needs a pipeline (change data capture, an outbox), monitoring for drift, and a story for rebuilding the copy from scratch. Dual writes from the application are not that story; the cache chapter’s race is what they produce.
- The query nobody planned. Specialised stores answer the queries they were modelled for. The key-value chapter asked the shop a question nobody planned and needed a scan or a new index in each store. A relational system answers it with a new SQL statement.
- Lock-in and exit. Managed services with proprietary APIs (DynamoDB, Spanner, Cosmos DB) are cheap to start and expensive to leave. That is acceptable when it is a decision rather than an accident.
- Price. Managed pricing is per request, per GB stored, per GB transferred and per replica. Model the bill at the two-year volume, not today’s.
The procedure
- Profile each data set with the table above. Numbers, with growth.
- Default to the system of record you already run, usually Postgres, and test the profile against its limits. If it fits with a margin of two to three times the two-year projection, stop.
- Name the job that does not fit, specifically: “dashboard queries scan 600 million rows”, not “analytics”.
- Shortlist the family from the map that is built for that job, and at most two products in it.
- Price the operations, the consistency pipeline and the bill, not only the benchmark.
- Measure with your data and your queries. A vendor’s benchmark is a hypothesis.
- Write the decision record, with the exit criteria.
A decision record is a page:
Decision: Product search moves to OpenSearch. Date: 2026-11-02
Workload: 5M products, 300 searches/s at peak, 20 updates/s; p99 < 150 ms;
facets on 12 attributes; typo tolerance; ranking by relevance and sales.
Options: (1) Postgres tsvector + pg_trgm (2) OpenSearch fed by CDC (3) a hosted search API
Choice: (2), because measured p99 on (1) with facets was 900 ms at 5M rows.
Given up: search results lag writes by about 2 s; one more cluster to run.
Evidence: benchmark notebook link; cost model link.
Exit/revisit: if products stay under 1M, or if the team cannot staff on-call for it by Q2.
The exit criteria are the part teams skip and later miss. They turn “we chose X” into “we chose X while these numbers held”.
Six scenarios
Profile each, pick, and defend the pick against the strongest alternative. The lab asks you to write two of these as decision records; reference answers are at the end of the lab.
- Payments ledger. A fintech holds customer balances. 2000 transfers a second at peak, each debiting one account and crediting another, possibly on different customers. A balance must never go negative. Auditors want every change, forever.
- Clickstream analytics. 200 million page-view events a day, 40 attributes each. Product managers explore funnels and retention over 90 days in dashboards and ad hoc queries. Losing a few minutes of events in a crash is acceptable.
- Session and cart store. 30 000 reads and writes a second, values under 2 KB, every key expires after 30 minutes of inactivity. Losing the last second of carts in a crash is acceptable; losing all carts is not.
- Messaging at scale. Chat messages for 10 million channels, 50 000 writes a second, reads are ‘the latest 50 messages of a channel’ and scroll-back. Data must survive the loss of a data centre.
- Multi-region SaaS. A B2B product with customers in the EU and the US. EU customer data must stay in the EU. Each customer’s users write from their own region and expect 50 ms responses. A few global admin reports run nightly.
- Product catalogue with search. 200 000 products, 40 searches a second, stemming, typo tolerance, filters on category and price. A team of four engineers, who already run Postgres.
You will push the shop’s Postgres through three jobs that are often handed to other engines, find where each one starts to hurt, and use the numbers in two decision records. Work in labs/databases. The pgbench files go in shop/queries/, which the pgbench service sees as /shop/queries/.
1. A queue with SKIP LOCKED.
docker compose exec -T db psql -U atlas -d shop <<'SQL'
DROP TABLE IF EXISTS jobs;
CREATE TABLE jobs (id bigserial PRIMARY KEY, kind text NOT NULL, payload jsonb NOT NULL,
run_at timestamptz NOT NULL DEFAULT now());
CREATE INDEX jobs_run_at ON jobs (run_at);
INSERT INTO jobs (kind, payload) SELECT 'email', jsonb_build_object('order_id', g) FROM generate_series(1, 500000) g;
VACUUM ANALYZE jobs;
SQL
cat > shop/queries/d3-choose-queue-work.sql <<'SQL'
WITH next AS (
SELECT id FROM jobs WHERE run_at <= now() ORDER BY run_at LIMIT 1 FOR UPDATE SKIP LOCKED)
DELETE FROM jobs USING next WHERE jobs.id = next.id RETURNING jobs.id, jobs.payload;
SQL
cat > shop/queries/d3-choose-queue-add.sql <<'SQL'
\set oid random(1, 200000)
INSERT INTO jobs (kind, payload) VALUES ('email', jsonb_build_object('order_id', :oid));
SQL
for i in 1 2; do
docker compose run --rm pgbench -n -c 8 -j 4 -T 20 \
-f /shop/queries/d3-choose-queue-work.sql@3 -f /shop/queries/d3-choose-queue-add.sql@1 | grep -E '^tps|^latency average'
docker compose exec db psql -U atlas -d shop -Atc \
"SELECT count(*) AS queued, (SELECT n_dead_tup FROM pg_stat_user_tables WHERE relname = 'jobs') AS dead FROM jobs"
donetps figure: thousands to over ten thousand transactions a second on a laptop, three quarters of them dequeues, so several thousand jobs a second with eight workers and no lost or double-processed job (SKIP LOCKED hands each row to one worker). The second run is slower than the first, often by a third or more, and dead is in the hundreds of thousands: every dequeued job is a dead tuple, and each dequeue walks the index past dead entries that autovacuum has not cleaned yet. That is the shape of the limit: not the locking, which is cheap, but the garbage.2. A session store in an unlogged table, against Redis.
docker compose exec -T db psql -U atlas -d shop -c \
"CREATE UNLOGGED TABLE IF NOT EXISTS sessions (k text PRIMARY KEY, v jsonb NOT NULL, expires_at timestamptz NOT NULL)"
cat > shop/queries/d3-choose-kv-put.sql <<'SQL'
\set s random(1, 100000)
INSERT INTO sessions VALUES ('s:' || :s, '{"cart": [17, 42], "currency": "EUR"}', now() + interval '30 minutes')
ON CONFLICT (k) DO UPDATE SET v = EXCLUDED.v, expires_at = EXCLUDED.expires_at;
SQL
cat > shop/queries/d3-choose-kv-get.sql <<'SQL'
\set s random(1, 100000)
SELECT v FROM sessions WHERE k = 's:' || :s;
SQL
docker compose run --rm pgbench -n -c 8 -j 4 -T 20 \
-f /shop/queries/d3-choose-kv-put.sql@1 -f /shop/queries/d3-choose-kv-get.sql@4 | grep -E '^tps|^latency average'
docker run --rm redis:8.6.8 sh -c 'redis-server --daemonize yes >/dev/null; sleep 1;
redis-benchmark -q -t set,get -n 200000 -c 8; redis-benchmark -q -t set,get -n 1000000 -c 8 -P 16'UNLOGGED skips the WAL, which is where the speed comes from, and it is also the catch: after a crash Postgres truncates an unlogged table to empty, and standbys never see it. Redis without pipelining is in the same range as Postgres, because both are bounded by round trips; with 16 commands per round trip (-P 16) it reaches several hundred thousand a second. The gap is CPU per operation and pipelining, and it matters only past the numbers Postgres already reached.3. Search with stemming, then with typos.
docker compose exec -T db psql -U atlas -d shop <<'SQL'
CREATE INDEX products_search ON products USING gin (to_tsvector('english', name || ' ' || category));
\timing on
SELECT id, name, category
FROM products, websearch_to_tsquery('english', 'deluxe kitchen') q
WHERE to_tsvector('english', name || ' ' || category) @@ q
ORDER BY ts_rank(to_tsvector('english', name || ' ' || category), q) DESC LIMIT 5;
SELECT count(*) FROM products, websearch_to_tsquery('english', 'delux kitchn') q
WHERE to_tsvector('english', name || ' ' || category) @@ q;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX products_name_trgm ON products USING gin (name gin_trgm_ops);
SELECT name, round(similarity(name, 'delux widgit')::numeric, 2) AS sim
FROM products WHERE name % 'delux widgit' ORDER BY 2 DESC LIMIT 3;
SQLproducts_search; the index and the query both reduce ‘Deluxe’ to the lexeme delux, so plurals and suffixes match too. The misspelled query returns 0: full-text search matches lexemes, and ‘kitchn’ is not one. The trigram query finds ‘Deluxe Widget …’ names with similarity around 0.4 despite two typos. For 5000 or 200 000 products this is a search engine. What it lacks is BM25 ranking, facet counts computed with the results, highlighting and synonym management at scale; when those become requirements, the specialist engines chapter’s OpenSearch step is the comparison to run.4. The aggregate that does not fit.
docker compose exec -T db psql -U atlas -d shop <<'SQL'
\timing on
SELECT p.category, date_trunc('week', o.created_at) AS week, sum(i.qty * i.unit_price_cents) / 100 AS revenue
FROM order_items i JOIN orders o ON o.id = i.order_id JOIN products p ON p.id = i.product_id
WHERE o.created_at >= now() - interval '2 years'
GROUP BY 1, 2 ORDER BY 1, 2 LIMIT 5;
SQL5. Write two decision records.
Pick two of the six scenarios, one where you keep Postgres and one where you do not, and write a record for each in the format from the body, in d3-choose/decisions.md or wherever your team keeps them. Use the numbers you measured in steps 1 to 4 as evidence where they apply.
Reference answers for the six scenarios
- Payments ledger: Postgres, single primary, synchronous standby. The invariant (no negative balance, debit and credit together) needs multi-row transactions with strong isolation, and 2000 transfers a second is well inside one primary. Append-only entries plus a balance row updated in the same transaction,
SERIALIZABLEorSELECT ... FOR UPDATEon both accounts in id order. Revisit when writes approach a third of what the largest instance sustains; the next step is sharding by account with transfers across shards as two-phase commits, or distributed SQL. The payment ledger lesson has the design. - Clickstream: a column store (ClickHouse, or a warehouse) fed from a queue. 200 million wide rows a day and exploratory aggregates is the columnar workload exactly; losing minutes of events is acceptable, so batch ingestion is fine. Postgres would hold it with partitions but answer in minutes, not seconds.
- Session and cart store: Redis with AOF and a replica, or Postgres if the rate were ten times lower. 30 000 ops/s with TTLs fits Redis natively (
EXPIRE), andappendonly yeswitheverysecloses about a second, which the requirement allows. An unlogged Postgres table would lose everything in a crash, which the requirement forbids; a logged one pays a WAL write per update. - Messaging: a wide-column store (Cassandra or ScyllaDB) partitioned by channel and time bucket. 50 000 writes a second, reads by partition in time order, multi-datacentre replication: the Discord workload. Bucket channels by time so a busy channel does not become one huge hot partition, and plan for tombstones from deletes.
- Multi-region SaaS: one Postgres (or Citus) deployment per region, tenants placed by region, nightly reports from a warehouse fed by both. Residency and latency both say each tenant’s data lives in its region; a tenant’s writes rarely need another region. Distributed SQL with regional placement (CockroachDB
REGIONAL BY ROW, Spanner) is the alternative when tenants genuinely span regions or the team wants one logical database; it costs consensus latency on cross-region transactions. - Product catalogue: Postgres full-text search with pg_trgm. Step 3 is the evidence: 200 000 products and 40 searches a second are far inside it, and four engineers who already run Postgres should not add a search cluster and a CDC pipeline for it. Exit criteria: relevance complaints that need BM25 or learning-to-rank, faceting at a scale where counts are slow, or a catalogue over a few million.
docker compose exec db psql -U atlas -d shop -c "BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM customers; SELECT pg_sleep(90); COMMIT;". Refill the queue with the TRUNCATE, INSERT and VACUUM from step 1 (as separate statements), and repeat the step 1 loop while the sleep runs. Throughput falls to a fraction of the first run, a third or less, and drops further in the second run, while dead climbs: vacuum cannot remove any tuple that the open snapshot might still need to see, so every dequeue walks over more garbage. A forgotten transaction in any service on the same database, an analytics query on the primary, or a replica with hot_standby_feedback = on running a long report does the same. It is the main reason teams move busy queues out of Postgres, and the reason idle_in_transaction_session_timeout exists. Clean up with DROP TABLE jobs, sessions; DROP INDEX products_search, products_name_trgm; and delete the four d3-choose-*.sql files.The shop has 120 000 products on Postgres. Search is a LIKE '%term%' query that takes 300 ms and misses plurals and typos. A senior engineer proposes adding Elasticsearch, fed by a nightly export, because 'we will need it eventually'. The team is five engineers, runs Postgres on a managed service, and has no one who has operated Elasticsearch. Product count grows about 30% a year.
- PAPER What Goes Around Comes Around... And Around... Michael Stonebraker and Andrew Pavlo, 2024
Twenty years of challengers to the relational model, from MapReduce to key-value, document, graph and vector stores, and how each either became a SQL feature or stayed in its niche. The strongest written case for defaulting to a relational system. Read: SIGMOD Record 53(2); read sections 1 and 2 (each data model in turn) and the conclusions; skim section 3 on architectures.
- PAPER One Size Fits All: An Idea Whose Time Has Come and Gone Michael Stonebraker and Uğur Çetintemel, 2005
The counter-case, by one of the same authors: specialised engines for warehouses and streams beat general-purpose ones by an order of magnitude or more. Read it next to the 2024 paper and decide where your workload sits. Read: ICDE 2005; sections 1 to 3 and the conclusions.
- BOOK Designing Data-Intensive Applications, chapters 2 and 3 Martin Kleppmann, 2017
The vocabulary for comparing data models and storage engines without vendor language. Chapter 2's discussion of when the document model fits is the most useful page for the document-versus-relational question. Read: chapter 2 (data models: relational, document, graph) and the summary of chapter 3 (storage engines and column stores).
- POST Why Uber Engineering Switched from Postgres to MySQL Evan Klitzke, 2016
The incident in the Why. Read it as a workload profile: which access pattern met which engine property. Then check which of the complaints current Postgres versions have addressed, which is the habit the decision record's revisit date is for.
- POST How Discord Stores Trillions of Messages Bo Ingram, 2023
Scenario 4 in production: why Cassandra fit the message workload, what went wrong at 177 nodes (hot partitions, GC pauses, compaction), and the move to ScyllaDB on 72 nodes. A choice of family that held while the product inside it changed.
- DOC PostgreSQL 17: Full Text Search
What tsvector, tsquery, dictionaries and ranking do, and their limits, so the lab's step 3 can be extended to a real catalogue. Read the controlling and indexing sections; pair with the pg_trgm page for typos.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.