Databases: data models, indexes and transactions
Foundations F05. What every design's database step needs: the relational model, the NoSQL families, B-trees vs LSM-trees, composite and covering indexes, ACID and the write-ahead log, isolation levels and their anomalies, the last-seat race, and choosing a database out loud. Each idea is told as a story you'll remember, with a lab that prices five index choices for one query.
Start here
Almost every design ends at a database, and the interviewer will ask three things about it: what shape is the data and which kind of database fits, how does the one important query stay fast, and what stops two users from breaking each other's writes. This page answers those three on a single machine. Copying data across machines (replication) and splitting it (sharding) are the next page.
It covers eight ideas: the relational model, the NoSQL families, the two storage engines underneath (B-trees and LSM-trees), indexes, transactions and ACID, isolation levels, handling the "last seat" race, and choosing a database out loud. Each is told as a story first.
Tatkal booking at 10 am
Picture a train-booking app when Tatkal opens at 10 am. Thousands of people want the same few berths in the same minute. One booking touches every idea on this page:
- Trains, coaches, berths, passengers and bookings are rows with keys that point at each other. (relational model)
- Your search history and session sit in a simple key-value store. (NoSQL families)
- Every seat change is written to disk in a way that survives a power cut and keeps up with the 10 am rush. (storage engines)
- Your PNR comes back instantly out of a billion bookings. (indexes)
- Money is debited and the berth is assigned together, or neither happens. (transactions)
- While you pay, other people see the berth as taken or free, never half-booked. (isolation)
- You and a stranger tap the last lower berth in the same second. One of you gets it. (concurrency control)
- Bookings live in one kind of database, search in another, tickets as PDFs in a third. (choosing)
This is a made-up app for teaching, not a description of how Indian Railways' systems work.
The relational model: tables, keys and joins
Store each fact once, in tables of rows with a primary key; link tables with foreign keys; let the database join them and enforce the rules with constraints.
The school admission register
A school keeps one admission register: roll number, name, father's name, address. Each fact is written once. The class attendance sheet and every exam mark sheet only write the roll number.
When a student's family moves house, the clerk changes one line in the admission register and every sheet is correct at once. If the address had been copied onto every mark sheet, someone would forget one, and the school would have two addresses for the same child. That is normalization: one fact, one place, everything else points to it.
- A table holds rows of the same shape. A primary key (an id) names each row uniquely.
- A foreign key is a column that holds another table's primary key: bookings.passenger_id → passengers.id. The database can refuse a booking for a passenger who doesn't exist.
- Constraints are rules the database enforces for you: NOT NULL, UNIQUE (one booking per berth per journey), CHECK (fare > 0), foreign keys.
- A join combines tables at query time: "bookings with passenger names for train 12627 on 5 Nov".
- Normalize first (each fact in one place). Denormalize on purpose when a hot read needs data from many tables: copy the train name into the booking row, and accept that you must keep the copy in step.
SQL lets you ask questions you didn't plan for, which is why it stays the default for core business data.
GitHub runs on MySQL: in December 2023 it described more than 1,200 MySQL hosts in 50+ clusters, over 300 TB of data and 5.5 million queries a second. Relational databases are not "small-scale only"; they scale with replicas and by splitting data, which is the next page.
In an interview, write the core tables in a few lines each: users(id, name), trains(id, number), bookings(id, user_id, train_id, journey_date, berth, status) with UNIQUE(train_id, journey_date, berth).
- Joins and constraints are easy on one machine and hard once data is split across many; designs that will shard keep related rows on the same shard (for example, everything for one workspace).
- Denormalized copies make reads fast and writes harder: every copy must be updated, often asynchronously, so some readers see stale data for a while.
Core entities with relationships and money go in a relational database: normalized tables, foreign keys, and a UNIQUE constraint that makes double-booking impossible at the data layer.
Copying the same field into many tables "for speed" without saying how the copies stay in step. Interviewers ask what happens when the source changes.
Key-value, document, wide-column, graph: shape data by how you read it
"NoSQL" is four different shapes: key-value (get by key), document (one nested record per thing), wide-column (a partition of rows kept sorted), graph (things and links); each trades ad-hoc queries and joins for a fast, predictable path for the queries you planned.
Four ways to keep things at a railway station
- The cloakroom: you hand over a bag and get token 417. To get it back you say "417". The clerk never looks inside. That's key-value.
- The clinic's patient file: everything about one patient (visits, reports, prescriptions) in one folder. Open the folder, you have it all. That's a document.
- The milkman's register: one page per house, entries in date order down the page. "What did flat 3B take this month?" is one page, read top to bottom. That's wide-column: the page is the partition, the date is the sort order.
- The family tree at a wedding: "how is the bride's cousin related to the groom's uncle?" You follow lines from person to person. That's a graph.
Each is perfect for one way of asking and clumsy for others. Nobody asks the cloakroom clerk for "all red bags".
- Key-value (Redis, DynamoDB with a simple key): get, put, delete by key. Fastest and simplest; no queries on the value.
- Document (MongoDB, Firestore): a JSON-like record per item, with nested lists. Great when you read a whole aggregate at once (an order with its items). Joins across documents are weak or manual.
- Wide-column (Cassandra, ScyllaDB, Bigtable, and DynamoDB tables with a sort key): rows grouped by a partition key and kept sorted by a clustering or sort key inside it. "Latest 50 messages in channel X" is one partition read in order. You design one table per query.
- Graph (Neo4j and similar): nodes and edges, built for many-hop traversals (friends of friends, fraud rings).
The line is blurry now: PostgreSQL stores and indexes JSON, and DynamoDB supports transactions. Decide by access pattern, not by the label.
DynamoDB: the partition key is hashed to choose a partition, and items with the same partition key are stored together, sorted by sort key (AWS docs). On Prime Day 2025 Amazon's DynamoDB use peaked at 151 million requests a second with single-digit-millisecond responses (AWS, Aug 2025).
Discord stores trillions of messages partitioned by channel and a time bucket, so "recent messages in this channel" is one partition read. In 2023 it moved from 177 Cassandra nodes to 72 ScyllaDB nodes; a recurring problem was hot partitions, where one busy channel's bucket got so much traffic it slowed the cluster (InfoQ, Jun 2023).
- Key-based stores scale out almost linearly because each request touches one partition; the price is that you must know your queries up front and add a new table or index for each new one.
- A poorly chosen partition key (one celebrity, one busy channel) puts too much traffic on one partition: a hot key.
Messages are read as "latest N in a channel", so a wide-column table keyed by (channel_id, bucket) with message_id as the sort key serves that in one partition read; I'd watch for hot channels.
Saying "NoSQL because it scales" without naming the access pattern and the key. Pick the key from the query, or the database can't help you.
Under the hood: B-trees and LSM-trees
A B-tree keeps data in sorted pages and updates them in place (steady reads); an LSM-tree appends writes to memory and a log, then merges sorted files in the background (cheap writes, reads may check several files).
The shopkeeper's ledger and the day notebook
Old Ramesh-ji keeps one big ledger, sorted by customer name. For every sale he finds the right page and writes the entry there. Finding any customer is quick, but at Diwali rush he's flipping pages all day.
His son does it differently. During the day he jots every sale, in order, in a small notebook. It's lightning fast. Each night he merges the notebook into a fresh sorted ledger and throws the old ones away. Looking someone up during the day means checking today's notebook and then the ledgers, newest first. Ramesh-ji is a B-tree. His son is an LSM-tree.
- Both first write the change to a log on disk (a write-ahead log), so a crash loses nothing that was committed.
- B-tree (PostgreSQL, MySQL InnoDB, most relational databases): sorted fixed-size pages (8 KB in PostgreSQL, 16 KB in InnoDB) in a shallow tree. A lookup reads a handful of pages; real indexes with millions of rows are four or five levels deep. A write finds its page and changes it in place: random page writes.
- LSM-tree (RocksDB, Cassandra, ScyllaDB, LevelDB): writes go to an in-memory table; when full it's flushed as an immutable sorted file (SSTable); compaction merges files in the background, dropping overwritten and deleted keys. Reads check memory, then files from newest to oldest; Bloom filters skip files that can't contain the key.
- The trade-off has three parts: write amplification (bytes written per byte of data), read amplification (places a read must look) and space amplification. B-trees favour reads; LSMs favour writes and compress well, and pay in background compaction.
Meta moved its main MySQL user database (UDB, the social graph) from InnoDB, a B-tree engine, to MyRocks, MySQL on RocksDB (an LSM). The migration finished in 2017; the VLDB 2020 paper reports UDB instance size 62.3% smaller than compressed InnoDB and fewer than half the database servers. To limit the LSM read penalty they leaned on Bloom filters kept in memory.
RocksDB's own docs describe the knob: leveled compaction saves space but writes more; universal compaction writes less but uses more space and reads.
- B-tree: predictable reads and range scans, mature tooling; heavy random writes and many indexes slow it down.
- LSM: high write throughput and compact storage; reads of missing or old keys and background compaction can cause latency spikes if not tuned.
For a write-heavy append workload like events or messages I'd use an LSM-based store; for transactional data with many secondary-index reads, a B-tree relational database.
Saying LSM-trees have no write amplification. They avoid random in-place writes, but compaction rewrites data several times; the win is sequential I/O and compression, not zero rewriting.
Indexes: fast reads, paid for on every write
An index is a sorted copy of some columns pointing back to the rows; it turns "read everything" into "walk a few pages", but every insert must update every index, and a multi-column index only helps queries that use its leading columns.
The phone directory
The old phone directory is sorted by surname, then first name. Finding "Reddy, Trinath" is quick: open near R, then T. Finding every "Trinath" in the city is hopeless: they're scattered across every surname. The order of the columns decides which questions are fast.
If the directory already prints the phone number next to the name, you never have to visit the house to ask. That's a covering index. And every time someone new gets a phone, the printer must slot them into the right place, in every directory edition that exists. That's the write cost.
- Without an index, the database reads the whole table (a sequential scan). With a B-tree index it walks from the root to a leaf, then follows pointers to the rows.
- Composite index (a, b): sorted by a, then by b inside each a. It serves WHERE a = ?, and WHERE a = ? ORDER BY b, but not WHERE b = ? on its own. Rule: equality columns first, then the range or sort column.
- Covering index: add the columns the query returns (PostgreSQL INCLUDE) so the answer comes from the index alone, an index-only scan.
- Selectivity: an index helps when it narrows to few rows. For "status = active" on 90% of rows, a scan is cheaper and the planner will choose one.
- Every index costs space and slows INSERT, UPDATE and DELETE. Index the queries you'll run, and drop indexes nobody uses.
PostgreSQL's docs: equality constraints on the leading columns, plus one range on the next column, limit how much of a multi-column index is scanned; "multicolumn indexes should be used sparingly", and more than three columns rarely help. Version 18 added skip scan, which can use a later column when the first has few distinct values; it doesn't rescue a wrong order in general.
Depth stays tiny: with about 200 entries per 8 KB page, 100 million rows need four levels. "Real world indexes with millions of records have a tree depth of four or five" (Use The Index, Luke).
- Each index speeds some reads and slows all writes to the table; on a write-heavy table, three useful indexes beat eight "just in case" ones.
- Covering indexes save table reads but make the index bigger and only help when the table changes slowly enough for index-only scans.
The hot query is a user's latest orders, so I'd add a composite index on (user_id, created_at DESC): it matches the WHERE and the ORDER BY, so one tree walk returns 20 rows with no sort.
Indexing every column one by one. Two single-column indexes don't make a composite one, and each extra index taxes every write.
Try it: Which index? One query, five choices
A screen shows one user's latest orders. Pick an index and see how many rows the database looks at, how long one query takes, and what every insert pays to keep the index. Then try the other presets: a busy chat channel, and a write-heavy log with too many indexes.
A food app's orders table: 100M rows, about 50 orders per user. The My Orders screen shows the latest 20 with status and total, 20,000 times a second at the peak of a sale.
The query: WHERE user_id = ? ORDER BY created_at DESC LIMIT 20
| What we're sizing | Number | How we got it | So we decide | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 · Read: one query | |||||||||||||||||||||||||||
| (user_id)The index finds all rows for this key quickly, but then fetches every one of them from the table and sorts them to keep the newest few. | 50 looked at · 5.1 ms | tree depth = ⌈log200(100M)⌉ = 4 levels (inner levels cached) 50 entries for this user_id → 1 leaf page + 50 table rows, then sort and keep 20 (1 + 50) × 0.1 ms = 5.1 ms | 5.1 ms per query and it stays flat as the table grows. Good enough for this screen. | ||||||||||||||||||||||||
| 2 · Write: what every insert pays | |||||||||||||||||||||||||||
| Index upkeepEvery index is a second, sorted copy of some columns. Each insert must find its place in every one of them and log the change. | 8.0K index updates/s | indexes per insert = 1 primary key + 2 other + this one = 4 2.0K inserts/s × 4 = 8.0K index entries written per second storage: table 20.0 GB + all indexes ≈ 9.60 GB (this one 2.40 GB) | Write cost is modest at this rate: the index pays for itself. Still drop indexes no query uses. | ||||||||||||||||||||||||
| 3 · All five side by side | |||||||||||||||||||||||||||
| |||||||||||||||||||||||||||
| 4 · Verdict for these numbers | |||||||||||||||||||||||||||
| Our pick | (user_id, created_at) INCLUDE (…)The composite index already finds the 20 rows without sorting, but at 20K queries a second that's still 400K random table reads a second. Add the columns the screen shows with INCLUDE so the index alone answers the query: a covering index, bigger on disk, much less I/O. | ||||||||||||||||||||||||||
Try: on My orders, compare (user_id) with (user_id, created_at); then flip the column order and watch the cost jump. On Chat channel history, the single-column index has to fetch 2M rows to show 50. On Click log, reads are cheap with any good index, but eight indexes on 200,000 inserts a second are the bill. Constants are rounded, typical teaching values: 8 KB pages, 200 entries per index page, 0.1 ms per uncached page read, 500 MB/s sequential. Real planners also use caches, statistics and tricks such as PostgreSQL 18's skip scan, so measure with EXPLAIN ANALYZE.
Transactions and ACID: all or nothing, and it stays done
A transaction groups several changes so they all happen or none do (atomicity), keep your rules true (consistency), don't trip over other transactions (isolation) and survive a crash once committed (durability).
Sending money home, and the power cut
You move ₹5,000 from your savings to your mother's account. That's two changes: minus 5,000 here, plus 5,000 there. Halfway through, the bank's building loses power.
If only the first change survived, ₹5,000 has vanished. The bank's promise is that after the lights come back, either both changes happened or neither did. And once the app said "Transfer successful", no power cut can undo it. The bank keeps that promise by writing what it's about to do in a journal before touching any account, and replaying the journal after the cut.
- Atomicity: BEGIN … COMMIT; any failure before COMMIT rolls everything back. Atomic means all-or-nothing, not "concurrent-safe".
- Consistency: the database enforces your constraints (balance ≥ 0, unique berth); the rest of "consistent" is your application's logic. It is not the C in CAP.
- Isolation: concurrent transactions don't see each other's half-done work. How strictly is a setting (next concept).
- Durability: COMMIT returns only after the change is in the write-ahead log on disk. On restart the database replays the log (redo). One machine's disk can still die, so real durability also needs replicas or backups.
The log is the trick: writing it is sequential, so committing is cheap, and many small commits can share one disk flush.
PostgreSQL's WAL rule: changes to data files may be written only after the log records describing them are flushed to permanent storage. Only the log needs flushing at commit, not every changed page; after a crash, unapplied changes are redone from the log, and archived WAL allows restoring to any point in time (PostgreSQL docs).
In the booking app: INSERT the booking, UPDATE the berth to taken, INSERT the payment row, all in one transaction. If the payment insert fails, the berth is free again automatically.
- Transactions inside one database are cheap and should be your first tool; transactions across services or databases are expensive (two-phase commit) and usually replaced by sagas with compensation (a later page).
- Long transactions hold locks and old row versions; keep them short, and never wait on a user or a remote API inside one.
Booking the berth and recording the payment intent happen in one local transaction; the call to the payment provider happens outside it, with an idempotency key, and a second transaction records the result.
Holding a database transaction open while calling a payment gateway. A slow gateway then holds your locks for seconds and the whole booking table backs up.
Isolation levels: how much of the others you can see
Isolation levels decide which anomalies concurrent transactions can cause; most databases default to a weaker level than serializable, and the same name means different things in different databases.
Two hostel wardens and the night-duty rule
A girls' hostel has a rule: at least one warden must be on duty at night. Tonight both Meena and Lata are on duty, and both feel unwell.
Meena opens the duty register: "Lata is on duty, so I can sign off." At the same moment Lata opens the register: "Meena is on duty, so I can sign off." Each change on its own was fine. Together, nobody is on duty. Neither overwrote the other's entry; each acted on a picture that the other was changing. That's write skew, and only the strictest isolation level stops it.
The anomalies, from mild to subtle:
- Dirty read: you see another transaction's uncommitted change, which it may roll back.
- Non-repeatable read: you read a row twice and get different values because someone committed in between.
- Phantom: you re-run a search and new rows match.
- Lost update: two read-modify-write cycles overlap and one overwrites the other (two clerks both set seats_left = 5 − 1).
- Write skew: two transactions read the same facts, then write different rows, together breaking a rule (the wardens).
The levels:
- Read committed: no dirty reads; each statement sees the latest committed data. PostgreSQL's default.
- Repeatable read, usually built as snapshot isolation: the transaction sees one snapshot from its start (MVCC keeps old row versions, so readers don't block writers). MySQL InnoDB's default is called repeatable read too, but its guarantees differ (see below).
- Serializable: the result equals some one-at-a-time order. PostgreSQL implements it as Serializable Snapshot Isolation, which aborts a transaction (SQLSTATE 40001) when it detects a dangerous pattern, so the app must retry.
PostgreSQL's docs: Read Committed is the default; Repeatable Read never shows phantoms in PostgreSQL but can still produce serialization anomalies; a concurrent update raises "could not serialize access due to concurrent update", and the application should retry the whole transaction.
The Hermitage test suite (Kleppmann, 2014) shows names don't match guarantees: PostgreSQL's "repeatable read" is snapshot isolation (prevents lost updates, allows write skew); MySQL InnoDB's "repeatable read" does not prevent lost updates in its tests; Oracle's "serializable" is actually snapshot isolation.
- Stronger isolation means more aborted or blocked transactions under contention; you pay in retries and throughput.
- Weaker isolation is fast but pushes correctness into your code: explicit locks, conditional updates and constraints.
PostgreSQL's default, read committed, allows lost updates and write skew. For the booking I'd rely on a conditional update plus a unique constraint; if a rule spans many rows, I'd run that transaction as serializable and retry on 40001.
Saying "it's in a transaction, so it's safe". A transaction at read committed still lets two bookings read "1 seat left" and both succeed.
The last lower berth: locks, versions and conditional writes
When two users race for one thing, make the database decide: a single conditional UPDATE, a row lock (pessimistic), or a version check that fails and retries (optimistic), with a unique constraint as the final guard.
The last lower berth at 10:00:01
Two people want the last lower berth for their parents. Both screens say "1 lower berth available". Both tap Book.
Option one: the booking clerk keeps a hand on the register while writing, and the second person waits in line (a lock). Option two: each person's form says "I saw version 7 of this berth"; the clerk accepts the first form, the berth becomes version 8, and the second form is returned: "this changed, please look again" (optimistic). Option three, the simplest: the clerk's rule is "write a name only if the berth is still blank". The second name never fits.
- Conditional update (often the best answer): UPDATE berths SET booking_id = ? WHERE id = ? AND booking_id IS NULL. Check the rows-affected count: 1 means you won, 0 means someone beat you. One statement, atomic, no explicit lock.
- Pessimistic locking: SELECT … FOR UPDATE inside a transaction locks the rows; others wait until you commit. Good when conflicts are common. Keep it short, lock rows in a consistent order, and expect the database to abort one side of a deadlock.
- Optimistic concurrency: store a version number; write only if it hasn't changed (WHERE version = 7, or a DynamoDB condition expression); on failure, re-read and retry. Good when conflicts are rare.
- Unique constraint as the backstop: UNIQUE(train_id, journey_date, berth) on confirmed bookings means even buggy code can't double-book.
- Holding a seat for minutes while the user pays is a different problem: a reservation row with an expiry, released by a timeout.
AWS's DynamoDB guide on optimistic locking: each item carries a Version attribute; the update has ConditionExpression "Version = :expected", increments it, and on ConditionalCheckFailedException the client re-reads and retries a capped number of times. AWS recommends it when conflicts are infrequent and retries are cheap.
PostgreSQL's FOR UPDATE prevents the selected rows from being "locked, modified or deleted by other transactions until the current transaction ends", and PostgreSQL detects deadlocks and aborts one of the transactions (PostgreSQL docs).
- Pessimistic locks waste nothing on retries but make users queue; with a hot row (the last berth at 10 am) the queue is the bottleneck.
- Optimistic writes never block, but under heavy contention most attempts fail and retry, multiplying load.
I'd book with one conditional UPDATE … WHERE booking_id IS NULL and check rows affected, backed by a unique constraint; for the payment hold, a reservation with a 10-minute expiry.
Read, check in application code, then write ("if seats_left > 0 then update"). Between the read and the write another request can do the same, and you've sold the berth twice.
Choosing a database out loud
Start from the access patterns and the guarantees each piece of data needs; default to a relational database for the core, add a specialised store only for a named query it serves better, and say how the copies stay in sync.
Moving into a new flat
When you move in, you don't put everything in one cupboard. Clothes go in the steel almirah, vegetables in the fridge, gold in the bank locker, and photos in an album you flip through by year. Each place is chosen by how you'll use the thing: daily, cold, safe, browsable.
But every extra place is one more key to carry and one more thing to keep track of. A sensible family starts with the almirah and adds the locker only when they have gold.
Ask four questions:
- How is it read and written? By key, by range in one partition, ad-hoc queries and joins, full-text, analytics over millions of rows?
- What must be guaranteed? Money and inventory need transactions and constraints; a like counter can be approximate.
- How big and how fast? Rows, bytes, reads and writes per second at the peak (the estimation page).
- What does the team already run well? Operating a database is a real cost.
Typical answers:
- Users, orders, payments, bookings: relational (PostgreSQL, MySQL).
- Very high-volume, key-shaped data (messages, events, sessions, carts): key-value or wide-column (DynamoDB, Cassandra, ScyllaDB).
- Text search: a search index such as Elasticsearch or OpenSearch, fed from the main database (a derived copy).
- Files, images, PDFs: object storage (S3); the database stores the URL.
- Hot reads: a cache in front (Redis), the caching page.
- Dashboards over huge history: a column-oriented warehouse, not the transactional database.
Notion (Oct 2021) kept PostgreSQL for its block data even at billions of rows, splitting it into 480 logical shards on 32 physical databases, keyed by workspace id so a workspace's blocks stay together. It considered DynamoDB and decided it was too risky for its use case.
Discord went the other way for messages: MongoDB, then Cassandra, then ScyllaDB, because its main query is "recent messages in one channel", which a partition per channel and time bucket serves directly.
- One general-purpose database is simpler to run and keep correct; several specialised stores each fit better but need sync pipelines (change data capture, events) and show stale data while they catch up.
- Choosing a scale-out NoSQL store early can lock you out of ad-hoc queries and transactions you'll want later; relational databases scale further than most interviews assume.
Bookings and payments in PostgreSQL for transactions and constraints; seat search served from a cache; tickets as PDFs in object storage. If messages or events reach hundreds of thousands of writes a second, a wide-column store keyed by the read pattern.
Naming a database without the reason ("I'll use MongoDB"). The interviewer wants the access pattern and guarantee that led to it.
Remember it
One line per idea. Read this the night before.
- The admission register: each fact once, keys point to it, constraints enforce the rules; denormalize on purpose.
- Cloakroom, patient file, milkman's register, family tree: key-value, document, wide-column, graph. Pick the key from the query.
- Ramesh-ji's ledger vs his son's notebook: B-tree for steady reads, LSM for heavy writes (compaction is the bill).
- The phone directory: composite index, equality columns first, then the sort; covering saves table reads; every index taxes writes.
- Money home in a power cut: atomic, consistent, isolated, durable; the write-ahead log makes commits cheap and crash-safe.
- Two wardens: read committed is the usual default; snapshot isolation still allows write skew; serializable means retries.
- The last lower berth: one conditional UPDATE and a unique constraint; locks when conflicts are common, versions when rare.
- Moving into a flat: relational core by default, a specialised store only for a named query, and say how copies stay in sync.
Check yourself
Answer out loud, then open.
Design the tables for a train-booking app and show how you prevent double-booking.
Core tables: users, trains, berths(id, train_id, coach, number), bookings(id, user_id, train_id, journey_date, berth_id, status).
- UNIQUE(train_id, journey_date, berth_id) on confirmed bookings: the database refuses a second one.
- Book with one conditional statement or insert; if it affects 0 rows or violates the constraint, tell the user the berth just went.
- Payment hold: a reservation row with an expiry, released by a timer.
Say it The constraint makes double-booking impossible; the conditional write makes losing the race a clean, fast answer.
A user's "My orders" page is slow on a 100M-row table. What index, and why that column order?
A composite index on (user_id, created_at DESC).
- Equality column first (user_id) narrows to one user's entries, which sit together.
- The sort column next means they're already in time order: read the first 20, no sort.
- (created_at, user_id) would be sorted by time first, so one user's rows are scattered across the whole index.
- If the page only needs status and total, INCLUDE them for an index-only scan.
B-tree or LSM-tree for an event log taking 200,000 writes a second, read rarely?
LSM-tree (RocksDB, Cassandra, ScyllaDB and similar).
- Writes go to memory and a sequential log, then are flushed as sorted files: no random page writes.
- Reads are rare, so checking several files (helped by Bloom filters) is acceptable.
- Compaction rewrites data in the background; budget disk bandwidth for it.
A B-tree would do a random leaf-page update per index per insert, which is the bottleneck at this rate.
What does each letter of ACID guarantee, and which one is commonly misunderstood?
Atomicity: all of the transaction's changes or none. Consistency: your constraints hold before and after. Isolation: concurrent transactions don't see each other's partial work, to a configurable degree. Durability: once committed, it survives a crash, via the write-ahead log.
Two common mix-ups:
- The C in ACID (rules hold) is not the C in CAP (every read sees the latest write across replicas).
- Atomicity is about failure (all or nothing), not about concurrency; that's isolation.
Two transactions both read "1 seat left" and both book it, even though each runs in a transaction. How?
At read committed (PostgreSQL's default) and even at snapshot isolation for some patterns, both can read the same state and both write.
- Read-then-write in application code is the bug: a lost update or write skew.
- Fixes: a conditional UPDATE … WHERE seats_left > 0 (or booking_id IS NULL) and check rows affected; SELECT … FOR UPDATE; a version check; or SERIALIZABLE with retries on 40001.
- Back it with a unique constraint so a bug can't oversell.
When would you choose optimistic over pessimistic concurrency control?
Optimistic when conflicts are rare and a retry is cheap: editing a profile, updating an item's stock in a large catalogue. No locks, no waiting; a version check fails now and then and the client retries.
Pessimistic when conflicts are common or a retry is expensive: the same hot row hit by many writers. Locks make them queue instead of all failing and retrying.
Say it Optimistic costs retries under contention; pessimistic costs waiting. I pick by how often two writers really collide.
The interviewer asks: "Why not just use MongoDB for everything?"
It depends on the data, so answer by access pattern:
- Orders and payments need multi-row transactions, constraints and ad-hoc queries: relational fits naturally.
- A product catalogue read as whole documents with varied attributes: a document store fits well.
- Messages read as "latest N per channel" at huge volume: a wide-column store keyed by channel.
Say it I default to PostgreSQL for the core and add a specialised store only for a query it serves better, with a named way to keep it in sync.
Where you'll use this in the series
- Uber: from tap to pickup · trip and driver tables, database choices, the ride state machine
- Back-of-envelope estimation · sizing rows, storage and writes per second before choosing a database
- APIs and real-time communication · cursor pagination is an index walk; idempotency keys need a unique constraint
- Replication and sharding · copying and splitting these databases across machines
- Consistency, CAP and quorums · the other C: what replicas agree on
- Ticketmaster: selling seats without double-booking · the last-berth race at stadium scale (coming)
- Payment system (Stripe) · transactions, constraints and ledgers (coming)
- Distributed cache / key-value store · building the key-value model yourself, LSM storage included (coming)
Sources
- Transaction isolation, PostgreSQL docs (checked Oct 2026)
- Write-Ahead Logging (WAL), PostgreSQL docs (checked Oct 2026)
- Indexes: introduction, PostgreSQL docs (checked Oct 2026)
- Multicolumn indexes, PostgreSQL docs (checked Oct 2026)
- Index-only scans and covering indexes, PostgreSQL docs (checked Oct 2026)
- Explicit locking, PostgreSQL docs (checked Oct 2026)
- MVCC introduction, PostgreSQL docs (checked Oct 2026)
- InnoDB transaction isolation levels, MySQL 8.4 Reference Manual (checked Oct 2026)
- Serializable Snapshot Isolation in PostgreSQL, Ports & Grittner, VLDB (2012)
- Hermitage: testing transaction isolation levels, M. Kleppmann (2014, checked Oct 2026)
- Core components of Amazon DynamoDB, AWS docs (checked Oct 2026)
- Optimistic locking with version number, Amazon DynamoDB docs (checked Oct 2026)
- AWS services scale to new heights for Prime Day 2025, AWS News Blog (Aug 2025)
- RocksDB Overview, RocksDB wiki (checked Oct 2026)
- MyRocks: LSM-Tree Database Storage Engine Serving Facebook's Social Graph, VLDB (2020)
- MyRocks: a space- and write-optimized MySQL database, Engineering at Meta (Aug 2016)
- Upgrading GitHub.com to MySQL 8.0, GitHub Blog (Dec 2023)
- Discord migrates trillions of messages from Cassandra to ScyllaDB, InfoQ (Jun 2023)
- Herding elephants: lessons learned from sharding Postgres at Notion, Notion (Oct 2021)
- The B-tree: anatomy of an index, Use The Index, Luke (checked Oct 2026)
- Data modeling, Hello Interview (third party, checked Oct 2026)
Checked October 2026. Database behaviour comes from the official PostgreSQL, MySQL, DynamoDB and RocksDB docs; company figures are as published on the dates shown (Notion 2021, GitHub 2023, Discord via InfoQ 2023, Meta's MyRocks paper 2020, AWS Prime Day 2025) and may have changed since. Hermitage results are from its test suite and depend on database versions. Lab constants (page size, entries per page, SSD read time, scan speed) are rounded, typical teaching values.
System Design Mastermind · Foundations
Series homeAll of Foundations
18 publishedStart here: the concepts every design uses, each told as a story you'll remember.
How a request travels: DNS, load balancers, gateways and open connections
Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.
The interview framework: requirements, numbers and scope before boxes
Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.
Back-of-envelope estimation: from users to servers in one minute
Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.
APIs and real-time communication: REST, gRPC, retries, webhooks and live updates
Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.
Databases: data models, indexes and transactions
Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.
Replication and sharding: copying and splitting your data
Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.
Caching: hit ratios, invalidation and stampedes
Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.
Consistency, CAP and quorums: what replicas promise
Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.
Coordination: clocks, leaders, locks and consensus
Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.
Queues and event streams
Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".
Idempotency, exactly-once and sagas
Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.
Scaling and performance
State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.
Reliability and disaster recovery
Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.
Observability and safe deployments
Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.
Security essentials for system design
Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.
Search, feeds and geo building blocks
Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.
Data pipelines: batch and stream
Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).
AI foundations: inference, RAG and agents
Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.