System designDataFundamental

Database Design in System Design

How to choose a datastore from access patterns, keep data correct under concurrency, and scale it from one machine to many: transactions, indexes, replication and sharding.

The short answerChoose a database from your access patterns and correctness needs, not its popularity. Use a relational database (PostgreSQL, MySQL) when you need transactions, constraints and joins; a key-value, document, wide-column, search, time-series or vector store when one access pattern dominates. Scale in order: fix queries and indexes, pool connections, cache hot reads, add read replicas, partition and archive, and shard only when one primary can't handle the writes or the data.

HLD book
01Fundamentals

How should you think about databases?

Pick storage from the application's access patterns and correctness needs. Popularity is not a requirement.

Before you say PostgreSQL, MongoDB, Cassandra or Redis, answer the questions that actually decide storage design:

  • Read patterns?
  • Write patterns?
  • Need transactions?
  • Strong consistency?
  • Relationships?
  • Ad-hoc queries?
  • Dataset size?
  • Expected QPS?
  • Read- or write-heavy?
  • Range queries?
  • Can data be stale?
  • Global distribution?

OLTP vs OLAP: what kind of work is it?

OLTP · transactions

  • Many small reads and writes
  • Live, user-facing, low latency
  • Frequent INSERT and UPDATE
  • Point lookups by key
  • PostgreSQL, MySQL, MongoDB

OLAP · analytics

  • Large scans over history
  • Aggregations, GROUP BY
  • Dashboards and reports
  • Column-oriented storage
  • BigQuery, ClickHouse, Snowflake
02Storage models

Ten database families

Each family is optimised for a different access pattern. Know what each is built for and what it gives up.

  1. Relational (SQL)

    PostgreSQL · MySQL · SQL Server
    Built for
    Structured data, relationships, constraints and transactions.
    Use for
    Payments, orders, bookings, inventory, accounts, wallets.
    Strength
    ACID, joins, foreign keys, flexible queries, mature tooling.
    Trade-off
    Schema changes need planning; horizontal write scaling takes work.
  2. Document

    MongoDB · Couchbase · Firestore
    Built for
    Self-contained JSON-like documents with flexible fields.
    Use for
    Catalogues, profiles, CMS content, varying metadata.
    Strength
    Flexible schema, natural mapping to app objects.
    Trade-off
    Duplication is common; complex relations are awkward.
  3. Key-value

    Redis · DynamoDB · Aerospike
    Built for
    Getting a value by a known key, very fast.
    Use for
    Cache, sessions, carts, counters, rate limits, flags.
    Strength
    Very high throughput, easy to partition, TTLs.
    Trade-off
    Few ad-hoc queries; access patterns must be known up front.
  4. Wide-column

    Cassandra · ScyllaDB · HBase
    Built for
    Huge, distributed, write-heavy workloads.
    Use for
    Event histories, feeds, IoT, messaging metadata.
    Strength
    Massive write throughput, horizontal scale, availability.
    Trade-off
    Model tables per query; a new query may need a new table.
  5. Graph

    Neo4j · Neptune · JanusGraph
    Built for
    Traversing relationships between entities.
    Use for
    Social graphs, fraud rings, recommendations, dependencies.
    Strength
    Fast many-hop queries.
    Trade-off
    Not for general CRUD; distributed traversal is hard.
  6. Time-series

    TimescaleDB · InfluxDB · VictoriaMetrics
    Built for
    Timestamped measurements, appended continuously.
    Use for
    Metrics, monitoring, sensors, telemetry, price ticks.
    Strength
    Compression, retention, downsampling, time-window queries.
    Trade-off
    Not a general transactional store.
  7. Search engine

    Elasticsearch · OpenSearch · Solr
    Built for
    Full-text search with inverted indexes and ranking.
    Use for
    Product search, autocomplete, log search, facets.
    Strength
    Fuzzy matching, relevance, aggregations.
    Trade-off
    Not the source of truth; needs syncing; heavy to operate.
  8. Vector

    pgvector · Qdrant · Milvus · Pinecone
    Built for
    Nearest-neighbour search over embeddings.
    Use for
    RAG, semantic search, image similarity, AI memory.
    Strength
    Search by meaning, with metadata filters.
    Trade-off
    Approximate search trades recall for speed; embeddings need refreshing.
  9. Columnar / analytical

    ClickHouse · BigQuery · Snowflake
    Built for
    Scanning and aggregating huge datasets.
    Use for
    Analytics, dashboards, BI, warehouses.
    Strength
    Column compression, very fast GROUP BY and SUM.
    Trade-off
    Poor at frequent small transactional writes.
  10. Distributed SQL

    Spanner · CockroachDB · YugabyteDB
    Built for
    SQL and transactions across many nodes and regions.
    Use for
    Global transactional apps, multi-region SQL.
    Strength
    SQL + horizontal scale + replication.
    Trade-off
    Distributed transactions add latency; often unnecessary early on.
03Decision guide

Which database should you use?

Start from the access pattern, then pick the family built for it.

Identify the access patternTransactions? Search? Analytics? Relationships?
TransactionsPostgreSQL / MySQL
Flexible documentsMongoDB
Key lookupRedis / DynamoDB
Huge writesCassandra
RelationshipsGraph DB
MetricsTime-series DB
Text searchElasticsearch
Semantic searchVector DB
AnalyticsClickHouse / BigQuery
04Data modelling

Normalisation vs denormalisation

Normalise to store each fact once. Denormalise on purpose, where a measured read path needs it.

Normalisation

  • Each fact stored once
  • No update anomalies
  • Separate entities, linked by keys
  • Reads often need JOINs

Denormalisation

  • Selected data duplicated
  • Fewer expensive JOINs on hot paths
  • Writes must update every copy
  • Needs a sync strategy (events, triggers, jobs)
Normal formRule
1NFAtomic values: no repeating groups or lists in a column.
2NF1NF, and no column depends on only part of a composite key.
3NF2NF, and no column depends on another non-key column.
05Transactions

ACID and BASE

Two ways to reason about correctness: strict transactional guarantees, or availability first with eventual agreement.

Atomicity

All of a transaction's changes happen, or none do.

Consistency

Transactions keep the defined rules and constraints valid.

Isolation

Concurrent transactions interact only as the isolation level allows.

Durability

Once committed, data survives crashes.

A bank transfer is atomicsql
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;   -- both happen, or (on error / ROLLBACK) neither does

BASE

Basically available

The system keeps answering, even during failures.

Soft state

State may change without new input as replicas converge.

Eventually consistent

Given no new writes, all replicas agree eventually.

06Concurrency

Transaction isolation levels

Isolation decides which effects of concurrent transactions you can observe. Stricter means fewer anomalies and less concurrency.

LevelDirty readNon-repeatable readPhantom readConcurrency
READ UNCOMMITTEDPossiblePossiblePossibleHighest
READ COMMITTEDPreventedPossiblePossibleHigh
REPEATABLE READPreventedPreventedDepends on DBMedium
SERIALIZABLEPreventedPreventedPreventedLowest

Dirty read

Reading another transaction's uncommitted change.

Non-repeatable read

The same row returns a different committed value later in your transaction.

Phantom read

Re-running a range query returns rows that weren't there before.

Lost update

Two transactions overwrite each other's change without noticing.

07Concurrency control

Locking and MVCC

Two ways to protect a record many users update at once, and the mechanism that lets reads and writes coexist.

Pessimistic locking

Lock first, then work. Good when conflicts are likely.

  • SELECT … FOR UPDATE
  • Other writers wait
  • Keep the transaction short

Optimistic locking

Work first, check on write. Good when conflicts are rare.

  • UPDATE … WHERE version = 7
  • 0 rows updated → someone else won; retry
  • High concurrency
Pessimisticsql
BEGIN;
SELECT * FROM seats WHERE id = 10 FOR UPDATE;   -- others wait here
UPDATE seats SET status = 'BOOKED' WHERE id = 10;
COMMIT;
Optimisticsql
UPDATE seats
SET    status = 'BOOKED', version = version + 1
WHERE  id = 10 AND version = 7;   -- affected rows = 0 means a conflict

MVCC: multi-version concurrency control

Transaction AReads version 1
Row version 1balance = 100
Row version 2balance = 150

A keeps reading its consistent snapshot (version 1) while newer transactions see version 2. Readers don't block writers.

08Distributed systems

CAP and consistency models

When the network splits, a distributed database must choose between answering and answering correctly.

Consistency

Every read sees the latest write (or an error).

Availability

Every request to a live node gets a response.

Partition tolerance

The system keeps working when nodes can't talk to each other.

Consistency is a spectrum

ModelWhat the client gets
Strong (linearizable)Reads always reflect the latest committed write.
Bounded stalenessReads may lag, but only by at most X seconds or versions.
CausalCausally related operations are seen in order.
Read-your-writesYou always see your own updates.
Monotonic readsOnce you've seen a newer value, you never see an older one.
EventualReplicas may differ for a while, then converge.
09Performance

Indexes and query plans

Indexes let the database find rows without reading the whole table. The optimiser decides whether to use them.

Without an index: a full table scansql
SELECT * FROM users WHERE email = '[email protected]';
-- may scan millions of rows to find one
With an index: a direct lookupsql
CREATE INDEX idx_users_email ON users (email);

B-tree

The default: equality, ranges, sorting.

Hash

Equality lookups only.

Composite

Several columns; follows the leftmost-prefix rule.

Covering

Includes every column the query needs, so the table isn't touched.

Partial

Indexes only some rows, e.g. WHERE status = 'ACTIVE'.

Full-text / spatial / vector

Text search, geography, nearest-neighbour.

Composite index order matters

Leftmost-prefix rulesql
CREATE INDEX idx_orders_user_status ON orders (user_id, status);

-- uses the index:  WHERE user_id = 42
-- uses the index:  WHERE user_id = 42 AND status = 'PAID'
-- can't use it well: WHERE status = 'PAID'

How the optimiser picks a plan

SQL query
Parser + plannerGenerates candidate plans
Cost estimatorUses statistics, cardinality, indexes
Execution planIndex scan / seq scan / join strategy
Read the plansql
EXPLAIN ANALYZE
SELECT id, user_id, status
FROM   orders
WHERE  user_id = 42 AND status = 'PAID';

Red flags in a plan

  • Seq scan on a huge table
  • Estimated rows far from actual
  • Expensive sorts
  • Nested loops over large inputs

What fixes them

  • The right index
  • Fresh statistics (ANALYZE)
  • Rewriting the query
  • Selective predicates first
10Connections

Connection pooling

Opening a database connection per request is slow and eats database memory. Reuse a bounded set instead.

App 1
App 2
App N
Connection pool / proxye.g. 50 shared connections (PgBouncer, RDS Proxy)
Database
11Availability and read scale

Replication

Keep copies of the data on several nodes for availability, durability and read capacity.

PrimaryAccepts writes
Replica 1reads
Replica 2reads
Replica 3failover standby

Single leader

One primary takes writes; followers copy them. The common default.

Multi leader

Several nodes accept writes (e.g. per region). Conflicts must be resolved.

Leaderless

Write to and read from several replicas with quorums (Dynamo, Cassandra).

Synchronous

  • Wait for the replica's acknowledgement
  • Stronger durability
  • Higher write latency

Asynchronous

  • Acknowledge immediately
  • Low write latency
  • Replica lag; failover can lose recent writes

Read/write splitting

Writes
Reads
Primaryall writes
Replica routerspreads reads
R1
R2
R3
12Horizontal scaling

Partitioning and sharding

Split big data into pieces. Partitioning splits it; sharding puts the pieces on different machines.

Horizontal partitioning

Split rows.

  • orders_2025, orders_2026, orders_2027
  • Great for time-based data
  • Old partitions can be archived or dropped cheaply

Vertical partitioning

Split columns or features.

  • users (id, email, name)
  • user_profiles (user_id, bio, avatar, preferences)
  • Hot narrow table, cold wide table

Sharding

Application
Shard routershard = f(shard key)
Shard Asubset
Shard Bsubset
Shard Csubset
StrategyHowWatch out for
Hashhash(key) mod N or a hash ringRange queries hit every shard
RangeKey ranges per shard (A–F, G–M…)Hot spots on popular or newest ranges
DirectoryA lookup service maps entity → shardThe directory must be fast and highly available
GeoBy region or countryUsers who move; global queries

Cross-shard joins

Expensive or impossible; denormalise or join in the app.

Cross-shard transactions

Need 2PC or sagas; avoid them by design.

Rebalancing

Moving data when adding shards, without downtime.

Global uniqueness

Unique constraints and IDs across shards (use Snowflake-style IDs).

Hot shards: the celebrity problem again

User
User
Millions
Shard Aoverloaded
Shard Bmostly idle
Shard Cmostly idle

A good shard key

  • High cardinality
  • Spreads traffic evenly
  • Matches the most common query
  • Avoids cross-shard queries

Fixing a hot shard

  • Cache the hot reads
  • Read replicas for that shard
  • Salt the key (id#0 … id#9)
  • Split the hot partition, or change the key
13Distribution

Consistent hashing and quorums

Move as few keys as possible when nodes change, and decide how many replicas must agree.

With hash(key) mod N, adding one node remaps almost every key. Consistent hashing places nodes and keys on a ring; each key belongs to the next node clockwise. Adding or removing a node moves only the keys next to it, about 1/N of them.

Node A
Node B
Node C
Node D

Keys are hashed onto the same ring and owned by the next node. Virtual nodes give each server many ring positions for an even spread.

Quorum reads and writes

SymbolMeaningExample
NReplicas of each item3
WAcks needed for a write to succeed2
RReplicas consulted on a read2
14Durability

WAL, buffer pool and backups

How committed data survives a crash, why most reads never touch disk, and why replication isn't a backup.

Application write
Write-ahead logDurable, sequential record of the change
Data pagesFlushed to disk later

After a crash, the database replays the WAL to recover every committed transaction. The same log feeds replicas and point-in-time recovery.

The buffer pool
SQL query
Buffer poolHot pages in RAM
Disk / SSD

Backups, RPO and RTO

Backup techniques

  • Full and incremental backups
  • Storage snapshots
  • WAL archiving → point-in-time recovery
  • Encrypted, cross-region copies

Questions to answer

  • How much data can we lose?
  • How fast must we be back?
  • Have we actually tested a restore?
  • Can we undo an accidental DELETE?

RPO · recovery point objective

The maximum data loss you accept, in time. “We can lose at most 5 minutes.”

RTO · recovery time objective

The maximum time to restore service. “Back within 1 hour.”

15Production changes

Migrations, deletes, archival and security

Large tables in production need careful changes, clear data lifecycles and real protection.

Zero-downtime schema migration (expand → contract)

  1. Expand

    Add the new column or table in a backward-compatible way.

  2. Dual-compatible code

    Deploy code that writes both and reads either representation.

  3. Backfill

    Migrate existing rows in small, throttled batches.

  4. Switch

    Move reads and writes to the new representation.

  5. Verify

    Check data, metrics and errors.

  6. Contract

    Remove the old schema in a later release.

Soft delete vs hard delete

Hard delete

  • DELETE FROM users WHERE id = 42;
  • The row is gone
  • Simple queries; meets erasure requests

Soft delete

  • UPDATE users SET deleted_at = NOW() WHERE id = 42;
  • Recoverable and auditable
  • Every query must filter deleted rows

Hot, warm and cold data

HotPrimary DB, frequent access
WarmArchive tables, cheaper storage
ColdObject storage, long-term archive

Security

Access

  • Least-privilege users per service
  • Private networking, no public endpoint
  • Secret rotation
  • Audited admin access

Data

  • TLS in transit, encryption at rest
  • Encrypted backups
  • Protect and minimise PII
  • Retention policies
16Scaling strategy

The database scaling ladder

Sharding is the last rung, not the first. Climb in order and measure at every step.

  1. Measure the bottleneck

    CPU, I/O, locks, cache hit rate, slow queries, connections.

  2. Fix inefficient queries

    N+1 queries, SELECT *, missing filters.

  3. Improve the schema

    Right types, constraints, normalisation.

  4. Add the right indexes

    From real query patterns.

  5. Pool connections

    Bounded pools, or a pooling proxy.

  6. Cache hot reads

    Redis in front of expensive or popular queries.

  7. Scale vertically

    A bigger machine is often the cheapest fix.

  8. Add read replicas

    For read-heavy traffic.

  9. Partition large tables

    By time or range.

  10. Archive cold data

    Keep the primary lean.

  11. Shard

    When one primary can't handle the writes or the data size.

17Case study

A ticket booking database

A high-concurrency booking platform is a good example of using several stores, each for what it does best.

Users
Booking service
PostgreSQLbookings + payments
Redisseat holds + cache
Searchmovie discovery
Analyticsreporting
Core schemasql
CREATE TABLE shows (
  id BIGINT PRIMARY KEY, movie_id BIGINT NOT NULL, theatre_id BIGINT NOT NULL,
  screen_id BIGINT NOT NULL, start_time TIMESTAMPTZ NOT NULL
);

CREATE TABLE show_seats (
  show_id BIGINT NOT NULL REFERENCES shows(id),
  seat_id TEXT   NOT NULL,
  status  TEXT   NOT NULL DEFAULT 'AVAILABLE',   -- AVAILABLE | HELD | BOOKED
  price   NUMERIC(10,2) NOT NULL,
  version INT    NOT NULL DEFAULT 0,
  PRIMARY KEY (show_id, seat_id)
);

CREATE TABLE bookings (
  id BIGINT PRIMARY KEY, user_id BIGINT NOT NULL, show_id BIGINT NOT NULL,
  status TEXT NOT NULL, total_amount NUMERIC(10,2) NOT NULL,
  idempotency_key TEXT UNIQUE                        -- safe retries
);

CREATE TABLE booking_seats (
  booking_id BIGINT NOT NULL REFERENCES bookings(id),
  show_id BIGINT NOT NULL, seat_id TEXT NOT NULL,
  UNIQUE (show_id, seat_id)                          -- a seat can be sold once, ever
);

Final guard against double booking

Optimistic conditional updatesql
UPDATE show_seats
SET    status = 'BOOKED', version = version + 1
WHERE  show_id = :showId AND seat_id = :seatId
  AND  status = 'AVAILABLE' AND version = :expectedVersion;
-- 0 rows updated → another transaction changed the seat first
Alternative: pessimistic locksql
BEGIN;
SELECT status FROM show_seats
WHERE  show_id = :showId AND seat_id = :seatId
FOR UPDATE;
-- verify AVAILABLE, then:
UPDATE show_seats SET status = 'BOOKED' WHERE show_id = :showId AND seat_id = :seatId;
COMMIT;

Redis still helps: a short-lived hold (SET show:992:seat:A10:lock <token> NX PX 300000) keeps the seat during checkout and absorbs contention. The database, with its conditional update and the UNIQUE (show_id, seat_id) constraint, is what guarantees a seat is sold once.

18Production

Failures and metrics

Good design covers what happens when the storage layer gets slow, fails or disagrees with itself.

FailureResponse
Primary failsPromote a healthy replica (managed failover); clients reconnect and retry safely.
Replica lagSend consistency-sensitive reads to the primary; alert on lag.
Connection exhaustionBounded pools, a pooling proxy, backpressure, timeouts.
Hot shardCache, replicas, key salting, split or re-key.
Slow queryEXPLAIN ANALYZE, indexes, statistics, lock waits.
DeadlockShort transactions, consistent lock order, retry the victim.
Disk fullCapacity alerts, archival, cleanup, emergency expansion.
Backup failureAlert immediately; regularly test real restores.
Region failureCross-region replicas and a rehearsed disaster-recovery runbook.

Metrics worth a dashboard

  • Query p50 / p95 / p99
  • QPS
  • CPU
  • Memory
  • Disk I/O
  • Disk space
  • Connections
  • Pool wait time
  • Cache hit ratio
  • Replication lag
  • Lock waits
  • Deadlocks
  • Slow queries
  • Rows scanned
  • Index usage
  • Transaction & rollback rate
  • Backup status
Interview prep

Database design interview questions, with answers

Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.

1

How do you choose between SQL and NoSQL?

Start from access patterns and correctness. If you need multi-row transactions, constraints, joins and ad-hoc queries (payments, orders, bookings), use SQL. If one access pattern dominates at very large scale (key lookups, huge write volumes, flexible documents, full-text search, time ranges), a specialised NoSQL store may fit better. Many systems use both.

2

When would you choose PostgreSQL, MongoDB, Cassandra or Redis?

PostgreSQL for transactional, relational data. MongoDB when records are naturally self-contained JSON documents with evolving fields. Cassandra for enormous write-heavy workloads with known query patterns and multi-node availability. Redis for sub-millisecond key-value access: cache, sessions, counters, rate limits, locks.

3

Why isn't Elasticsearch usually the source of truth?

It's optimised for search and ranking, not transactions; indexing is near-real-time rather than immediate; and its durability and consistency guarantees are weaker than a primary database's. Keep the truth in the database and sync to the search index via events or change-data-capture.

4

OLTP vs OLAP?

OLTP serves many small, low-latency reads and writes for live users, such as placing an order. OLAP runs large scans and aggregations over history for analytics and dashboards. They want different storage layouts (row vs column), so analytics usually moves to a warehouse like BigQuery, Snowflake or ClickHouse.

5

Normalisation vs denormalisation?

Normalisation stores each fact once, avoiding update anomalies, at the cost of joins. Denormalisation duplicates selected data to make hot reads cheap, at the cost of keeping the copies in sync. Normalise by default; denormalise specific read paths you've measured to be slow.

6

What are the ACID properties?

Atomicity: all of a transaction's changes happen or none do. Consistency: transactions keep the defined rules and constraints. Isolation: concurrent transactions don't interfere beyond the chosen isolation level. Durability: committed data survives crashes, typically via a write-ahead log.

7

Explain the isolation levels and the anomalies they prevent.

READ UNCOMMITTED allows dirty reads. READ COMMITTED prevents dirty reads but allows non-repeatable reads. REPEATABLE READ keeps rows stable within a transaction; phantoms depend on the database. SERIALIZABLE behaves as if transactions ran one at a time. Higher levels mean fewer anomalies and less concurrency.

8

What is a lost update, and how do you prevent it?

Two transactions read the same value, both modify it, and the second write silently overwrites the first. Prevent it with atomic updates (SET x = x + 1), pessimistic locks (SELECT … FOR UPDATE), optimistic locking with a version column, or a stricter isolation level.

9

Optimistic vs pessimistic locking?

Pessimistic locking locks the row up front (SELECT … FOR UPDATE), so other writers wait. It's good when conflicts are frequent. Optimistic locking lets everyone proceed and checks a version on write (UPDATE … WHERE version = 7); if no rows change, someone else won and you retry. It's good when conflicts are rare.

10

What is MVCC?

Multi-version concurrency control keeps several versions of a row, so readers see a consistent snapshot while writers create new versions, and reads don't block writes. PostgreSQL and MySQL InnoDB use it. Writers still lock rows against other writers, and old versions need cleanup (VACUUM, purge).

11

Explain the CAP theorem correctly.

When a network partition separates nodes, a distributed system must choose between consistency (refuse or delay requests it can't answer correctly) and availability (answer from whatever data it has). Without a partition you can have both; then the real trade-off is latency vs consistency, as PACELC puts it.

12

What is a database index, and why does it slow writes?

A separate structure, usually a B-tree, that maps column values to rows so lookups don't scan the table. Every INSERT, UPDATE or DELETE must update each affected index too, and indexes take storage, so add the ones your real queries need, not every possible one.

13

What is a composite index, and why does column order matter?

An index on several columns, such as (user_id, status). It's sorted by the first column, then the second, so it helps queries that filter on user_id, or on user_id and status, but not queries on status alone: the leftmost-prefix rule.

14

What does EXPLAIN ANALYZE show?

The plan the optimiser chose (sequential vs index scan, join type and order) together with actual row counts and timings. Look for sequential scans on big tables, estimates far from actual rows, expensive sorts and nested loops over large inputs.

15

Why do applications use connection pools, and how can autoscaling exhaust connections?

Opening a database connection is expensive, and each one uses database memory. A pool reuses a bounded set. But 200 autoscaled instances × 100 pooled connections is 20,000 connections, far more than most databases handle, so size pools globally or put a proxy like PgBouncer or RDS Proxy in front.

16

Single-leader vs multi-leader vs leaderless replication?

Single-leader: one primary takes writes and followers copy them; simple and the common default. Multi-leader: several nodes accept writes, useful across regions, but you must resolve conflicts. Leaderless (Dynamo-style): clients write to and read from several replicas with quorums; highly available, but you reason about versions and repairs.

17

Synchronous vs asynchronous replication?

Synchronous waits for a replica to confirm before acknowledging the write: stronger durability, higher latency. Asynchronous acknowledges immediately: fast, but replicas lag, and a failover can lose the newest writes. Many setups use semi-synchronous: wait for one replica, the rest async.

18

How do you solve read-after-write inconsistency with replicas?

Route a user's reads to the primary for a short time after they write, read from the primary for consistency-sensitive screens, track the replication position and only use replicas that have caught up, or use a database that offers read-your-writes sessions.

19

Partitioning vs sharding?

Partitioning splits a dataset into pieces, for example by month, often inside one database server. Sharding places those pieces on different servers so storage and write throughput scale horizontally. Sharding is partitioning across machines.

20

Hash vs range sharding, and what makes a good shard key?

Hash sharding spreads keys evenly but makes range queries scatter across shards. Range sharding keeps ranges together but risks hot spots, for example all new data landing on the latest range. A good key has high cardinality, spreads traffic evenly, and matches the most common query so most requests touch one shard.

21

What is a hot shard, and how do you fix it?

One shard gets far more traffic than the others, usually a celebrity or a skewed key. Fixes: cache its hot reads, add read replicas, salt the key (user:123#0..9), split that partition, precompute popular data, or choose a better shard key.

22

What is consistent hashing, and why virtual nodes?

Nodes and keys are hashed onto a ring; each key belongs to the next node clockwise, so adding or removing a node moves only about 1/N of the keys. Virtual nodes give each server many points on the ring, which evens out load and spreads a failed node's keys across many servers.

23

What are N, R and W in quorum systems?

N is the number of replicas, W the acknowledgements a write needs, and R the replicas a read consults. If R + W > N, read and write sets overlap, so a read normally sees the latest write. Real guarantees also depend on versioning, sloppy quorums and repair.

24

What is a write-ahead log?

Before changing data pages, the database appends the change to a sequential, durable log and fsyncs it at commit. After a crash it replays the log to recover committed transactions. The same log feeds replication and point-in-time recovery.

25

Replication vs backup, and what are RPO and RTO?

Replication copies every change, including an accidental DROP TABLE, so it's not a backup. Backups are point-in-time copies you can restore. RPO is how much data you can afford to lose (for example 5 minutes); RTO is how long recovery may take (for example 1 hour). Test restores regularly.

26

How would you run a zero-downtime schema migration?

Expand and contract: add the new column or table in a backward-compatible way, deploy code that writes both and reads either, backfill old rows in small batches, switch reads, verify, and only later remove the old schema. Avoid one huge locking migration.

27

How would you scale a read-heavy vs a write-heavy database?

Read-heavy: indexes, caching, read replicas, denormalised read models and CDNs for public data. Write-heavy: batch writes, simplify indexes, partition, move work to queues, choose a write-optimised store (LSM-based like Cassandra) where it fits, and eventually shard by a key that spreads writes evenly.

28

How would you prevent double seat booking in the database?

Guard the final write with a conditional update (UPDATE … WHERE status = 'AVAILABLE' AND version = :v, and check that one row changed) or a SELECT … FOR UPDATE inside a short transaction, plus a unique constraint on (show_id, seat_id) in the bookings table. Use a Redis hold for the fast UX, and the database for correctness.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

Payments, orders and bookings need multi-row transactions and constraints. Which store fits best?

Reference

Database design glossary

The terms from this guide, in one line each.

OLTP / OLAP
Transactional workloads for live users vs analytical scans over history.
ACID
Atomicity, consistency, isolation, durability: the transaction guarantees.
Isolation level
How much concurrent transactions can see of each other's work.
MVCC
Keeping row versions so readers see a snapshot without blocking writers.
Index
A sorted structure (usually a B-tree) that finds rows without a full scan.
Replica lag
How far a replica trails the primary.
Sharding
Splitting data across several database servers by a shard key.
Hot shard
A shard getting disproportionate traffic.
Quorum
The number of replicas that must agree for a read (R) or write (W) to count.
WAL
Write-ahead log: changes are logged durably before data pages are updated.
RPO / RTO
Maximum acceptable data loss / maximum acceptable recovery time.
Expand–contract
A migration pattern: add the new schema, move over, then remove the old one.
Summary

Key takeaways

  1. Choose the database from access patterns, transaction needs and consistency, not from what's popular.
  2. Relational by default for money, inventory and bookings; specialised stores for the access patterns they were built for.
  3. Know your isolation level, and prevent lost updates with atomic updates, locks or version checks.
  4. Indexes speed reads and cost writes. Design them from real queries and check with EXPLAIN ANALYZE.
  5. Replicas scale reads but lag, so route read-after-write traffic deliberately.
  6. Shard last, with a key that spreads load and keeps common queries on one shard.
  7. Replication is not backup. Define RPO and RTO and test restores.
Questions

Database design: frequently asked questions

How should I choose a database in a system design interview?

List the access patterns first: read/write ratio, point lookups vs ranges vs search, transaction and consistency needs, relationships, data size and QPS. Then pick the store that fits, commonly a relational database for core transactional data plus specialised stores (cache, search, analytics) where needed, and explain the trade-off.

What is the difference between partitioning and sharding?

Partitioning splits data into smaller pieces, often within one database server. Sharding distributes those pieces across multiple servers so storage and write capacity scale horizontally.

What is database replication?

Replication keeps copies of data on multiple nodes. It improves availability (fail over to a replica), durability (more copies) and read scalability (serve reads from replicas), at the cost of possible replica lag.

What is a hot shard?

A hot shard receives far more reads or writes than the others, usually because of a skewed shard key or a celebrity entity, so it becomes a bottleneck while other shards sit idle.

Is NoSQL faster than SQL?

Not inherently. NoSQL stores are fast for the access patterns they're designed around, often by giving up joins or multi-row transactions. A well-indexed relational database is very fast for most workloads and scales further than many people assume.

When should I shard a database?

Only after query tuning, indexes, connection pooling, caching, vertical scaling, read replicas, partitioning and archiving are no longer enough, typically when write throughput or data size exceeds what one primary can handle.

Next topicMessage Queues

Move slow work off the request path: Kafka, RabbitMQ, consumer groups, ordering, retries, DLQs and exactly-once myths.

Go deeperSee databases inside complete designs

Learn how databases, caching, load balancing, queues, rate limiting, locking and scaling work together in complete interview-style architectures.

  • SQL
  • NoSQL
  • Indexes
  • Replication
  • Sharding
  • BookMyShow
Explore the book

Last reviewed 18 November 2026