Guide / System design Fundamentals
3. Databases — types and how to choose
Choose a database by access pattern, not by fashion: what you query by, how much you write, what consistency you need, and how the data relates. Most real systems are polyglot: Postgres for transactions, Redis for hot reads, Elasticsearch for search, S3 for blobs, Kafka as the event log.
3.1 The main families#
| Type | Examples | Data model | Best at | Weak at |
|---|---|---|---|---|
| Relational (SQL) | PostgreSQL, MySQL, Aurora | Tables, rows, joins, schema | ACID transactions, complex queries, joins, integrity (orders, payments, payroll) | Horizontal write scaling without sharding work; rigid schema changes at huge scale |
| Distributed SQL (NewSQL) | CockroachDB, Spanner, TiDB, YugabyteDB | SQL tables, auto-sharded, consensus-replicated | SQL + ACID + horizontal scale, multi-region | Higher write latency (consensus), cost, operational complexity |
| Key-value | Redis, DynamoDB, Memcached, etcd | Key → value | Lookups by key at massive scale, sessions, carts, counters | Queries by anything other than the key; ad-hoc analytics |
| Document | MongoDB, Firestore, Couchbase | JSON documents, nested | Flexible schema, aggregates read together (product catalogue, CMS, profiles) | Cross-document joins and transactions (possible but costly); data duplication |
| Wide-column | Cassandra, ScyllaDB, HBase, Bigtable | Partition key + clustering columns | Massive write throughput, time-ordered data per key (messages, IoT, activity feeds) | Ad-hoc queries; you design one table per query; no joins; tombstone/compaction pain |
| Graph | Neo4j, Amazon Neptune, TigerGraph, ArangoDB | Nodes + edges + properties | Multi-hop relationship queries (friends-of-friends, fraud rings, recommendations, knowledge graphs) | Bulk aggregations, simple CRUD at scale, horizontal sharding of the graph |
| Time-series | TimescaleDB, InfluxDB, Prometheus, ClickHouse | Timestamped points | Metrics, monitoring, IoT; downsampling and retention | General transactions; updates to old data |
| Search engine | Elasticsearch, OpenSearch, Solr, Typesense | Inverted index | Full-text search, fuzzy match, faceting, log search | Source of truth; strong consistency (near-real-time refresh ~1 s) |
| Columnar / OLAP | ClickHouse, BigQuery, Snowflake, Redshift, Druid | Column-oriented storage | Aggregations over billions of rows, dashboards, analytics | Point lookups and high-rate single-row updates |
| Object / blob | S3, GCS, Azure Blob | Files + metadata | Images, videos, backups, data lake files (Parquet) | Low-latency small random updates |
| Vector | pgvector, Pinecone, Qdrant, Weaviate, Milvus | Embedding vectors + metadata | Similarity search for RAG, recommendations | Exact queries, transactions (see Part 2, section 16) |
| Ledger / event store | EventStoreDB, Kafka (as log), QLDB-style ledgers | Append-only events | Audit trails, event sourcing | Querying current state without projections |
3.2 Decision guide#
- Money, inventory, anything that needs multi-row atomicity → relational (Postgres/MySQL). Shard or move to distributed SQL only when one primary can’t keep up.
- Known key lookups at huge scale, simple access → DynamoDB / Cassandra / Redis.
- Very high write rate, append-mostly, query by one key + time → Cassandra/ScyllaDB (chat messages, events).
- Flexible, nested, read-as-a-whole objects → document DB (or Postgres JSONB if you also need transactions).
- Questions are about relationships 3+ hops deep → graph DB.
- Full-text, typo-tolerant, faceted search → Elasticsearch/OpenSearch, fed from the primary DB via CDC.
- Analytics over billions of rows → columnar warehouse fed by ETL/CDC; never run heavy analytics on the OLTP primary.
- Semantic similarity → vector index (pgvector first if you already run Postgres and have < ~10–50M vectors).
3.3 SQL vs NoSQL — the honest trade-off#
| Question | SQL | NoSQL |
|---|---|---|
| Schema | Enforced, migrations | Flexible, enforced in app code |
| Queries | Any query, joins, ad-hoc | Only the access patterns you designed for |
| Transactions | Multi-row ACID by default | Usually single-item atomic; multi-item is limited or slower |
| Scaling | Vertical + read replicas; sharding is manual work | Built-in horizontal partitioning |
| Consistency | Strong on primary | Often tunable or eventual |
Interview line: “I’d start with Postgres because the data is relational and we need transactions. At our estimated 1.2K writes/s a single primary with replicas is enough. If writes grow 10×, I’d shard by user_id or move this table to Cassandra/DynamoDB since its access pattern is key-based.”
3.4 DynamoDB / Cassandra modelling (often probed)#
- Partition key decides which node holds data; a good key has high cardinality and even traffic. Sort/clustering key orders data within a partition so range queries are cheap (
user_id+created_at). - Design tables from queries: list access patterns first, then a table (or GSI) per pattern. Single-table design in DynamoDB packs several entity types into one table with composite keys (
PK=USER#1,SK=ORDER#2026-11-01). - Hot partitions: a celebrity or a date-only key concentrates traffic; add a shard suffix (
date#0..9) and query all suffixes. - GSI: a secondary index with its own keys; eventually consistent, costs extra writes.
- Cassandra tunable consistency: with replication factor N, read R + write W > N gives strong reads (e.g. QUORUM/QUORUM with N=3).
- Partition size limits: keep Cassandra partitions under ~100 MB; bucket by time (
chat_id + month).
3.5 Search engine internals (Elasticsearch / OpenSearch)#
- Inverted index: maps each term to the list of documents containing it (posting list, with positions and frequencies). A query for “red shoes” intersects the posting lists for “red” and “shoes” — fast regardless of corpus size.
- Analyzers turn text into terms at index and query time: tokenizer (split words) → filters (lowercase, stop words, stemming “running” → “run”, synonyms, ASCII folding). Index-time and query-time analyzers must match, or searches miss.
- Relevance: BM25 scores by term frequency (more occurrences = more relevant, with saturation), inverse document frequency (rare terms matter more), and document length normalization. Business ranking adds boosts (popularity, stock, recency) via
function_scoreor a rerank step. - Fuzzy and partial matching: edit-distance fuzzy queries for typos, n-grams / edge n-grams for autocomplete (bigger index), completion suggesters for fast prefix lookups.
- Structure: an index is split into primary shards (fixed at creation, so choose with growth in mind; reindex to change) each with replicas (for failover and read throughput). Each shard is a Lucene index made of immutable segments; updates are delete + reinsert; background merges compact segments.
- Near-real-time: new documents become searchable after a refresh (~1 s default); durability comes from the translog. So it’s not read-after-write consistent — don’t use it as the source of truth.
- Query flow: a coordinating node scatters the query to one copy of each shard, each returns top hits (query phase), coordinator merges and fetches documents (fetch phase). Deep pagination (
from: 100000) is expensive — usesearch_aftercursors. - Aggregations / facets: counts by brand, price ranges; computed on doc values (columnar). Terms aggregations across shards are approximate for very large cardinality.
- Keeping it in sync: primary DB → CDC (Debezium) or outbox events → indexer → Elasticsearch. Indexers are idempotent (doc ID = primary key, use external version numbers to drop out-of-order updates).
- Zero-downtime reindex (mapping change, new analyzer): create
products_v2, backfill, dual-write or replay CDC, switch the aliasproducts→products_v2, delete v1. - Common pitfalls: mapping explosion (dynamic fields from arbitrary JSON keys), too many small shards (overhead per shard), huge shards (slow recovery; aim for tens of GB per shard), heap pressure from fielddata on text fields, split-brain in old clusters (modern versions use quorum-based master election).
Finished this page?Mark it done to track your progress across the guide.