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
Ten database families
Each family is optimised for a different access pattern. Know what each is built for and what it gives up.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Which database should you use?
Start from the access pattern, then pick the family built for it.
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 form | Rule |
|---|---|
| 1NF | Atomic values: no repeating groups or lists in a column. |
| 2NF | 1NF, and no column depends on only part of a composite key. |
| 3NF | 2NF, and no column depends on another non-key column. |
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.
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 doesBASE
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.
Transaction isolation levels
Isolation decides which effects of concurrent transactions you can observe. Stricter means fewer anomalies and less concurrency.
| Level | Dirty read | Non-repeatable read | Phantom read | Concurrency |
|---|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible | Highest |
| READ COMMITTED | Prevented | Possible | Possible | High |
| REPEATABLE READ | Prevented | Prevented | Depends on DB | Medium |
| SERIALIZABLE | Prevented | Prevented | Prevented | Lowest |
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.
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
BEGIN;
SELECT * FROM seats WHERE id = 10 FOR UPDATE; -- others wait here
UPDATE seats SET status = 'BOOKED' WHERE id = 10;
COMMIT;UPDATE seats
SET status = 'BOOKED', version = version + 1
WHERE id = 10 AND version = 7; -- affected rows = 0 means a conflictMVCC: multi-version concurrency control
A keeps reading its consistent snapshot (version 1) while newer transactions see version 2. Readers don't block writers.
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
| Model | What the client gets |
|---|---|
| Strong (linearizable) | Reads always reflect the latest committed write. |
| Bounded staleness | Reads may lag, but only by at most X seconds or versions. |
| Causal | Causally related operations are seen in order. |
| Read-your-writes | You always see your own updates. |
| Monotonic reads | Once you've seen a newer value, you never see an older one. |
| Eventual | Replicas may differ for a while, then converge. |
Indexes and query plans
Indexes let the database find rows without reading the whole table. The optimiser decides whether to use them.
SELECT * FROM users WHERE email = '[email protected]';
-- may scan millions of rows to find oneCREATE 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
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
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
Connection pooling
Opening a database connection per request is slow and eats database memory. Reuse a bounded set instead.
Replication
Keep copies of the data on several nodes for availability, durability and read capacity.
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
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.
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
| Symbol | Meaning | Example |
|---|---|---|
| N | Replicas of each item | 3 |
| W | Acks needed for a write to succeed | 2 |
| R | Replicas consulted on a read | 2 |
WAL, buffer pool and backups
How committed data survives a crash, why most reads never touch disk, and why replication isn't a backup.
After a crash, the database replays the WAL to recover every committed transaction. The same log feeds replicas and point-in-time recovery.
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.”
Migrations, deletes, archival and security
Large tables in production need careful changes, clear data lifecycles and real protection.
Zero-downtime schema migration (expand → contract)
Expand
Add the new column or table in a backward-compatible way.
Dual-compatible code
Deploy code that writes both and reads either representation.
Backfill
Migrate existing rows in small, throttled batches.
Switch
Move reads and writes to the new representation.
Verify
Check data, metrics and errors.
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
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
The database scaling ladder
Sharding is the last rung, not the first. Climb in order and measure at every step.
Measure the bottleneck
CPU, I/O, locks, cache hit rate, slow queries, connections.
Fix inefficient queries
N+1 queries, SELECT *, missing filters.
Improve the schema
Right types, constraints, normalisation.
Add the right indexes
From real query patterns.
Pool connections
Bounded pools, or a pooling proxy.
Cache hot reads
Redis in front of expensive or popular queries.
Scale vertically
A bigger machine is often the cheapest fix.
Add read replicas
For read-heavy traffic.
Partition large tables
By time or range.
Archive cold data
Keep the primary lean.
Shard
When one primary can't handle the writes or the data size.
A ticket booking database
A high-concurrency booking platform is a good example of using several stores, each for what it does best.
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
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 firstBEGIN;
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.
Failures and metrics
Good design covers what happens when the storage layer gets slow, fails or disagrees with itself.
| Failure | Response |
|---|---|
| Primary fails | Promote a healthy replica (managed failover); clients reconnect and retry safely. |
| Replica lag | Send consistency-sensitive reads to the primary; alert on lag. |
| Connection exhaustion | Bounded pools, a pooling proxy, backpressure, timeouts. |
| Hot shard | Cache, replicas, key salting, split or re-key. |
| Slow query | EXPLAIN ANALYZE, indexes, statistics, lock waits. |
| Deadlock | Short transactions, consistent lock order, retry the victim. |
| Disk full | Capacity alerts, archival, cleanup, emergency expansion. |
| Backup failure | Alert immediately; regularly test real restores. |
| Region failure | Cross-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
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.
1How 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.
2When 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.
3Why 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.
4OLTP 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.
5Normalisation 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.
6What 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.
7Explain 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.
8What 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.
9Optimistic 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.
10What 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).
11Explain 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.
12What 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.
13What 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.
14What 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.
15Why 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.
16Single-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.
17Synchronous 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.
18How 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.
19Partitioning 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.
20Hash 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.
21What 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.
22What 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.
23What 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.
24What 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.
25Replication 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.
26How 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.
27How 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.
28How 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.
Quick quiz
6 questions. Pick an answer to see why it's right or wrong.
Payments, orders and bookings need multi-row transactions and constraints. Which store fits best?
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.
Key takeaways
- Choose the database from access patterns, transaction needs and consistency, not from what's popular.
- Relational by default for money, inventory and bookings; specialised stores for the access patterns they were built for.
- Know your isolation level, and prevent lost updates with atomic updates, locks or version checks.
- Indexes speed reads and cost writes. Design them from real queries and check with EXPLAIN ANALYZE.
- Replicas scale reads but lag, so route read-after-write traffic deliberately.
- Shard last, with a key that spreads load and keeps common queries on one shard.
- Replication is not backup. Define RPO and RTO and test restores.
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.
Move slow work off the request path: Kafka, RabbitMQ, consumer groups, ordering, retries, DLQs and exactly-once myths.
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
Last reviewed 18 November 2026