Summary#
Choosing a database is choosing the shape of every future query, the failure modes of your system, and a large part of your operating cost, often for years. The good news is that the decision is far more mechanical than the endless "SQL versus NoSQL" debates suggest. Four questions, asked in order, settle most choices:
- What are the access patterns? Exact-key lookups, rich relational queries, full-text search, graph traversal, time-range scans, large aggregations, similarity search, or whole-file reads?
- What transactions and consistency do you need? Single-item atomicity, multi-row ACID transactions, or cross-region strong consistency? Where is eventual consistency acceptable?
- What are the scale and the cost envelope? Data size, read and write throughput, growth, latency targets, and the money and people available to run it.
- What can you operate? Managed versus self-hosted, the team's expertise, and what the organisation already runs well.
For most product systems, the answer is a relational database (PostgreSQL or MySQL) as the system of record, plus a small number of specialised stores for the access patterns it serves poorly:
- a cache for hot reads;
- a search engine for full-text queries;
- an OLAP warehouse for analytics;
- object storage for blobs;
- sometimes a vector index or time-series store.
Each extra store is fed from the system of record, ideally via change data capture. Reach for a distributed NoSQL store as the primary database when the requirements clearly call for it: very high write throughput, massive scale with simple key-based access, or multi-region active-active writes.
This page gives you a decision tree, a requirement-to-database table covering ten categories, a guide to transaction and consistency needs, scale and cost thresholds, the managed options on AWS, Google Cloud and Azure, the discipline of polyglot persistence, and how the case studies in this handbook make these choices.
Why It Exists#
There are hundreds of databases, and each one's marketing claims it's fast, scalable and easy. Engineers face that market with incomplete information and strong opinions. Three failure patterns are common.
The wrong default. Teams pick a database because it's fashionable, because a previous company used it, or because "NoSQL scales". Then they discover their product needs multi-row transactions and ad-hoc reporting, or the reverse: they pick a relational database for a firehose of telemetry and spend a year fighting write amplification and vacuum. In interviews, the equivalent is choosing an exotic database to impress, which usually backfires: a graph database for a social network, a document database for strongly relational data. The choice then becomes the thing the interviewer probes, and the justification doesn't hold up.
False dichotomies. "I need relational because my data has relationships" is weak reasoning: NoSQL stores can model relationships fine if you design for the access patterns. "I need NoSQL for scale" is equally weak: relational databases, used well, scale to very large workloads with replicas, partitioning and caching. Facebook's social graph has famously been stored in sharded MySQL behind a caching layer for most of its history. The useful question isn't "SQL or NoSQL?" but "what does this database do well, and does that match this workload?" See SQL vs NoSQL: How to Choose for the comparison itself.
One database for everything, or a database for everything. Forcing full-text search, analytics and caching all onto one OLTP database overloads it and serves each workload poorly. The opposite mistake, five datastores for a product with ten engineers, multiplies operational burden, consistency problems and cost. Good design finds the small set of stores that covers the access patterns, with one clear source of truth for each piece of data.
A database choice is also one of the most expensive decisions to reverse. Migrating a live system between datastores means dual writes, backfills, verification and a cutover, often taking months (see Online Data Migrations and Schema Evolution). Discord's migration of trillions of messages from Cassandra to ScyllaDB in 2022 needed a purpose-built migrator and careful coordination. That's why the decision deserves a deliberate process, and an architecture decision record.
The rest of this page turns that intuition into a method.
How It Works#
Start from access patterns, not data shape#
An access pattern is a specific way the application reads or writes data, stated concretely: "fetch a user's 50 most recent orders", "find all restaurants within 2 km that are open now", "count clicks per ad per minute for the last 30 days", "append a GPS point every 4 seconds for each active driver". Access patterns come directly from your API endpoints: for each endpoint, ask "what query does this need?"
Databases differ mostly in which access patterns they make cheap, and that follows from how they lay out data on disk and in memory:
- B-tree-based relational databases keep rows sorted by key with secondary indexes, so they're good at point lookups, range scans and joins on indexed columns, and at transactional updates in place.
- LSM-tree stores (Cassandra, ScyllaDB, RocksDB-based systems) turn writes into sequential appends, so they absorb very high write rates. The price is extra work on reads and in background compaction (see Storage Engines: B-Trees vs LSM Trees).
- Columnar analytical stores keep each column contiguous and compressed, so scanning and aggregating a few columns across billions of rows is fast. Fetching or updating single rows is slow.
- Inverted indexes (Elasticsearch, OpenSearch) map terms to documents, so "find documents containing these words, ranked by relevance" is fast. Updates are batched and eventually visible.
- Hash-partitioned key-value stores (DynamoDB, Redis Cluster) route each key to one partition. Exact-key access is fast at any scale, but queries that aren't keyed by the partition key are expensive or impossible.
Once you've written down the top access patterns with rough frequencies, you'll find that many candidate databases are already ruled out, and the remaining choice is between a few that fit.
The four questions in order#
1. Access patterns. For each of the top three to five operations, note:
- the query shape: key lookup, range, join, search, aggregate, traversal, similarity;
- its frequency (QPS) and latency target;
- the result size.
Separate the operational path (user-facing reads and writes) from the analytical path (reports, dashboards, data science). These almost always want different stores.
2. Transactions and consistency. Which operations must be atomic across several records (moving money, booking a seat and creating an order)? Which reads must see the latest write (a balance, an inventory count at checkout)? Which can be stale (a like count, a recommendation list)? Strong multi-record transactions point toward a relational or distributed SQL database. "Eventually consistent is fine" opens up many more options.
3. Scale and cost. How much data now and in three years? Peak reads and writes per second? Does a single node (with replicas for availability and read scaling) cover it with headroom? If yes, the scale question is answered, and you should choose on the other criteria. If not, which dimension breaks first: storage, write throughput, read throughput, or geographic distribution?
4. Operations. Who will run it? Is a managed service available in your cloud? What does the team already know? An unfamiliar database adds learning, new failure modes, new backup and monitoring tooling, and on-call risk. That cost is real and often decisive.
The decision tree#
The tree comes in two parts. The first part checks whether a specialised access pattern dominates. Each question is a yes/no step, asked in order:
The second part handles the operational records that most product backends are built on:
How to read the tree:
- The first branch is about the specialised access patterns. If the workload is primarily search, analytics, time series, similarity or blobs, a specialised store usually serves it far better than a general-purpose database, but often alongside a system of record rather than instead of one.
- The operational branch starts with transactions. If the core workflow needs multi-record atomicity or flexible queries (most product backends), start relational. The thresholds in the tree are deliberately conservative planning numbers. Modern hardware with good schema design often goes well beyond them, so treat them as "time to check", not hard limits.
- Only when relational clearly doesn't fit do you move to distributed SQL (if you still need transactions at large scale or across regions) or to NoSQL (if access is key-based and you can design around its limits).
- Within NoSQL, the shape of writes and reads decides. Wide-column stores fit append-heavy, time-ordered data partitioned by an entity. Document stores fit self-contained aggregates with variable structure queried by fields. Key-value stores fit exact-key access at any scale.
The tree is a starting point, not a verdict. Two things commonly override it: an existing, well-run database in the organisation (using it is often better than adding a new one), and a managed service that removes most of the operational burden of an otherwise heavier option.
The requirement-to-database table#
| Category | Requirement signals | Strengths | Weaknesses | Typical technologies |
|---|---|---|---|---|
| Relational OLTP | Transactions across rows; joins; constraints; ad-hoc queries; most product backends | ACID, rich SQL, secondary indexes, mature tooling | One write primary per cluster unless sharded; schema changes need care at scale | PostgreSQL, MySQL, SQL Server, Oracle; Aurora, Cloud SQL, AlloyDB |
| Distributed SQL (NewSQL) | ACID at large scale; multi-region strong consistency | Horizontal scaling with SQL and transactions | Higher write latency, especially across regions; costlier; fewer experts | Spanner, CockroachDB, YugabyteDB, TiDB |
| Key-value | Exact-key lookups at huge scale; sessions; carts; feature flags | Predictable single-digit-ms latency at any scale; simple | No ad-hoc queries; access patterns fixed up front | DynamoDB; Redis and Memcached for in-memory |
| Document | Self-contained aggregates with variable structure; queries by fields within documents | Flexible schema; nested data read in one fetch | Cross-document joins and transactions are weaker or costlier; denormalised data drifts | MongoDB, Firestore, Couchbase |
| Wide-column | Very high write rates; time-ordered data per entity; multi-region active-active | Linear write scaling; tunable consistency; no single primary | Query-driven modelling; no joins; limited secondary indexes; tombstone and compaction pitfalls | Cassandra, ScyllaDB, Bigtable, HBase |
| Search | Full-text search; relevance ranking; faceted filtering; fuzzy matching; log search | Inverted indexes, analysers, scoring, aggregations | Not a system of record; near-real-time visibility; heavy to operate | Elasticsearch, OpenSearch, Solr; Postgres full-text at small scale |
| Graph | Deep, variable-length traversals central to the product (fraud rings, knowledge graphs) | Index-free adjacency; expressive traversal queries | Hard to shard; niche skills; most "graph" products work fine on SQL | Neo4j, Amazon Neptune, JanusGraph, TigerGraph |
| Time-series | Metrics and sensor readings keyed by time and labels; downsampling; retention | Compression of numeric series; time-window queries; rollups | High-cardinality labels hurt; not for general queries | Prometheus, InfluxDB, TimescaleDB, VictoriaMetrics |
| Analytics (OLAP) | Aggregations over billions of rows; dashboards; ad-hoc analysis; many dimensions | Columnar compression; massively parallel scans | Slow single-row writes and updates; not for user-facing OLTP | BigQuery, Snowflake, Redshift, ClickHouse, Druid, Pinot |
| Vector | Similarity search over embeddings: semantic search, RAG, recommendations | Approximate nearest neighbour indexes (HNSW, IVF) | Recall versus latency tuning; filtering is tricky; memory-hungry | pgvector, OpenSearch k-NN, Pinecone, Milvus, Qdrant, Weaviate |
| Blob / object | Images, video, documents, backups, data-lake files | Practically unlimited scale; very durable; cheap per GB; CDN-friendly | High per-request latency; no queries beyond prefix listing; whole-object writes | Amazon S3, Google Cloud Storage, Azure Blob Storage |
The categories in more detail follow.
Relational OLTP: the default
Relational databases store data in tables with fixed schemas and enforce relationships with foreign keys and constraints. They provide ACID transactions (see ACID Transactions and Isolation Levels), arbitrary secondary indexes, and a declarative query language that lets you ask questions you didn't anticipate when designing the schema.
Most product problems map naturally onto this model. Users, posts, comments and likes; customers, products, orders and payments; events, venues, seats and tickets. Each has clear entities and relationships, and integrity rules ("a ticket belongs to exactly one booking") that the database can enforce. When the requirements include no double-charging, no overselling, no lost updates, relational transactions are the most direct tool.
The usual objection, that relational databases don't scale, is mostly outdated. A single modern PostgreSQL or MySQL primary on a large instance handles tens of thousands of transactions per second on well-indexed workloads and stores multiple terabytes. Read replicas multiply read capacity; caching removes most repeat reads; partitioning and sharding (manual, or via Vitess for MySQL or Citus for PostgreSQL) take writes and storage further. Many of the largest internet companies run core data on sharded relational databases.
Watch for:
- Multi-table joins on hot paths at scale. These can become performance traps. Denormalised read models, caches or precomputed results take the pressure off.
- Schema migrations on very large tables, which need online tooling.
- Connection limits. Use a connection pooler such as PgBouncer or RDS Proxy.
In interviews, PostgreSQL is the safest default unless the requirements clearly signal otherwise. It's widely known, feature-rich (JSONB, full-text search, PostGIS for geospatial, pgvector), and easy to defend. See Relational Databases and SQL and PostgreSQL in Practice.
Key-value stores
A key-value store maps a key to an opaque value. Lookups by exact key are extremely fast and scale nearly without limit, because every request routes to one partition. Query capabilities beyond that are limited or absent.
Two quite different families share the name:
- In-memory key-value stores (Redis, Memcached, Valkey) with sub-millisecond latency, used mainly as caches, session stores, rate-limit counters, leaderboards (Redis sorted sets) and ephemeral state. Redis offers persistence options, but it's normally not the system of record for data you can't lose. See Redis in Practice.
- Durable, distributed key-value stores such as DynamoDB, with single-digit-millisecond latency at essentially any scale, used as a primary database. DynamoDB adds sort keys (making it really a key plus sorted range), secondary indexes, conditional writes and transactions, so it's a capable primary store when access patterns are known up front. See Amazon DynamoDB in Practice.
In practice, key-value and relational often work together: the relational database is the source of truth, and a key-value cache fronts the hottest reads. Data modelling in a key-value store is flat and heavily denormalised: you duplicate data under several keys to serve several access patterns, which makes reads cheap but updates harder to keep consistent.
Document databases
Document databases store JSON-like documents with flexible schemas, and can index and query fields inside them. Modelling shifts from normalising across tables to embedding related data in one document. A user document might contain their addresses and preferences, so a single read returns everything a screen needs.
Choose a document database when:
- Records vary in structure. Product catalogues with category-specific attributes are the classic case; so are user profiles where some users have extensive histories and others almost none.
- The application reads and writes whole aggregates.
- The schema is evolving quickly.
Be cautious when data is highly relational or when many documents must change atomically. MongoDB has supported multi-document ACID transactions since version 4.0 (2018), but designs that need them constantly are often better served by a relational database. Note also that interview problems are deliberately scoped, so "rapidly evolving schemas" rarely applies; and PostgreSQL's JSONB columns provide document-style flexibility inside a relational database, which covers many "we need flexible fields" cases.
Wide-column stores
Wide-column stores organise data by a partition key (which node holds the data) and clustering columns (how rows are sorted within the partition). A row keyed by (user_id, timestamp) puts all of a user's events together on one replica set, sorted by time. A write is an append to that partition, and "this user's latest 100 events" is a contiguous read.
They shine for enormous write volumes (telemetry, messaging, activity logs, IoT), time-ordered per-entity data, and multi-region active-active deployments where any replica accepts writes. Cassandra and ScyllaDB are leaderless, with tunable consistency per query (see Quorums and Leaderless Replication); Bigtable and HBase use range-partitioned tablets.
Modelling is query-first: design one table per access pattern, duplicating data as needed, because there are no joins and secondary indexes are limited. Partitions must stay bounded in size, so a busy chat channel might be bucketed by time window. Deletes create tombstones that slow reads until compaction removes them. Discord stored trillions of messages this way, first on Cassandra and later on ScyllaDB, partitioned by channel and time bucket. See Apache Cassandra in Practice.
Search engines
A LIKE '%term%' query scans every row and can't rank results by relevance. Search engines build an inverted index, a map from each term to the documents containing it. Analysers do the preparation:
- tokenisation splits text into terms;
- lowercasing and stemming make "running" and "runs" both match "run";
- synonyms and edit-distance fuzzy matching catch variants and misspellings.
Scoring functions such as BM25 then rank the matching documents. Search engines also provide faceted aggregations ("filter by brand, price band, rating") and, increasingly, vector search for hybrid keyword-plus-semantic retrieval.
Elasticsearch and OpenSearch are the common choices; they shard indexes across nodes and replicate shards for availability. Treat the search index as a derived store: the system of record lives in a database, and changes flow to the index via change data capture or an indexing pipeline. Search updates become visible after a refresh interval (about one second by default), and the cluster can always be rebuilt from the source. For modest needs (thousands to a few million documents, simple ranking), PostgreSQL's full-text search with GIN indexes avoids a whole extra system. See Elasticsearch and Search Systems.
Graph databases
Graph databases store nodes and edges with properties, and are optimised for traversing relationships: "friends of friends who like jazz and live in Berlin", "shortest path between two accounts", "all entities within four hops of this fraudulent card".
They're the right choice when deep, variable-depth traversal is the core workload: fraud-ring detection, knowledge graphs, network topology, some recommendation and identity-resolution systems. In an interview they're almost always the wrong choice. Most "social graph" problems need only one or two hops ("who do I follow", "who follows me"), which an indexed edge table in a relational or key-value store answers efficiently. Large social networks have historically modelled their core graphs on sharded relational storage with caching (Facebook's TAO sits on MySQL). Graph databases also tend to be harder to shard, because traversals cross partitions. See Graph Databases for when they genuinely pay off.
Time-series databases
Metrics, sensor readings and financial ticks share a shape: a series identified by a name and labels, a timestamp, and a numeric value, written in time order and read by time range. Time-series databases exploit this:
- Compression: delta-of-delta timestamps and XOR-encoded values, as in Facebook's Gorilla paper (Pelkonen et al., VLDB 2015), shrink each point to a couple of bytes.
- Downsampling and retention policies keep fine-grained data briefly and rollups for longer.
- Window functions for rates and percentiles over time.
Prometheus dominates infrastructure monitoring; InfluxDB, TimescaleDB (PostgreSQL-based) and VictoriaMetrics are common alternatives. Their weak spot is high cardinality: millions of distinct label combinations (a user ID as a label, for instance) explode the index. For high-cardinality, multi-dimensional event analysis (per-ad, per-device, per-country click analytics), an OLAP store is usually the better fit. See Time-Series Databases.
Analytical databases (OLAP)
OLTP databases are designed for many small reads and writes. Analytical queries, such as "sum revenue by country by week over three years", scan huge numbers of rows but only a few columns. Columnar OLAP stores keep each column together, compress it heavily (similar values compress well) and scan it in parallel across many nodes, making those aggregations orders of magnitude faster than in a row store. The cost is slow single-row writes and updates, so data usually arrives in batches or micro-batches.
Warehouses (BigQuery, Snowflake, Redshift) suit business analytics and ad-hoc SQL. Real-time OLAP engines (ClickHouse, Apache Druid, Apache Pinot) suit user-facing analytics with sub-second queries on fresh data, such as an advertiser dashboard.
A common pattern for event analytics:
- Write raw events to a write-optimised store or log.
- Aggregate them in batch (Spark) or in a stream (Flink).
- Load the pre-aggregated results into an OLAP database for queries.
With 10,000 clicks per second and 5-minute batches, each batch is 3 million events; at about 100 bytes each, that's only around 300 MB, small enough for one machine. Distributed processing frameworks earn their keep as volumes grow. See Data Pipelines, Warehouses and Lakes.
Vector databases
Embedding models turn text, images or users into vectors of hundreds to thousands of numbers, where geometric closeness means semantic similarity. Finding the nearest vectors exactly means comparing against every vector, which is too slow at scale. Approximate nearest neighbour (ANN) indexes such as HNSW graphs and IVF clustering, often combined with product quantisation, trade a little recall for orders-of-magnitude speed.
Start simple. If you already run PostgreSQL, pgvector (with HNSW or IVF indexes) handles millions of vectors and lets you combine similarity with ordinary filters and joins in one query: "similar products that are in stock in the user's region". Other options extend stores you may already run:
- Elasticsearch/OpenSearch k-NN adds vectors to an existing search cluster and gives you strong hybrid keyword-plus-vector search.
- Redis vector search suits low-latency, smaller indexes.
- S3 Vectors is a newer AWS offering for storing and querying vectors directly in S3, for cost-sensitive cases.
Purpose-built vector databases make sense at very large scale (a reasonable rule of thumb is beyond about 100 million vectors) or when retrieval is the core product:
- Pinecone is fully managed and serverless: easiest to operate, but less control and higher cost.
- Milvus is built for billions of vectors, at the cost of running a multi-component distributed system.
- Qdrant is notable for its filtering.
- Weaviate is notable for its hybrid search.
- Chroma is popular for prototyping retrieval-augmented generation (RAG).
See Vector Databases and Similarity Search.
Blob and object storage
Large binary objects (images, video, audio, documents, backups, data-lake files) don't belong in a database. They bloat it, slow backups and replication, and cost much more per GB. Object storage (S3, Google Cloud Storage, Azure Blob Storage) stores them durably, using replication and erasure coding, at practically unlimited scale and low cost. S3 Standard, for example, lists about $0.023 per GB-month for the first 50 TB in its main US regions, typically an order of magnitude cheaper per GB than storing the same bytes in a managed operational database.
The standard design keeps metadata in a database (owner, name, size, status, object key) and bytes in object storage:
- Clients upload directly using presigned URLs, bypassing your servers.
- Large files use multipart (chunked) uploads, so transfers can be resumed and parallelised.
- Downloads go through a CDN in front of the bucket.
- Upload-complete events (bucket notifications) update the metadata row.
Don't use object storage as your primary database. It has high per-request latency and no query capability beyond listing by prefix. See Object Storage and Blob Storage and Pattern: Handling Large Files and Blobs.
How far can one PostgreSQL go?
Before adding a specialised store, check whether an extension or feature of the database you already run covers the need at your scale:
| Need | Inside PostgreSQL | Usually fine up to | Move to a specialised store when |
|---|---|---|---|
| Flexible fields | JSONB columns with GIN indexes | Most product use | Documents dominate and joins are rare |
| Full-text search | tsvector with GIN, pg_trgm for fuzzy matching | Millions of documents, simple ranking | Relevance tuning, facets, multilingual analysis or large scale are central |
| Geospatial | PostGIS | Very large datasets | Rarely; PostGIS is a leading geospatial engine |
| Vectors | pgvector (HNSW, IVF) | Millions to tens of millions of vectors | Beyond about 100M vectors, or very high query rates |
| Time series | Partitioned tables, TimescaleDB | Moderate ingest rates | Very high ingest or high-cardinality metrics at scale |
| Queue | SELECT ... FOR UPDATE SKIP LOCKED | Thousands of jobs per second | High throughput, fan-out or replay needs (use Kafka or SQS) |
| Cache | Shared buffers plus materialised views | Moderate read rates | Sub-millisecond, very high QPS reads (use Redis) |
Every system you don't add is one less thing to secure, monitor, back up, upgrade and wake up for.
Transaction and consistency needs#
"Do we need transactions?" is too coarse a question. Break it into what must be atomic and what must be fresh, operation by operation.
Levels of atomicity, from weakest to strongest:
| Level | Example need | Who provides it |
|---|---|---|
| Single-item atomic write | Update one user profile; increment one counter | Virtually every database, including Redis, DynamoDB and Cassandra (per partition) |
| Conditional single-item write (compare-and-set) | "Reserve this seat only if it's still available"; optimistic locking with a version | DynamoDB condition expressions, Cassandra lightweight transactions (Paxos-based; slower), Redis WATCH/Lua, SQL UPDATE ... WHERE version = ? |
| Multi-item, single-partition atomic | Write an order and its line items together under one customer key | Cassandra batches within a partition, DynamoDB items sharing a partition key (via transactions), document databases by embedding |
| Multi-item ACID across partitions or tables | Debit one account, credit another; create booking, payment and ledger rows | Relational databases; distributed SQL; DynamoDB TransactWriteItems (up to 100 items); MongoDB multi-document transactions |
| Cross-system atomicity | Update the database and publish an event and call a payment provider | No database alone: use the outbox pattern, sagas and idempotency (see Distributed Transactions: 2PC, Sagas and Outbox) |
Most systems need the strong levels for only a few operations: payments, inventory, bookings, balances, uniqueness (usernames, seat assignments). If those operations can be designed to touch one partition (for example, keeping an account's balance and its ledger entries under the same key), a NoSQL store with conditional writes may be enough. If they inherently span many entities with complex invariants, a relational database makes correctness much easier to achieve and to prove.
Isolation matters too. "ACID" doesn't mean every transaction behaves as if it ran alone. PostgreSQL defaults to Read Committed and MySQL InnoDB to Repeatable Read; both allow some anomalies (lost updates, write skew) unless you use SELECT ... FOR UPDATE, stricter isolation levels, or constraints. CockroachDB defaults to Serializable. Spanner offers external consistency, a property stronger than serializability that respects real-time order across the globe, using its TrueTime clocks. Know which isolation level your design relies on, and say so.
Freshness (read consistency). Separately from atomicity, decide which reads need the latest write:
- Strongly consistent reads. The balance shown before a withdrawal, the seat map at the moment of purchase, a permission check after revocation. Serve them from the primary or leader, or use quorum reads or strongly consistent read options (DynamoDB's
ConsistentRead, CassandraQUORUMreads withQUORUMwrites). - Read-your-writes. A user's own profile edits should appear immediately to them. Route their reads to the primary for a short window after writing, or carry a version token.
- Eventually consistent reads. Feeds, counts, search results, recommendations, analytics. Serve them from replicas, caches and derived stores.
See Consistency Models for the full spectrum and CAP Theorem and PACELC for the trade-off during partitions and in normal operation.
Multi-region consistency raises the stakes. Synchronous replication across regions adds round-trip latency to every write: tens of milliseconds within a continent, 100 ms or more between continents. Options:
- Single-primary with asynchronous cross-region replicas (the common default). Fast writes, but a failover may lose the last seconds of writes.
- Multi-region strongly consistent databases (Spanner, CockroachDB, Aurora DSQL, DynamoDB global tables in strong-consistency mode where available). No data loss on region failure, at the price of higher write latency and cost.
- Multi-primary with conflict resolution (Cassandra, DynamoDB global tables in their default last-writer-wins mode, CRDTs). Writes are local and fast, but concurrent writes conflict and the application must tolerate the resolution.
See Multi-Region and Global Data.
Durability and auditability. Financial and regulated systems often require that no committed transaction is ever lost and that every change is traceable. That points toward:
- synchronous replication within a region (a commit is acknowledged only once it's on at least two machines);
- point-in-time recovery backups;
- append-only ledgers: rows are never updated in place; corrections are new entries;
- immutable audit logs, often streamed via CDC to separate storage.
A double-entry ledger in a relational database, with its event stream copied to Kafka and object storage, is a common foundation for payment systems.
Scale and cost#
First, ask whether scale is even a factor. Do the arithmetic before reaching for a distributed database.
10M users × 5 KB of profile and settings = 50 GB. 20M orders per year × 2 KB = 40 GB per year.
Both fit comfortably on one relational primary for many years. At 1,000 peak writes per second, a single primary has plenty of headroom. In that range the scale question is answered, and the choice should rest on transactions, queries and operations.
Scale starts to dominate the decision when one of these is true:
- Write throughput exceeds what one primary sustains: often somewhere in the tens of thousands of simple writes per second, depending on row size, indexes and hardware. Options are sharding the relational database, or a horizontally scalable store (DynamoDB, Cassandra, distributed SQL).
- Data size grows to many terabytes, where backups, restores, index rebuilds and schema changes on one node become slow and risky. Partition, archive cold data, or move it to cheaper tiers (see Data Lifecycle, Tiering and Retention).
- Read throughput exceeds what replicas plus a cache can absorb. That's rare, because caches go a long way (see Pattern: Scaling Reads).
- Geographic distribution: users on several continents need low-latency writes, or data must stay in specific regions.
- Extreme skew: hot keys, such as a celebrity, a flash-sale item or a viral post, concentrate load on one partition whatever the database (see Pattern: Scaling Writes).
Cost has several components. Compare total cost, not just the price list.
| Cost component | What drives it | Watch for |
|---|---|---|
| Compute | Instance sizes and counts, or request units in serverless pricing | Over-provisioned primaries; idle replicas; read and write capacity priced separately |
| Storage | GB-month, and the multiplier from replication (often 3×) and indexes | Indexes that are as large as the data; never-deleted history |
| I/O and requests | Per-request or per-I/O charges in some managed services | Chatty access patterns; scans billed per byte processed in some warehouses |
| Data transfer | Cross-zone replication traffic, cross-region replication, internet egress | Multi-AZ chatter and egress to analytics tools in other clouds |
| Backups | Snapshot and PITR retention | Long retention on large datasets |
| Licences | Commercial databases priced per core | Licence costs that exceed infrastructure costs |
| People | Engineering time to operate, tune, upgrade and be on call | A self-hosted cluster that needs a dedicated team |
Pricing models shape the choice.
- Provisioned (a fixed instance size, or provisioned capacity units) is cheapest for steady load.
- On-demand or serverless (pay per request or per second of capacity) is best for spiky or unpredictable load and for small workloads, but can cost several times more at sustained high utilisation.
- Reserved or committed-use discounts cut steady-state costs significantly in exchange for a one- or three-year commitment.
A common progression is to start on demand while load is uncertain, then switch to provisioned capacity with reservations once the baseline is known.
A worked comparison. Suppose 5 TB of data and 2,000 requests per second, mostly key-based reads:
- A managed relational cluster (primary plus a replica on large instances) has a fixed monthly cost dominated by instance hours and provisioned storage. It also gives you arbitrary queries for free.
- A serverless key-value store with on-demand pricing costs per request. At 2,000 requests per second, that's over 5 billion requests a month, which can cost more than the fixed cluster at steady load. Switching to provisioned capacity usually brings it down substantially. Storage per GB is typically priced well above object storage.
- Moving cold data (say 4 of the 5 TB is rarely read history) to object storage in a columnar format like Parquet, queried with Athena or BigQuery external tables, can cut the storage bill for that portion by roughly an order of magnitude.
The exact numbers depend on region, discounts and current price lists. The method is what matters: model compute, storage, requests and transfer separately at today's load and at 10×, and include the people cost of operating each option.
Operational cost often dominates. A self-hosted Cassandra cluster may be cheaper per node-hour than DynamoDB. But someone must handle repairs, compaction tuning, upgrades, capacity planning and 3 a.m. pages. For small teams, a managed service is usually cheaper in total even at a higher list price. At large scale with a strong platform team, self-hosting (or a vendor-supported distribution) can win. Discord's move from Cassandra to ScyllaDB, which cut the cluster from 177 nodes to 72 while improving tail latency, is an example where operating cost and latency drove a database change at large scale.
Managed options per cloud#
Each major cloud offers a managed service in almost every category. Managed services handle provisioning, patching, backups, replication and failover, which removes much of the operational cost. In exchange you get less control, some feature lag, and a degree of lock-in, especially for proprietary APIs.
| Category | AWS | Google Cloud | Azure |
|---|---|---|---|
| Relational OLTP | RDS (PostgreSQL, MySQL, MariaDB, SQL Server, Oracle); Aurora (PostgreSQL- and MySQL-compatible) | Cloud SQL (PostgreSQL, MySQL, SQL Server); AlloyDB for PostgreSQL | Azure SQL Database; Azure Database for PostgreSQL; Azure Database for MySQL |
| Distributed SQL | Aurora DSQL | Spanner | Azure Cosmos DB for PostgreSQL (Citus) |
| Key-value | DynamoDB | Firestore (document/key access); Bigtable for wide-row key access | Cosmos DB (NoSQL and Table APIs) |
| In-memory cache | ElastiCache (Valkey, Redis OSS, Memcached); MemoryDB | Memorystore (Valkey, Redis, Memcached) | Azure Managed Redis; Azure Cache for Redis |
| Document | DocumentDB (MongoDB-compatible) | Firestore | Cosmos DB for MongoDB |
| Wide-column | Amazon Keyspaces (Cassandra-compatible) | Bigtable | Cosmos DB for Apache Cassandra; Azure Managed Instance for Apache Cassandra |
| Search | OpenSearch Service | Vertex AI Search; Elastic Cloud via Marketplace | Azure AI Search |
| Graph | Neptune | Spanner Graph | Cosmos DB for Apache Gremlin |
| Time-series | Timestream | Bigtable; Managed Service for Prometheus | Azure Data Explorer; Azure Monitor managed Prometheus |
| Analytics (OLAP) | Redshift; Athena over S3 | BigQuery | Microsoft Fabric; Azure Synapse Analytics |
| Vector | pgvector on RDS/Aurora; OpenSearch k-NN; S3 Vectors | Vertex AI Vector Search; pgvector on AlloyDB and Cloud SQL | Azure AI Search vectors; Cosmos DB vector search |
| Object storage | S3 | Cloud Storage | Blob Storage |
Product names and features change frequently, so check current documentation before committing. A few points help when comparing:
- Compatible is not identical. "MongoDB-compatible" or "Cassandra-compatible" services implement the wire protocol and most of the API, but may differ in features, consistency behaviour or performance characteristics. Test the features you actually rely on.
- Proprietary APIs lock you in more. DynamoDB, Firestore, Cosmos DB's native API and Spanner are excellent managed services, but moving off them means rewriting data access code. Open-protocol services (PostgreSQL, MySQL, Redis/Valkey, Kafka-compatible) are easier to move.
- Cloud-neutral vendors offer managed versions of open-source or proprietary databases on several clouds: MongoDB Atlas, Elastic Cloud, Redis Cloud, Snowflake, Databricks, ClickHouse Cloud, CockroachDB Cloud, Neon and Supabase (PostgreSQL), PlanetScale (MySQL/Vitess and PostgreSQL), Pinecone and others. They fit when you want the same database across clouds, or features the cloud's own service lacks.
- Serverless variants (Aurora Serverless, DynamoDB on-demand, Firestore, BigQuery on-demand, Neon) scale capacity automatically, which suits spiky workloads and development environments. Watch cold-start latency and per-request costs at sustained load.
See Cloud Architecture Essentials for the broader service map.
Polyglot persistence#
Polyglot persistence means using several kinds of datastore within one system, each for the access pattern it serves best. The term was popularised by Martin Fowler and Pramod Sadalage, notably in NoSQL Distilled (2012). Almost every system at scale is polyglot. A typical e-commerce platform:
- PostgreSQL holds orders, customers and payments (transactions and integrity).
- Redis caches product pages and holds carts and sessions (low latency).
- Elasticsearch powers product search (relevance, facets).
- S3 stores product images (cheap bytes behind a CDN).
- A warehouse such as BigQuery or Snowflake holds analytics (aggregations over history).
- A vector index supports "similar products" (semantic similarity).
Done well, polyglot persistence gives each workload the right engine. Done badly, it creates a web of inconsistent copies. The rules that keep it healthy:
- One source of truth per piece of data. Every entity has exactly one authoritative store. Every other copy is derived, and the system can tolerate it being stale or rebuild it.
- Propagate changes from the source, not by dual writes. If the application writes to PostgreSQL and then to Elasticsearch, a crash between the two leaves them inconsistent forever. Instead, capture changes from the source's log (CDC with Debezium, DynamoDB Streams and so on) or write an outbox row in the same transaction, then let consumers update derived stores. See Change Data Capture and the Outbox Pattern.
- Make derived stores rebuildable. Keep the change stream or a snapshot from which any derived store can be rebuilt from scratch. Then a corrupted search index or a schema change in the warehouse is a reindex, not a crisis.
- Design for the staleness. Users may search for a product a second after it's created and not find it. Decide what's acceptable, show it in the UI if needed, and serve read-your-writes from the source where it matters.
- Count the operational cost. Each store needs security, backups, monitoring, upgrades, capacity planning and expertise. Add one only when the access pattern genuinely can't be served well by what you already run. For a small team, "PostgreSQL plus Redis plus S3" covers a remarkable range of products.
Martin Kleppmann's Designing Data-Intensive Applications (2017) frames this architecture as "unbundling the database": the log of changes is the central abstraction, and indexes, caches and materialised views become derived data, maintained by stream processors rather than inside one monolithic database engine.
Examples from the case studies#
The case studies in this handbook make these decisions repeatedly. Seeing them side by side shows the patterns.
| Case study | System of record | Other stores | Why |
|---|---|---|---|
| Design a URL Shortener (Bitly) | Key-value or relational: short code → long URL | Redis cache; CDN or edge redirects | Pure key lookup with a very high read-to-write ratio; data small enough that the choice hinges on operations rather than scale |
| Design a News Feed (Facebook / Twitter) | Relational or wide-column for posts and follow edges | Redis for precomputed feeds; object storage for media | Feed reads must be fast; fan-out-on-write fills per-user feed caches |
| Design a Chat System (WhatsApp) | Wide-column (Cassandra or ScyllaDB) partitioned by conversation and time bucket | Redis for presence and connection routing | Huge append-heavy write volume; reads are "latest messages in this chat" |
| Design a Ticket Booking System (Ticketmaster) | Relational (PostgreSQL) for events, seats, bookings | Redis for seat holds with TTL; Elasticsearch for event search; CDN for event pages | No double-booking requires transactions or conditional writes; search is a separate access pattern |
| Design a Payment System | Relational with an append-only double-entry ledger | Kafka plus object storage for an immutable audit trail; warehouse for reconciliation | Durability, auditability and multi-record atomicity are the core requirements |
| Design a Ride-Hailing App (Uber) | Relational or distributed SQL for rides and payments | Redis with geospatial indexes for live driver locations | Driver locations change every few seconds and are only needed in memory; rides need transactional state |
| Design a Proximity Service (Yelp) | Relational for businesses | Geospatial index (PostGIS, geohash in Redis, or Elasticsearch geo queries); search engine | Read-heavy "near me" queries combined with text filters |
| Design File Storage and Sync (Dropbox / Google Drive) | Relational for file metadata, versions and sharing | Object storage for chunks; CDN | Bytes and metadata separated; metadata needs consistency for sync |
| Design a Video Streaming Platform (YouTube / Netflix) | Relational or wide-column for video metadata | Object storage plus CDN for video segments; analytics warehouse for views | Petabytes of immutable media; metadata is small |
| Design a Metrics Monitoring and Alerting System | Time-series database | Object storage for long-term blocks; relational for alert rules | Compressed time-ordered numeric data, range queries, retention |
| Design an Ad Click Aggregator | Kafka as the durable event log | Stream processor state; OLAP store (ClickHouse, Druid or Pinot) for aggregates; object storage for raw events | High-cardinality, multi-dimensional aggregation queries over fresh data |
| Design Post Search (Facebook Search) | The posts database | Inverted index (Elasticsearch or a custom index) | Full-text relevance search is a different access pattern from post storage |
| Design Top-K / Trending (Top Videos, Leaderboards) | Event stream | Redis sorted sets or stream-processor state; OLAP store for long windows | Counting and ranking over sliding windows |
| Design a Collaborative Editor (Google Docs) | Document snapshots plus an operations log | In-memory session state on the document's server; object storage for snapshots | Ordered operation logs per document; low-latency sync |
| Design an LLM Chat Service (ChatGPT) | Document or relational store for conversations | Vector index for retrieval; object storage for uploaded files; Redis for rate limits | Conversations are self-contained aggregates; retrieval needs similarity search |
Patterns worth noticing:
- Relational is the system of record far more often than not, especially wherever money, inventory, bookings or permissions are involved.
- Wide-column stores appear where writes are append-heavy and massive: messages, events, time-ordered activity.
- Redis appears in almost every design, but as a cache or for ephemeral state (holds, presence, locations, counters, rate limits), not as the record of truth.
- Object storage plus a CDN is universal for media, with metadata in a database.
- Search, analytics, time series and vectors are almost always derived stores fed by a log, not where data originates.
- The same problem can have more than one good answer. A URL shortener on DynamoDB and one on PostgreSQL can both be right. What makes either answer good is the reasoning tied to requirements.
When to Use It#
Use this decision process whenever you're introducing a new datastore, designing the data layer of a new system, or reconsidering an existing choice because requirements or scale have changed. Concrete triggers:
- A new service needs persistent data, and someone has proposed a specific database. Check the proposal against the access patterns.
- An access pattern is being served badly: full-text search via
LIKE, analytics queries slowing the OLTP primary, a hot table at 80% CPU. - Load forecasts cross the thresholds above: writes in the tens of thousands per second, data in the many terabytes, users on several continents.
- A new compliance or residency requirement affects where data can live.
- Operating cost or on-call burden for a current database is disproportionate.
- In interviews, whenever you place a database box on the diagram. Say what kind and why in one or two sentences tied to access patterns and consistency.
Pick something else instead when:
- The organisation already runs a database that fits. Using the well-operated PostgreSQL cluster and its tooling usually beats a theoretically better fit that nobody knows how to run. Note the fit gap and move on.
- The decision is easily reversible. A cache technology or a prototype datastore can be swapped cheaply; don't run a full evaluation.
- The platform team offers a paved road. Use the supported options unless your requirements truly fall outside them.
When NOT to Use It#
- Don't add a datastore for a hypothetical future. "We might need graph queries someday" doesn't justify running Neo4j today. Model edges in your existing database and revisit when traversal becomes central.
- Don't choose by benchmark headlines. Vendor benchmarks are run on favourable workloads. Your access patterns, data sizes and consistency settings decide real performance; test with them.
- Don't let the decision stall the design. In an interview especially, pick a sensible database in under a minute, justify it briefly, and spend your time on the parts that matter more. "PostgreSQL, because we need transactions for bookings and the data fits one primary" is enough.
- Don't make SQL versus NoSQL the topic. Unless you're asked, avoid a generic comparison. Talk about the specific database you chose and how its features solve this problem.
How to Implement It#
A practical procedure for making and recording a database choice:
- Inventory the access patterns. For each API endpoint and background job, write the query, its frequency, latency target, consistency need and result size. Separate operational from analytical patterns.
- Mark the transactional boundaries. Which writes must be atomic together? Which reads must be fresh? Can the atomic sets share a partition key?
- Estimate data size and throughput now and at 10×. Check whether one relational primary with replicas covers it.
- Shortlist two or three candidates using the decision tree and table. Include the database you already operate, if any.
- Model the data in each candidate for the top access patterns: tables and indexes, or partition and sort keys. Weak fits become obvious as soon as you try to serve every query.
- Spike the riskiest pattern. Load realistic data volumes and measure p99 latency and throughput for the hardest query. Check behaviour under failover.
- Compare total cost (compute, storage, requests, transfer, backups, licences, people) at today's load and at 10×.
- Decide and record an ADR, with the context, alternatives, consequences and triggers to revisit (see The Design Process: From Problem to Architecture).
- Plan derived stores (cache, search, analytics) and how they're fed: CDC or outbox, never dual writes.
- Plan operations from day one: backups and tested restores, monitoring of the database's key metrics, capacity alerts, schema migration tooling, and the upgrade path.
An access-pattern inventory makes steps 1–3 concrete. It's short enough to put in a design doc:
# access-patterns.yaml for the bookings service
entities: [Event, Venue, Seat, Booking, Payment]
patterns:
- name: view_event_seat_map
query: "seats by event_id with status"
qps_peak: 20000 # on-sale spikes; cacheable for ~1s
latency_p99_ms: 150
consistency: eventual # stale by 1s is OK for display
- name: hold_seats
query: "conditional update seats set held where status=available"
qps_peak: 3000
latency_p99_ms: 200
consistency: strong # no double-hold; multi-row atomic
atomic_with: [seat rows for one event]
- name: confirm_booking
query: "insert booking + payment, update seats sold"
qps_peak: 800
consistency: strong # multi-table ACID
- name: search_events
query: "full-text by name/artist, filter by city/date"
qps_peak: 5000
consistency: eventual # index lag of seconds OK
- name: sales_reports
query: "aggregate bookings by event/day/channel"
freshness: 15min
path: analytical
data_size: {now_gb: 120, in_3y_gb: 900}
decision_hint: >
Strong multi-row atomicity + under 1 TB + 3k peak writes/s
-> PostgreSQL primary; search via Elasticsearch from CDC;
seat-map reads from cache; reports in the warehouse.| Technology | Fits when |
|---|---|
| PostgreSQL | The default system of record: transactions, rich queries, extensions (PostGIS, pgvector, full-text) |
| MySQL with Vitess | You need horizontal sharding of a MySQL-based system, with a proven path at very large scale |
| Spanner, CockroachDB, YugabyteDB | ACID transactions beyond one primary's capacity, or multi-region strong consistency |
| DynamoDB | Key-based access patterns known up front, serverless operations, very high and spiky scale on AWS |
| Cassandra, ScyllaDB | Massive append-heavy writes, time-ordered per-entity data, multi-region active-active, with a team able to operate it |
| MongoDB | Self-contained documents with varied structure, queried by fields |
| Redis, Valkey | Caching, sessions, counters, rate limits, leaderboards, ephemeral state |
| Elasticsearch, OpenSearch | Full-text search, relevance, facets, log search, hybrid vector search |
| ClickHouse, Druid, Pinot | Real-time, user-facing analytics over high-cardinality event data |
| BigQuery, Snowflake, Redshift | Warehouse analytics, ad-hoc SQL and BI over large history |
| Prometheus, TimescaleDB, InfluxDB | Metrics and time-series with time-range queries and retention |
| pgvector, Pinecone, Milvus, Qdrant | Similarity search over embeddings, from small (pgvector) to very large (dedicated) |
| S3, GCS, Azure Blob | Files, media, backups and data-lake storage |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Single relational database for everything | Simplest operations; one source of truth; transactions everywhere | Specialised workloads (search, analytics) served poorly; eventual scaling limit | Early-stage products; moderate scale; small teams |
| Relational system of record plus derived specialised stores | Each workload gets the right engine; source stays clean | Pipelines to build; staleness in derived stores; more systems to operate | Most mature products |
| NoSQL as system of record | Horizontal scale; predictable latency; managed serverless options | Access patterns fixed up front; weaker ad-hoc queries; transactions limited | Known key-based patterns at very large scale, or very high write rates |
| Distributed SQL | SQL and ACID with horizontal and multi-region scale | Higher write latency; cost; smaller talent pool | Transactional workloads that outgrow one primary, or need global consistency |
| Managed cloud-native database | Minimal operations; built-in HA and backups | Lock-in; cost at scale; less tuning control | Most teams, most of the time |
| Self-hosted open source | Control; portability; potentially cheaper at large scale | Operational burden; needs expertise and on-call | Large scale with a strong platform team, or portability requirements |
Common Pitfalls#
- Choosing by fashion or résumé. Picking a database because it's new or interesting rather than because it fits.
- Modelling NoSQL like SQL. Normalised tables in DynamoDB or Cassandra, followed by scans and application-side joins. NoSQL demands query-first design.
- Ignoring the analytical path. Running reports on the OLTP primary until it falls over during month-end.
- Dual writes to keep stores in sync, which eventually diverge after crashes and partial failures.
- Storing blobs in the database. Multi-megabyte columns that bloat backups and replication.
- Assuming "ACID" means "no anomalies". Default isolation levels allow lost updates and write skew unless you design for them.
- Hot partitions. A partition key with low cardinality or heavy skew (country, date, a celebrity's ID) concentrates load whatever the database.
- Underestimating operations. No tested restores, no capacity alerts, no upgrade plan.
- Unbounded growth. No retention or archival policy, so tables and indexes grow forever.
- Interview over-engineering. Five databases in the first ten minutes, or a graph database for a follower list.
Real-World Examples#
The public engineering record shows that the companies that scaled furthest usually picked a few well-understood databases and engineered around their limits, rather than adopting many exotic ones.
- Facebook: TAO over sharded MySQL. Facebook's social graph lives in many sharded MySQL databases. TAO, described in TAO: Facebook's Distributed Data Store for the Social Graph (Bronson et al., USENIX ATC 2013), is a graph-aware caching layer on top that exposes objects and associations, the data model the product actually uses. The paper reports it sustains about a billion reads per second. Lesson: the record of truth can stay relational while a purpose-built layer serves the access pattern.
- Amazon: Dynamo for the shopping cart. Dynamo: Amazon's Highly Available Key-value Store (DeCandia et al., SOSP 2007) came from the requirement that customers must always be able to add to their cart, even during failures. Amazon chose availability over strong consistency, and reconciled conflicting cart versions on read. This was a requirement-driven choice, not a technology-driven one. DynamoDB later took the name and many of the ideas, but it's a different, managed system. See Amazon DynamoDB in Practice.
- Instagram: sharded PostgreSQL. Instagram's engineering blog (2012) described sharding PostgreSQL into thousands of logical shards mapped onto fewer physical servers. IDs were generated inside the database: a 64-bit value with 41 bits of millisecond timestamp, 13 bits of logical shard ID and 10 bits of per-shard sequence. Logical shards can be moved between machines without re-sharding the data, and IDs sort by time.
- Discord: Cassandra to ScyllaDB for messages. Discord's messages are append-heavy and read as "the latest messages in this channel", which suits wide-column partitioning. By early 2022 they ran 177 Cassandra nodes holding trillions of messages, with garbage-collection pauses and hot partitions causing unpredictable latency. They migrated to 72 ScyllaDB nodes, and p99 read latency fell from a 40–125 ms range to a steady 15 ms. Same data model and access pattern, with a better engine and a request-coalescing service in front.
- Notion: sharding PostgreSQL. Notion's engineering blog (2021) described moving from one large PostgreSQL instance to 480 logical shards spread over 32 physical databases, partitioned by workspace ID so that all of a workspace's blocks live together. They kept PostgreSQL rather than switching engines, and chose a partition key that matches the main transactional boundary.
- Uber: Schemaless on MySQL. Uber's 2016 engineering posts describe Schemaless, an append-only, sharded datastore built as a layer on top of MySQL. They used MySQL as a reliable storage engine and built the scaling and data model they needed above it.
- YouTube and Slack: Vitess. Vitess was created at YouTube to shard MySQL horizontally. Slack wrote in 2020 about migrating its MySQL workloads onto Vitess to get past single-shard limits without leaving MySQL.
- Netflix: Cassandra at scale. Netflix is one of the best-known large Cassandra users, for multi-region, high-write data such as viewing history, alongside many other stores including relational databases where transactions matter.
Common thread: almost all of these kept a mature engine and changed how it's partitioned, cached or layered. Engine switches (Discord) happened when the data model was already right and the engine's operational behaviour was the problem.
Case studies that use this pattern#
Every case study makes a database decision. These show the widest range of reasoning:
- Design a URL Shortener (Bitly): key-value lookups at a huge read-to-write ratio.
- Design a Chat System (WhatsApp): wide-column partitioning for append-heavy messages.
- Design a Ticket Booking System (Ticketmaster): relational transactions against double-booking, with search and cache as derived stores.
- Design a Payment System: ledgers, durability and auditability.
- Design a Metrics Monitoring and Alerting System: time-series storage, compression and retention.
- Design an Ad Click Aggregator: streaming into an OLAP store.
- Design an LLM Chat Service (ChatGPT): conversations plus a vector index for retrieval.
In the Interview#
A strong database answer usually covers:
- The access patterns the store must serve, with rough QPS.
- The choice, by name, and the one or two reasons it fits.
- The data model: tables and indexes, or partition key and sort key, for the top queries.
- How it scales: replicas for reads, the shard key for writes, and when that becomes necessary.
- Consistency and transactions: what's atomic and at what isolation level.
- Derived stores and how they're kept in sync.
Common follow-ups:
- "Why not use NoSQL here?" Answer with the access pattern and the transaction requirement, not with ideology. If NoSQL would also work, say so, and say why you still prefer your choice.
- "What happens at 10× or 100× load?" Walk through replicas, caching, then sharding by a key that keeps transactions local. Mention distributed SQL if transactions span keys.
- "What's your partition key, and what could make it hot?" Name the key, the skew risk (celebrities, popular events) and the mitigation (key splitting, caching, write sharding).
- "How do you keep search or the cache consistent with the database?" CDC or outbox into an indexer; invalidate the cache on change; accept and quantify the lag.
- "How would you migrate if you picked wrong?" Dual-read verification, backfill plus CDC, shadow reads, then a gradual cutover (Deep Dive below).
- "Where do you store images and video?" Object storage with metadata in the database, presigned uploads and a CDN for delivery.
- "How do you handle analytics?" A separate warehouse or OLAP store fed by CDC or the event stream, never heavy reports on the OLTP primary.
Deep Dive: The physics under the choice: B-trees, LSM trees, columns and the RUM conjectureShow
Most "which database?" questions reduce to "which storage layout?". Engines that share a layout behave alike, whatever the marketing says. Knowing the three main layouts lets you predict how an unfamiliar database will behave from one sentence of its documentation. Storage Engines: B-Trees vs LSM Trees covers the internals; this section focuses on what they mean for choosing.
B-trees: read-optimised, update in place. The B-tree (Bayer and McCreight, Organization and Maintenance of Large Ordered Indexes, 1972) keeps keys sorted in fixed-size pages, typically 4–16 KB, with a high fan-out. With 8 KB pages and around 300 keys per interior page, one billion rows need a tree only four levels deep (300⁴ ≈ 8 billion). The top two or three levels stay in memory, so a point lookup costs about one disk read. Range scans follow sorted leaves. PostgreSQL, MySQL InnoDB, SQL Server and Oracle are B-tree engines. The cost is on writes: changing one row rewrites a whole page, plus a write-ahead log (WAL) record. A 100-byte update can cause 8 KB or more of physical writes once the page is flushed: write amplification of up to roughly 80× for small random updates, softened by batching many changes into one page flush. Random writes scattered across a large table also mean random I/O, which is fine on SSDs but slow on spinning disks.
LSM trees: write-optimised, append and merge. The log-structured merge-tree (O'Neil, Cheng, Gawlick and O'Neil, The Log-Structured Merge-Tree, Acta Informatica 1996) buffers writes in memory (a memtable), then flushes them to immutable sorted files (SSTables). Background compaction merges the files. Writes are sequential and cheap; Cassandra, ScyllaDB, RocksDB, HBase and the storage layers of CockroachDB and TiDB use LSM trees. The costs move elsewhere:
- Read amplification. A key may be in the memtable or any of several levels. Bloom filters, about 10 bits per key for a ~1% false-positive rate, skip most files that don't contain the key, but range scans must still merge across levels.
- Write amplification from compaction. With leveled compaction and a size ratio of 10 between levels, each byte is rewritten roughly 10 times per level it passes through. Total write amplification of 10–30× is common, so a 50 MB/s ingest can become several hundred MB/s of background disk writes.
- Space amplification. Size-tiered compaction can temporarily need about twice the live data size on disk; leveled compaction keeps it nearer 1.1×.
- Tombstones. Deletes are writes of a marker. Queries that scan over many tombstones slow down, a classic Cassandra failure mode with queue-like tables.
Column stores: scan-optimised, compress everything. C-Store (Stonebraker et al., VLDB 2005) and its successors store each column separately, sorted and compressed. Worked example: a fact table of 1 billion rows × 100 columns × 8 bytes is 800 GB in a row store. A query summing one column grouped by another reads all 800 GB in a row layout. A column store reads the two columns, 16 GB, and run-length or dictionary encoding typically compresses that by 5–10× again, to 2–3 GB. The difference between minutes and under a second is mostly physics, not cleverness. The cost is that single-row inserts and updates are expensive, so column stores batch writes (ClickHouse parts, Parquet files) and are poor at OLTP.
The RUM conjecture. Athanassoulis et al. (Designing Access Methods: The RUM Conjecture, EDBT 2016) argue that an access method can optimise at most two of three overheads: Read, Update and Memory (space). B-trees favour reads and space and pay on updates; LSM trees favour updates and pay on reads or space; adding indexes speeds reads but costs updates and memory. It's a conjecture rather than a theorem, but it's a reliable lens. When a vendor claims to be best at everything, ask which of the three it gives up and under what workload that shows.
| Layout | Strong at | Weak at | Typical engines | Choose for |
|---|---|---|---|---|
| B-tree, row | Point reads, ranges, in-place updates, transactions | Very high random write rates | PostgreSQL, MySQL InnoDB, SQL Server | OLTP systems of record |
| LSM, row or wide-column | Sustained high write rates, sequential I/O | Read amplification, compaction spikes, tombstones | Cassandra, ScyllaDB, RocksDB, HBase | Append-heavy events, messages, time-ordered data |
| Columnar | Scans and aggregations over few columns, compression | Single-row writes and updates | ClickHouse, BigQuery, Snowflake, Redshift, Parquet | Analytics and reporting |
| Hash index in memory | O-of-1 key lookups at microsecond latency | Range queries; data must fit in RAM | Redis, Memcached | Caches and ephemeral state |
| Inverted index | Term lookup, relevance ranking, facets | Frequent updates to the same document; joins | Lucene, Elasticsearch, OpenSearch | Full-text search |
Practical consequences when choosing:
- If writes dominate and are mostly appends, an LSM engine is the natural fit. Budget disk I/O for compaction (often 2–3× the ingest rate) and keep 30–50% disk headroom.
- If you need many secondary indexes on a write-heavy table, every index multiplies write cost on any engine. Consider moving the secondary query paths to a derived store.
- If reports scan months of history, no OLTP engine will be cheap. Move them to columnar storage.
- If p99 latency must be very stable, watch for background work: compaction in LSM engines, vacuum in PostgreSQL, and garbage collection in JVM-based databases. Discord's move from Cassandra to ScyllaDB was largely about removing garbage-collection pauses, not about a different data model.
Deep Dive: Migrating between databases, and managing lock-inShow
Database choices are Type 1 decisions mostly because migration is hard, not because it's impossible. Knowing the migration playbook changes the risk calculation: a choice you can exit in a quarter is less frightening than one you can't exit at all. Online Data Migrations and Schema Evolution covers the mechanics; here is how it bears on choosing.
The standard online migration has six phases:
- Abstract the access. Route all reads and writes through one repository or data-access layer, so you can switch implementations behind it. Codebases that query the database from everywhere are the hardest to migrate.
- Replicate new changes. Stream every change from the old store to the new one with CDC (for example Debezium reading the PostgreSQL WAL or MySQL binlog), or with an outbox. Avoid application dual writes: a crash between the two writes leaves them permanently divergent, with nothing to notice.
- Backfill history. Copy existing data in throttled batches while CDC keeps the new store current. Make the copy idempotent, so it can be restarted, and make CDC win over backfill for rows changed during the copy. For example, compare a version or timestamp column and keep the newer.
- Verify. Compare row counts and checksums per key range, then shadow read: serve from the old store, read from the new one in parallel, compare, and log mismatches. Run it until the mismatch rate is essentially zero across a full business cycle, including month-end jobs.
- Cut over gradually. Move reads by percentage (1%, 10%, 50%, 100%), then switch writes. Keep reverse replication (new to old) running so rollback is possible.
- Decommission only after a defined soak period, and after the last consumers of the old store have been found. The batch job nobody remembered usually surfaces here.
Worked numbers: backfilling 10 TB at an aggressive 200 MB/s takes about 14 hours. Throttled to 50 MB/s to protect production latency, it takes 10 TB ÷ 50 MB/s = 200,000 seconds, about 2.3 days. Verification and gradual cutover usually take weeks more. A realistic timeline for migrating a core datastore is one to two quarters, and the data copy is the shortest part of it.
What makes a migration hard (and therefore what to avoid early if exit matters):
- Semantics, not syntax. Moving from a serializable store to one with weaker isolation, or from transactions to single-item atomicity, changes behaviour your code relies on without anyone noticing. Inventory where code depends on transactions, unique constraints and read-your-writes.
- Proprietary features. DynamoDB streams and conditional expressions, Spanner's TrueTime-based commit semantics, vendor-specific SQL extensions, stored procedures and triggers all have to be rewritten.
- Data model mismatch. A normalised schema doesn't map onto a single-table NoSQL design. Moving between relational and query-first models means redesigning access patterns, not copying rows.
- Data gravity and egress. Moving tens of terabytes out of a cloud provider incurs transfer charges, and analytics, backups and other services tend to grow around the store.
- Identifiers. Auto-increment IDs, database-generated UUID formats and time-ordered key schemes often leak into URLs, caches and other services.
Managing lock-in deliberately. Lock-in is a cost, not a sin. Paying it for the operational benefits of a managed service is often right. Some practical levers:
- Wire-compatible alternatives lower exit cost. Aurora PostgreSQL, AlloyDB, CockroachDB and YugabyteDB speak the PostgreSQL wire protocol to varying degrees. ScyllaDB is compatible with Cassandra's CQL and offers a DynamoDB-compatible API. Compatibility is never total, so test the features you actually use.
- Open formats for analytics. Keeping the lake in Parquet with an open table format (Apache Iceberg, Delta Lake or Hudi) lets several engines query the same data.
- Isolate proprietary calls behind the data-access layer. Don't abstract everything (lowest-common-denominator abstractions throw away the features you chose the database for), but know where the dependencies are.
- Record the exit plan in the ADR: the trigger that would make you leave, the likely target, and a rough cost. Revisiting it yearly is cheap insurance.
Schema evolution within one database follows the same principle in miniature: expand, migrate, contract. Add the new column or table (expand), dual-read or backfill while both shapes coexist, switch readers, and only then drop the old shape (contract). Each step is independently deployable and reversible. On large PostgreSQL or MySQL tables, use online schema-change tools (pg_repack, gh-ost, pt-online-schema-change) or features that avoid long locks; adding an index on a 500 GB table without CONCURRENTLY can block writes for an hour.
Deep Dive: Benchmarking and validating a database choiceShow
A spike that measures the riskiest access pattern is the most valuable step in choosing a database, and also the easiest one to get wrong. Most misleading results come from a handful of mistakes that are easy to avoid once you know them.
Standard benchmarks and what they're for.
- YCSB. The Yahoo! Cloud Serving Benchmark (Cooper, Silberstein, Tam, Ramakrishnan and Sears, Benchmarking Cloud Serving Systems with YCSB, SoCC 2010) defined a common harness and core workloads for key-value and NoSQL stores. Workload A is 50% reads and 50% updates; B is 95/5; C is read-only; D reads the latest inserted records; E runs short range scans; F does read-modify-write. Keys follow a Zipfian distribution by default, so a few keys are hot, as in real traffic. YCSB is useful for comparing engines on simple key access, but it says nothing about joins, transactions or secondary indexes.
- TPC-C. TPC-C models an order-entry business with warehouses, districts, customers, orders and stock. Its transaction mix is roughly 45% New-Order, 43% Payment and 4% each Order-Status, Delivery and Stock-Level. Throughput is reported as New-Order transactions per minute (tpmC). It stresses multi-row transactions and contention, which is why distributed SQL vendors cite it. The official benchmark has strict rules; vendor "TPC-C-like" runs often don't follow them.
- TPC-H and TPC-DS. Decision-support benchmarks for analytical engines: 22 queries for TPC-H and 99 for TPC-DS, run over generated data at scale factors such as 1 TB.
- Jepsen. Not a performance benchmark: Kyle Kingsbury's Jepsen tests check whether a database keeps its consistency promises under network partitions, clock skew and crashes. Its published analyses have found lost writes, stale reads and isolation anomalies in many well-known systems, often in configurations their documentation described as safe. The Elle checker (Kingsbury and Alvaro, Elle: Inferring Isolation Anomalies from Experimental Observations, VLDB 2020) infers isolation violations from transaction histories. If correctness matters, read the Jepsen analysis of your candidate and note which version and settings it tested.
Designing your own spike. Vendor and standard benchmarks rarely match your workload, so test the hardest pattern yourself:
- Use your data shape and size. Load at least as much data as production will have within a year, and make sure it exceeds RAM. A 100 GB test on nodes with 256 GB of memory measures the cache, not the database. Reproduce key skew: real traffic is Zipfian, and a uniform random key distribution hides hot partitions.
- Use your queries, including the secondary-index lookups and range scans, at the real read-to-write mix.
- Run to steady state. LSM engines look fast until compaction catches up, and B-tree engines look fast until the table outgrows the buffer pool and vacuum or purge runs. Run for hours, not minutes.
- Measure tail latency correctly. Report p50, p99 and p99.9 using a histogram such as HdrHistogram, not averages. Beware coordinated omission, a term popularised by Gil Tene. A closed-loop load generator waits for each response before sending the next request, so when the database stalls the generator stops sending and the stall barely appears in the results. Use an open-loop generator that sends at a fixed rate (wrk2 and k6's constant-arrival-rate executor work this way), or correct for the missing samples.
- Find the knee. Increase load stepwise until latency rises sharply. Queueing theory says latency grows like 1/(1−ρ) as utilisation ρ approaches 1, so plan to run at the load where p99 still meets the target, typically 50–70% of the knee.
- Break it on purpose. Kill a node, fail over the primary, partition the network and fill a disk, all while under load. Measure how long writes are unavailable, whether any acknowledged writes are lost, and how long recovery and rebalancing take.
- Price it. Convert the configuration you needed for the target p99 into monthly cost, including replicas, storage, I/O and backups.
A worked result. A team spiking DynamoDB against PostgreSQL for a 20,000 reads/s and 2,000 writes/s key-value workload with a 10 ms p99 target might find both meet it. PostgreSQL needs a primary plus two replicas on mid-size instances; DynamoDB needs nothing but capacity settings. At that point the decision comes down to cost at the measured load, the team's operational capacity, and whether future access patterns need ad-hoc queries. The benchmark didn't pick the winner; it removed the performance question so the real trade-offs became visible.
Key Takeaways#
- Choose a database from access patterns first: what is read and written, how often, how fast, and how fresh. Data shape comes second.
- Ask four questions in order: transactional or analytical? What atomicity is needed? Which access pattern dominates? How large and how fast will it grow?
- Relational (usually PostgreSQL) is the default system of record. One well-tuned primary with replicas handles more than most teams expect; move away from it only for a specific reason.
- Choose NoSQL for known, key-based access at very large scale or very high write rates, and design the model query-first.
- Search, analytics, caches, time series and vectors are usually derived stores fed by CDC or an outbox, never by dual writes.
- Keep blobs in object storage with metadata in the database, served through a CDN.
- Count total cost: compute, storage, requests, transfer, backups and the people who operate it. A database your team knows is worth a lot.
- The layout decides behaviour: B-trees favour reads and updates in place, LSM trees favour writes, column stores favour scans. Every engine gives up something (the RUM conjecture).
- Treat the choice as a Type 1 decision. Spike the riskiest pattern with realistic data and tail-latency measurement, record an ADR with exit triggers, and know the migration playbook before you need it.
- In interviews, name the database and give one or two reasons tied to the requirements. Then show the data model, the scaling path and how derived stores stay in sync.