Skip to content

Databases

Almost every system design question reduces to “where does the data live and how is it found”. Choosing a database is choosing a set of guarantees and a write path. Most teams should start with a relational database, and the reason is not familiarity — it is that constraints, transactions and a query planner solve more problems than they create.

Start relational: schema, constraints, joins and ACID transactions solve the majority of application problems, and PostgreSQL or MySQL scales further than most people think. Choose NoSQL when a specific access pattern demands it — huge write volume, a document-shaped aggregate, key-value lookups at low latency, or a graph. Indexes are B-trees by default: they make reads fast and writes slower, and every query must be served by one. Replication gives read scale and availability at the cost of lag; sharding gives write scale at the cost of cross-shard queries and rebalancing.

Relational (PostgreSQL, MySQL) NoSQL (document, KV, wide-column, graph)
Schema Enforced, migratable Flexible or absent
Query Arbitrary SQL, joins, aggregates Fixed access paths, usually no joins
Transactions Multi-row, multi-table ACID Often single-item
Scaling writes Vertical + sharding Horizontal by design
Consistency Strong by default Tunable, often eventual
Best at Relationships, invariants, reporting Volume, specific access patterns

NoSQL families and their real shapes:

  • Key-value (Redis, DynamoDB): get(key) at high throughput. No query language; you must know the key.
  • Document (MongoDB, Couchbase): a whole aggregate in one document. Good when you always read the aggregate together; painful for cross-document transactions and joins.
  • Wide-column (Cassandra, HBase, ScyllaDB): partitioned by key, sorted by clustering columns. Designed for very high write throughput and time-series-style access.
  • Search (Elasticsearch, OpenSearch): inverted indexes. A secondary index over a system of record, not a primary store.
  • Graph (Neo4j): traversal-heavy queries with many hops.

The phrase “schemaless” is misleading. A document store has no enforced schema, so the schema lives in your application code and every reader must handle every historical shape.

An index is a sorted data structure (usually a B-tree) mapping key values to row locations.

CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);

Rules that hold in every relational engine:

  • Composite index order matters. (customer_id, created_at) serves WHERE customer_id = ? and WHERE customer_id = ? ORDER BY created_at, but not WHERE created_at = ?. Leftmost prefix.
  • A covering index contains every column the query needs, so the engine never touches the table. Add the selected columns as trailing key or INCLUDE columns.
  • Selectivity determines usefulness. An index on a boolean column with two values is usually ignored by the planner; a full scan is cheaper.
  • Every index costs on write. Each insert/update maintains every index. Twelve indexes on a write-heavy table is a design smell.
  • Functions and casts disable indexes unless you create an expression index or the type matches: WHERE lower(email) = ? needs an index on lower(email).
  • Check the plan. EXPLAIN ANALYZE tells you whether the index is used and where the time goes. Guessing is not optimisation.
EXPLAIN ANALYZE
SELECT id, total_cents FROM orders
WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;

If you see Seq Scan on a large table with a selective filter, the index is missing or unusable.

ACID: atomicity (all or nothing), consistency (constraints hold), isolation (concurrent transactions do not corrupt each other), durability (committed survives a crash).

Isolation levels and the anomalies they permit:

Level Dirty read Non-repeatable read Phantom read
Read uncommitted possible possible possible
Read committed (Postgres default) no possible possible
Repeatable read (MySQL default) no no possible*
Serializable no no no

*Postgres REPEATABLE READ also prevents phantoms in practice by aborting on conflict; the standard permits them. Say “the implementation differs” rather than asserting a rule.

Higher isolation means more locking or more aborts. Know what your default is, and when you need SELECT ... FOR UPDATE or SERIALIZABLE — a lost update on a balance is exactly the case where read committed is not enough.

Single-leader (primary/replica). Writes go to the primary, replicate to read replicas.

  • Read scale, failover, and a hot standby for backups.
  • Replication lag means replicas are stale. Consequences: a user reads their own write and does not see it; a cache is warmed from stale data; a failover loses the last few writes if replication is asynchronous.
  • Synchronous replication removes the loss window at the cost of write latency (one more round trip) and availability if the replica is unreachable.

Multi-leader. Writes accepted in several places, conflicts resolved afterwards. Needed for multi-region active-active; conflict resolution is genuinely hard, and “last write wins” silently discards data.

Leaderless / quorum (Dynamo-style, Cassandra). The client writes to N replicas and reads from a quorum. R + W > N guarantees the read set overlaps the write set, so a read sees the latest write. This is the mechanism behind tunable consistency, covered in CAP and Consistency.

Two different things people conflate:

  • Partitioning splits one table into pieces inside one database (range or hash). Improves vacuum, index size and scan pruning. No distribution problem.
  • Sharding splits data across separate databases. Buys write scale and storage, costs cross-shard queries and transactions.

Shard key strategies:

Strategy Pro Con
Hash of key Even distribution Range queries need every shard
Range Efficient range scans Hotspot at the newest range (time-series)
Directory / lookup Flexible, easy to move data The directory is a SPOF and a latency hop
Geographic Data locality, compliance Cross-region queries

Choosing the key is the most consequential decision on the page:

  • High cardinality, so shards can be even.
  • Present in the most common query, so queries stay single-shard.
  • Not monotonically increasing, or one shard takes all writes (the classic “shard by timestamp” failure).

Resharding is the hard part. Consistent hashing and virtual nodes limit how much data moves when you add a shard; a directory service lets you move individual tenants. Either way, plan for data migration while serving traffic.

BASE — Basically Available, Soft state, Eventually consistent — describes systems that prefer availability and low latency over immediate consistency. It is not a synonym for “no guarantees”: it is a different, weaker, explicitly bounded set. Amazon’s Dynamo paper popularised it.

The useful framing is not ACID vs BASE but where each applies. A payment ledger needs ACID. A “likes” counter can be eventually consistent. A product catalogue can be eventually consistent for search and strongly consistent for price at checkout.

Work backwards from access patterns:

  1. What are the top three queries, with their filters and sort orders?
  2. What is the write volume and the read:write ratio?
  3. Do writes need multi-entity transactions?
  4. What consistency does each read require?
  5. What is the growth rate and the retention policy?
  6. Does the team already operate this engine? Operational cost is a real cost.

Default answers that survive scrutiny:

  • PostgreSQL for general application data, with jsonb for semi-structured parts and full-text search when you do not need a dedicated engine.
  • Redis for caching, counters, rate limits and ephemeral state.
  • A queue for asynchronous work, not a database table polled in a loop.
  • A search engine as a secondary index, rebuilt from the primary store.
  • A wide-column store when write volume or time-series access genuinely exceeds a relational primary — measured, not assumed.
  1. Which columns would you index for WHERE tenant_id = ? AND status = ? ORDER BY created_at?
  2. What breaks in the application when replication lag is two seconds?
  3. How do you shard a table by user id and still answer “top 10 today”?
  4. When is a SELECT ... FOR UPDATE necessary, and what does it cost?
  5. How do you migrate a large table’s schema without downtime?
  6. Why is an eventually consistent counter acceptable but an eventually consistent balance not?
  • “NoSQL scales better.” It scales differently. Many workloads fit in one Postgres instance far beyond what a rewrite would cost.
  • “Add an index for every filter.” Indexes slow writes and bloat storage. Index for the actual query shapes.
  • “Shard early.” Sharding is a one-way door with a large operational bill. Partition first.
  • “Replicas give consistency.” They give lag and read capacity.
  • “Eventually consistent means it will be fine.” It means you must design for the window. Say how long it is and what the user sees during it.