Interview Study Guide

Guide / System design Fundamentals

4. Databases at scale — indexing, big queries, transactions

Created · Updated · 9 min read

4.1 How indexes work#

  • B-tree / B+tree (Postgres, MySQL InnoDB default): sorted tree, O(log n) lookups, supports equality, ranges, ORDER BY, prefix LIKE 'abc%'. 100M rows ≈ 4 levels deep, so a lookup is a few page reads.
  • Hash index: equality only, no ranges.
  • LSM tree (Cassandra, RocksDB, ScyllaDB): writes go to memory + append-only log, flushed to sorted files (SSTables) and compacted. Very fast writes; reads may check several files (Bloom filters help).
  • GIN / inverted (Postgres JSONB, arrays, full-text), GiST / BRIN (BRIN = tiny index for naturally ordered data like timestamps in an append-only table), HNSW/IVF for vectors.
  • Clustered vs secondary: InnoDB stores rows inside the primary-key B-tree; secondary indexes point to the PK, so a secondary lookup is two tree walks. Postgres stores rows in a heap and all indexes point to the heap.

4.2 Index design rules#

  1. Composite index order = equality columns first, then range/sort column. For WHERE user_id = ? AND status = ? ORDER BY created_at DESC, index (user_id, status, created_at).
  2. Leftmost prefix rule: an index on (a, b, c) serves a, a,b, a,b,c — not b alone.
  3. Covering index: include all selected columns (INCLUDE in Postgres) so the query never touches the table (“index-only scan”).
  4. Partial index: WHERE status = 'PENDING' — small, fast index over the rows you actually query.
  5. Selectivity: indexing a boolean or low-cardinality column alone rarely helps; the planner will scan.
  6. Cost of indexes: each one slows writes and uses memory. Remove unused ones (pg_stat_user_indexes).
  7. Index killers: functions on the column (WHERE DATE(created_at) = ... → use a range or an expression index), leading wildcard LIKE '%abc', implicit type casts, OR across different columns (use UNION or separate indexes).

4.3 Fetching a few records from a huge table quickly#

  • Read the plan: EXPLAIN ANALYZE. Look for Seq Scan on big tables, row-estimate mismatches, and sort spills to disk.
  • Make the filter hit an index whose leading columns match the WHERE; make ORDER BY ... LIMIT match index order so the DB stops after N rows.
  • Use keyset pagination, never deep OFFSET.
  • Partition large time-based tables (orders_2026_11): queries with a date filter touch one partition (partition pruning); old partitions drop instantly instead of slow DELETEs.
  • Avoid SELECT *; fetch only needed columns (enables covering indexes, less I/O).
  • Fix N+1 queries (one query per row from an ORM loop) with joins, IN (...) batching, or DataLoader.
  • Keep statistics fresh (ANALYZE), tune work_mem for sorts, and use connection pooling (PgBouncer) so 1,000 app instances don’t open 1,000 × N connections.

4.4 Computing over millions of users’ orders#

The interview question: “Show each user’s total spend and the top 100 spenders across 2B orders in DynamoDB/MongoDB.” The answer is to never compute this on the request path from the OLTP store.

ApproachHowWhen
Pre-aggregate on writeOn each order event, increment user_totals[user_id] (atomic UPDATE ... SET total = total + ? or DynamoDB ADD)Running totals, counters, dashboards needing real-time
Stream processingOrders → Kafka/DynamoDB Streams → Flink/Kafka Streams → aggregates table or Redis sorted set (ZINCRBY)Real-time leaderboards, windowed metrics (last 1 h)
Batch ETL to warehouseCDC/export → S3 (Parquet) → Spark / BigQuery / Snowflake / ClickHouseAd-hoc analytics, monthly reports, ML features
Materialized viewsPostgres MATERIALIZED VIEW refreshed periodically, or a summary tableModerate scale inside SQL
MapReduce / scatter-gatherEach shard computes partial aggregates, a coordinator merges (sum of sums, merge top-K lists)Sharded OLTP when you must query live

Key points: aggregates must be idempotent (dedupe by order_id so replays don’t double-count); top-K across shards = each shard returns its top K, coordinator merges (approximate unless K is large enough); approximate algorithms (HyperLogLog for distinct counts, Count-Min Sketch for heavy hitters) trade exactness for tiny memory. Lambda architecture = batch for accuracy + stream for freshness; Kappa = stream only with replay.

4.5 Transactions and isolation#

ACID: Atomicity (all or nothing), Consistency (constraints hold), Isolation (concurrent transactions don’t see each other’s partial work), Durability (committed data survives crashes, via WAL).

Isolation levelPreventsStill allowsDefault in
Read uncommitted—Dirty readsRarely used
Read committedDirty readsNon-repeatable reads, phantoms, lost updatesPostgres, Oracle, SQL Server
Repeatable read / snapshot+ non-repeatable readsWrite skew (Postgres), phantoms in some enginesMySQL InnoDB
SerializableEverything— (retries on conflict, slower)CockroachDB, Spanner

Anomalies to name: lost update (two read-modify-writes overwrite each other — fix with SELECT ... FOR UPDATE, atomic UPDATE x = x - 1, or optimistic version check); write skew (two doctors both go off-call because each saw the other on call — fix with serializable or locking the rows that define the constraint).

Locking styles: pessimistic (SELECT ... FOR UPDATE, holds locks, good under high contention, risk of deadlocks) vs optimistic (UPDATE ... SET qty = qty - 1, version = version + 1 WHERE id = ? AND version = ?; 0 rows updated → retry; good under low contention). MVCC (Postgres, InnoDB) lets readers see a snapshot without blocking writers.

Inventory decrement the safe way: UPDATE inventory SET qty = qty - 1 WHERE sku = ? AND qty > 0 and check affected rows = 1. One statement, atomic, no oversell.

4.6 Schema changes and migrations at scale#

Never lock a big table in production. Use expand-and-contract: add nullable column → dual-write → backfill in batches → switch reads → drop old column. Tools: gh-ost / pt-online-schema-change (MySQL), CREATE INDEX CONCURRENTLY (Postgres).

4.7 Isolation anomalies with examples#

AnomalyExamplePrevented by
Dirty readT1 reads T2’s uncommitted balance, T2 rolls backRead Committed and above
Non-repeatable readT1 reads a row twice, T2 commits an update in between and the values differRepeatable Read and above
PhantomT1 runs WHERE price < 10 twice; T2 inserts a matching row between runsSerializable (Postgres RR also prevents it via snapshots; MySQL InnoDB uses gap locks)
Lost updateTwo transactions read qty=5, both write qty=4SELECT ... FOR UPDATE, atomic UPDATE qty = qty - 1, optimistic version check, or Serializable
Write skewTwo on-call doctors both see “2 on call” and both go off; now 0Serializable (SSI), or lock the guarding row, or a constraint

Defaults: Postgres Read Committed, MySQL InnoDB Repeatable Read. Pick the weakest level that preserves your invariant, and fix specific races with row locks or constraints instead of making everything Serializable. Serializable transactions can abort with serialization failures: retry the whole transaction.

4.8 MVCC and locking#

  • MVCC (multi-version concurrency control): each write creates a new row version; readers see a snapshot and never block writers. Cost: old versions must be cleaned (VACUUM in Postgres; undo log purge in MySQL); long transactions prevent cleanup and bloat tables.
  • Row locks: SELECT ... FOR UPDATE locks selected rows until commit (pessimistic); FOR UPDATE SKIP LOCKED lets many workers pull different rows from a job table without blocking each other (a simple queue); NOWAIT fails immediately instead of waiting.
  • Optimistic locking: UPDATE ... WHERE id=? AND version=?; if 0 rows updated, retry. Best when conflicts are rare.
  • Deadlocks: two transactions lock rows in opposite order. Prevent by locking in a consistent order, keeping transactions short, and retrying on deadlock errors.
  • Advisory locks (pg_advisory_xact_lock) serialise application-level critical sections per key.
  • Hot row: a single counter row updated by everyone serialises writes; shard the counter or aggregate asynchronously.

4.9 Reading query plans#

EXPLAIN (ANALYZE, BUFFERS) SELECT ... shows what the planner did and the real timings.

Look forMeaningFix
Seq Scan on a big table with a selective filterNo usable indexAdd an index on the filter column(s)
Estimated rows ≪ actual rowsStale statisticsANALYZE, extended statistics
Sort with external merge DiskSort spilled to diskIndex matching ORDER BY, raise work_mem
Nested Loop with a huge outer sideWrong join strategy or missing indexIndex the join column, rewrite
Index Scan then Heap Fetches highNot index-onlyCovering index (INCLUDE)
Rows Removed by Filter very largeIndex not selectiveComposite or partial index

Also watch N+1 queries from ORMs (1 query for orders + N for items): use joins or batched IN fetches. Use pg_stat_statements to find the top queries by total time.

Most asked questions#

1. How do indexes work and what are the downsides? A B-tree keeps keys sorted so lookups are O(log n); they speed reads but slow writes, use space, and can be ignored by the planner if not selective.

2. Composite index column order? Equality columns first, then range or sort column; the index serves queries that use a left prefix.

3. Explain ACID and isolation levels. Atomic, Consistent, Isolated, Durable; the levels trade anomalies for concurrency (table above).

4. How do you prevent overselling the last item? UPDATE stock SET qty = qty - 1 WHERE sku=? AND qty > 0 and check affected rows, or a reservation row with a unique constraint.

5. How do you paginate a huge table efficiently? Keyset pagination on an indexed unique order (REST API design).

6. How do you change a schema on a huge table with no downtime? Expand/contract: add nullable column, backfill in batches, dual-write, switch reads, drop old; use online schema-change tools (gh-ost, pt-osc, CREATE INDEX CONCURRENTLY).

Senior-level questions#

1. “A query is fast in staging and slow in production.” Data volume and distribution (plan differs), stale stats, parameter sniffing, missing index in prod, lock waits, cold cache, or bloat. Compare EXPLAIN ANALYZE on prod-sized data.

2. “Long transactions are hurting the database. How?” They hold locks and snapshots, preventing vacuum (bloat) and growing replication lag. Set idle_in_transaction_session_timeout, keep transactions short, never call external services inside a transaction.

3. “How do you build a job queue in Postgres?” Table with status; workers SELECT ... FOR UPDATE SKIP LOCKED LIMIT n, mark processing with a lease, delete or mark done; works to thousands/sec; use a real queue beyond that.

4. “Add an index to a 2 TB table without blocking writes.” CREATE INDEX CONCURRENTLY (Postgres) or online DDL in MySQL; monitor replication lag and disk; validate and retry on failure; ensure no long transaction blocks completion.

5. “Why is my count(*) slow and what are alternatives?” It scans an index or table under MVCC. Use approximate counts (pg_class.reltuples), maintained counter tables, or cached counts; avoid exact totals in pagination.

Quiz#

1. What is write skew and how do you stop it?

Two transactions read overlapping data, each updates different rows, and together they violate an invariant. Use Serializable isolation, lock the shared guard row, or enforce the invariant with a constraint.

2. What does SKIP LOCKED do?

It skips rows locked by other transactions so multiple workers can claim different rows concurrently.

3. Postgres default isolation level?

Read Committed.

4. Why can a long-running transaction slow down the whole database?

It pins old row versions (no vacuum), holds locks, and can increase replication lag.

5. Estimated rows 10, actual 2 million in EXPLAIN. What is wrong?

Stale or insufficient statistics leading to a poor plan: run ANALYZE or create extended statistics.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes