Interview Study Guide

Guide / System design Fundamentals

3. Databases — types and how to choose

Created · Updated · 6 min read

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#

TypeExamplesData modelBest atWeak at
Relational (SQL)PostgreSQL, MySQL, AuroraTables, rows, joins, schemaACID 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, YugabyteDBSQL tables, auto-sharded, consensus-replicatedSQL + ACID + horizontal scale, multi-regionHigher write latency (consensus), cost, operational complexity
Key-valueRedis, DynamoDB, Memcached, etcdKey → valueLookups by key at massive scale, sessions, carts, countersQueries by anything other than the key; ad-hoc analytics
DocumentMongoDB, Firestore, CouchbaseJSON documents, nestedFlexible schema, aggregates read together (product catalogue, CMS, profiles)Cross-document joins and transactions (possible but costly); data duplication
Wide-columnCassandra, ScyllaDB, HBase, BigtablePartition key + clustering columnsMassive 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
GraphNeo4j, Amazon Neptune, TigerGraph, ArangoDBNodes + edges + propertiesMulti-hop relationship queries (friends-of-friends, fraud rings, recommendations, knowledge graphs)Bulk aggregations, simple CRUD at scale, horizontal sharding of the graph
Time-seriesTimescaleDB, InfluxDB, Prometheus, ClickHouseTimestamped pointsMetrics, monitoring, IoT; downsampling and retentionGeneral transactions; updates to old data
Search engineElasticsearch, OpenSearch, Solr, TypesenseInverted indexFull-text search, fuzzy match, faceting, log searchSource of truth; strong consistency (near-real-time refresh ~1 s)
Columnar / OLAPClickHouse, BigQuery, Snowflake, Redshift, DruidColumn-oriented storageAggregations over billions of rows, dashboards, analyticsPoint lookups and high-rate single-row updates
Object / blobS3, GCS, Azure BlobFiles + metadataImages, videos, backups, data lake files (Parquet)Low-latency small random updates
Vectorpgvector, Pinecone, Qdrant, Weaviate, MilvusEmbedding vectors + metadataSimilarity search for RAG, recommendationsExact queries, transactions (see Part 2, section 16)
Ledger / event storeEventStoreDB, Kafka (as log), QLDB-style ledgersAppend-only eventsAudit trails, event sourcingQuerying current state without projections

3.2 Decision guide#

  1. 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.
  2. Known key lookups at huge scale, simple access → DynamoDB / Cassandra / Redis.
  3. Very high write rate, append-mostly, query by one key + time → Cassandra/ScyllaDB (chat messages, events).
  4. Flexible, nested, read-as-a-whole objects → document DB (or Postgres JSONB if you also need transactions).
  5. Questions are about relationships 3+ hops deep → graph DB.
  6. Full-text, typo-tolerant, faceted search → Elasticsearch/OpenSearch, fed from the primary DB via CDC.
  7. Analytics over billions of rows → columnar warehouse fed by ETL/CDC; never run heavy analytics on the OLTP primary.
  8. 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#

QuestionSQLNoSQL
SchemaEnforced, migrationsFlexible, enforced in app code
QueriesAny query, joins, ad-hocOnly the access patterns you designed for
TransactionsMulti-row ACID by defaultUsually single-item atomic; multi-item is limited or slower
ScalingVertical + read replicas; sharding is manual workBuilt-in horizontal partitioning
ConsistencyStrong on primaryOften 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_score or 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 — use search_after cursors.
  • 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 alias products → 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.
Pritam Ghosh · System design & AI engineering study notes