All modules

Databases and storage: interview questions

21 questions. Try answering out loud before you open the model answer.

1. We are building a marketplace with users, listings, orders and payments. Would you use a SQL or a NoSQL database?

Seniordata-modellingsqlnosql

What the interviewer is really testing

Whether you choose a store from the data, the queries and the numbers instead of from fashion, and whether you can say what each choice gives up. Interviewers also watch for candidates who treat it as one decision for the whole system.

Show the model answer, follow-ups and checklist

Model answer

I would not choose one database for the whole product. I would choose per dataset, from the queries and from what must never be wrong.

The core is relational. Placing an order touches the buyer, the listing’s stock and a payment record, and it must never sell an item twice or charge twice. That needs transactions across rows and constraints the database enforces. On scale, 5 million orders a month is about 2 per second on average, perhaps 50 at peak. One PostgreSQL primary with a couple of read replicas handles that with a great deal of room. So users, listings, orders and payments live there, normalized, as the system of record.

Then I look for data that does not fit.

  • Search over listings needs full text, filters and ranking. That goes in a search index, fed from the database.
  • Sessions and carts are read by one key at a high rate and are short-lived. Redis.
  • Listing photos are large and immutable. Object storage, with a row in the database for each.
  • Activity events such as views and clicks arrive at thousands per second, are append-only and are read by user and time. A log and a warehouse, or a wide-column store if the product reads them back.

Each extra store is another system to run and to keep consistent, so I add one only when a number or a query forces it.

What would change the core? If orders approached tens of thousands of writes per second, or had to be accepted in several regions, I would shard by buyer or move to a distributed SQL database. I would keep SQL and transactions. Moving orders to a key-value store would mean rebuilding constraints and joins by hand in application code.

Likely follow-ups

Listings have very different attributes in each category. Does that push you to a document database?
Not on its own. I would keep the common fields as columns and put the category-specific attributes in a JSONB column with an index, which PostgreSQL handles well. I would move listings to a document store only if their volume or query needs outgrew the relational database, and orders and payments would stay where they are.
Traffic grows a hundredfold and orders reach 20,000 writes per second. What changes?
One primary is no longer enough for the orders data. I would shard by a key that keeps an order's rows together, such as buyer id, or move to a distributed SQL database, so that I keep SQL and transactions inside a shard. Work that crosses shards, such as paying a seller, becomes an asynchronous step with a saga instead of one transaction.
Why not use DynamoDB from day one, since it is managed and scales?
It is a reasonable choice when the access patterns are known and stable, because every query has to be designed into the keys. A young product changes its queries often, and support tools and analysts need ad hoc access. I would be trading query flexibility and simple constraints for scale I do not need yet.
How do you keep the search index in step with the database?
The database is the source of truth. Changes flow to the index through change data capture or an outbox table, so the index lags by a second or so and can always be rebuilt. I would not write to both from the request handler, because a failure between the two writes leaves them different for good.

Common mistakes

  • Naming a database before stating the queries, the invariants and the scale.
  • Saying NoSQL scales without a number that shows one relational primary is not enough.
  • Treating the choice as one decision for the whole system instead of one per dataset.
  • Forgetting what is given up, such as joins, constraints, ad hoc queries and transactions across partitions.
  • Adding four stores to a design and ignoring the cost of operating and synchronising them.

A strong answer includes

  • Starts from access patterns, invariants and size, not from a product name
  • Puts orders and payments in a relational database and says why (transactions and constraints)
  • Gives a rough number showing the core data fits one primary with replicas
  • Identifies data that suits another store (search, sessions, images, event streams) and names the store
  • States what each extra store costs and how it stays consistent with the source of truth
  • Says what would trigger a change, and prefers sharding or distributed SQL over abandoning transactions

Revise: SQL vs NoSQL

2. A query on a 200 million row table filters by tenant, status and a date range, sorts by date and takes two seconds. What index do you create, and why?

Seniorindexesquery-performanceb-tree

What the interviewer is really testing

Whether you understand how a B-tree's sort order decides which queries it can serve, so that you can reason about column order instead of reciting "index the WHERE columns". Strong candidates also check the plan and count the cost of the index.

Show the model answer, follow-ups and checklist

Model answer

The query is:

SELECT id, total, created_at FROM orders
WHERE tenant_id = ? AND status = 'open' AND created_at >= ?
ORDER BY created_at DESC LIMIT 50;

First I would run EXPLAIN to see what it does today. Most likely it uses an index on tenant_id alone, fetches every order for the tenant, filters, and sorts.

The index I want is (tenant_id, status, created_at).

A B-tree is sorted by its first column, then the second, then the third. The two equality conditions pick out one contiguous section of the index: this tenant, status open. Inside that section the entries are already in created_at order. The database starts at the newest entry, reads backwards, and stops after 50. There is no sort step, and it reads about 50 entries however many orders the tenant has.

Column order is the whole point. With (tenant_id, created_at, status) the scan would cover every order for the tenant in the date range and check the status of each one. If 1% are open, that is about 5,000 entries read to find 50. The rule is equality columns first, then the range or sort column.

Two refinements:

  • Make it covering. Add total as an included column so the query is answered from the index alone, which saves 50 random reads of the table.
  • Consider a partial index. If open orders are a small share and this is the hot query, an index on (tenant_id, created_at) restricted to status = 'open' is much smaller and cheaper to maintain.

The cost is real. This is one more tree to update on every insert and every status change. I would build it concurrently so writes are not blocked, then confirm with EXPLAIN ANALYZE that the plan is an index scan with no sort and that rows read is close to rows returned.

Likely follow-ups

Would (status, tenant_id, created_at) work just as well?
For this query, yes. The order of the equality columns among themselves does not change how many entries are read. I would still lead with tenant_id, because other queries filter by tenant alone and can reuse the index as a prefix. "Most selective column first" matters much less than "equality before range".
The filter becomes status IN ('open', 'pending'). Does the index still avoid the sort?
Not directly. Each status is its own section of the index, sorted by date inside it, so the two sections together are not in date order. The database either sorts the matches or merges the two streams. I could write it as a UNION ALL of two queries that each take 50 rows and then take the top 50, or use (tenant_id, created_at) and filter status if both values are common.
You built the index and the planner still does not use it. Why might that be?
Stale statistics that make the planner misjudge row counts, a parameter whose type differs from the column so a cast is applied, a function wrapped around a column, or a tenant so large that the planner expects most of the table to match. In PostgreSQL a failed concurrent build also leaves an invalid index behind. I would read the EXPLAIN output before guessing.
What does this index cost you?
Several gigabytes of storage on a table this size, and one more tree to update on every insert. Status is an indexed column, so every status change now moves an index entry, and in PostgreSQL it stops those updates being heap-only. That is acceptable for a hot query and wasteful for a rare one.

Common mistakes

  • Putting the range or sort column before the equality columns.
  • Creating three single-column indexes and expecting the database to combine them efficiently.
  • Ordering columns by selectivity alone and ignoring the range and the sort.
  • Not looking at the query plan before or after the change.
  • Forgetting that the index slows writes and takes space.

A strong answer includes

  • Looks at the current plan with EXPLAIN first
  • Proposes (tenant_id, status, created_at) with equality columns before the range and sort column
  • Explains that entries are then already in date order, so there is no sort and the scan stops after 50
  • Explains what goes wrong with created_at in the middle
  • Mentions a covering index or a partial index as a refinement
  • States the write and storage cost, and builds the index without blocking writes
  • Verifies with EXPLAIN ANALYZE afterwards

Revise: Indexes and B-trees

3. Inserts into a table got slower each time the team added an index. Why, and what would you do about it?

Mid-levelindexeswrite-performanceb-tree

What the interviewer is really testing

Whether you know that an index is a separate structure that must be maintained on every write, and can explain why the slowdown is sometimes gradual and sometimes sudden. A good answer includes how to find indexes that are safe to remove.

Show the model answer, follow-ups and checklist

Model answer

Every index is its own B-tree, and every one of them has to reflect each new row. An insert into a table with six indexes is seven writes: the row, plus an entry in each index. Each entry belongs on one particular leaf page, and for most indexes that page is effectively random. Every change also goes into the write-ahead log, so log volume and replication traffic grow with each index.

The slowdown has two phases. While all the indexes fit in memory, each extra index adds a little CPU and log volume, and inserts get gradually slower. Once the indexes outgrow memory, an insert has to read index pages from disk before it can change them, and throughput falls sharply. That cliff is usually what makes a team notice.

Updates pay too. Changing an indexed column removes one index entry and adds another. In PostgreSQL, an update that touches any indexed column writes a new entry in every index.

What I would do, in this order:

  1. Measure which indexes are used. Drop the ones that nothing reads.
  2. Remove redundant ones. An index on (a) adds nothing if (a, b) exists.
  3. Shrink what remains. A partial index that covers only the rows a query needs is smaller and cheaper to maintain.
  4. Change the write pattern. Batch the inserts. For bulk loads, drop the indexes and rebuild them afterwards.
  5. Keep the working set small. Partition the table by time, so that the indexes on the current partition fit in memory, and prefer keys that increase over time.

If the table is written constantly and queried rarely, I would question whether those queries belong on this database at all. They may be better served from a replica, a warehouse or a search index.

The principle is that an index is a trade: slower writes and more storage in return for faster reads. Each one should be justified by a query I can name.

Likely follow-ups

How do you find out which indexes are safe to drop?
The database keeps usage counters, such as pg_stat_user_indexes in PostgreSQL and the unused-index view in MySQL's sys schema. I would watch them over a full business cycle, including month-end jobs, and on the replicas as well, since reads may happen there. Unique indexes stay even with zero reads, because they enforce a constraint.
Why does it matter whether the indexed values arrive in order or at random?
With increasing values, such as a timestamp or a time-ordered id, every insert lands on the rightmost leaf page, which stays in memory. With random values, such as a UUIDv4, each insert lands on a different page, so the whole index has to be in memory to avoid disk reads, and pages split all over the tree.
Would an LSM-based engine make the problem go away?
It makes index maintenance cheaper, because index entries also become sequential appends instead of in-place page updates. It does not make it free. Every index is still extra data to write and compact, and reads cost more. It helps when the workload is truly write-dominated.

Common mistakes

  • Saying indexes only affect reads.
  • Blaming locks or the network without first counting how many structures each insert updates.
  • Dropping indexes without checking usage, including unique indexes that enforce constraints.
  • Missing the memory effect, where throughput collapses once the indexes no longer fit in the buffer pool.

A strong answer includes

  • Explains that each insert writes the row plus one entry per index
  • Notes that each index entry lands on an effectively random leaf page, and that log volume grows too
  • Explains the cliff when the indexes outgrow memory
  • Uses index usage statistics to find unused and redundant indexes
  • Offers at least two mitigations beyond dropping indexes (batching, partitioning by time, ordered keys, partial indexes)
  • States the trade-off, slower writes in return for faster reads on named queries

Revise: Indexes and B-trees

4. You need to ingest 100,000 events per second and serve occasional lookups by key. Would you pick a B-tree or an LSM-based storage engine?

Seniorstorage-engineslsm-treeb-tree

What the interviewer is really testing

Whether you can connect a workload to how a storage engine does its disk I/O, with numbers, and whether you know what the LSM tree's write speed costs. The interviewer wants a trade-off, not a slogan such as "LSM is faster for writes".

Show the model answer, follow-ups and checklist

Model answer

I would pick an LSM-based engine, and the reason is the shape of the disk I/O.

The numbers. At 200 bytes per event, 100,000 events per second is 20 MB per second of new data, or about 1.7 TB per day. The data will be far larger than memory within hours.

What a B-tree does with that. Each insert has to modify one leaf page in every index. With keys that are not in arrival order, those pages are effectively random, and once the index exceeds memory each insert means reading a page and later writing a whole 8 or 16 kB page back to change 200 bytes. Sustained, that is a heavy random workload. A time-ordered key helps the primary index, and every secondary index still pays.

What an LSM tree does. A write is an append to the write-ahead log plus an insert into the memtable. When the memtable fills, it is written out as a sorted file in one sequential pass. Nothing is read on the write path and nothing is updated in place.

What I pay.

  • A point read may check several files. Bloom filters skip most of them, so the occasional lookup by key costs about one disk read.
  • Compaction rewrites data in the background. For append-only, time-ordered events I would use a time-window or size-tiered strategy, which rewrites data far less than levelled compaction. I would expire data with a time-to-live so that whole files are dropped, with no row-by-row deletes.
  • I need disk headroom, and I need to watch for pending compactions.

When I would choose the B-tree. If the workload were read-heavy with updates in place, needed multi-row transactions and several secondary indexes, or needed steady low read latency at a modest write rate, which describes most applications. A partitioned PostgreSQL table is simpler to run and handles a few thousand inserts per second comfortably.

Likely follow-ups

Reads grow to half the workload and need a p99 under 10 ms. Does your answer change?
It might. I would first try levelled compaction, a larger block cache and Bloom filters, which keep a point read to about one disk read. If updates and range scans dominate and the write rate has fallen, a B-tree engine gives steadier read latency with no compaction in the background. I would measure before switching.
What happens when compaction cannot keep up with writes?
Flushed files pile up, so each read has more files to check and gets slower. Space is not reclaimed, so the disk fills. Eventually the engine slows or stalls incoming writes on purpose until it catches up. The fixes are more compaction throughput, a strategy with lower write amplification, or backpressure on the producers.
SSDs made random writes cheap. Is the LSM tree still worth it?
The gap is much smaller than on spinning disks, and a B-tree on NVMe goes a long way. The remaining LSM advantages are that it does not write a whole page to change a few bytes, that its immutable files compress well, and that sustained ingest stays sequential. On the other side, compaction rewrites data too, so it is not automatically kinder to the drive.
Which real systems would you shortlist?
For the LSM side, Cassandra or ScyllaDB if I want a distributed store, or something built on RocksDB. For the B-tree side, PostgreSQL or MySQL InnoDB. If the events are time-series metrics I would also look at a time-series database, which is LSM-like and adds time partitioning and compression.

Common mistakes

  • Saying LSM is faster without explaining sequential versus random I/O.
  • Ignoring compaction, write amplification and write stalls.
  • Claiming that LSM reads are always slow, and forgetting Bloom filters and the block cache.
  • Choosing an engine without numbers for write rate, record size and data volume.
  • Forgetting that deletes become tombstones, and that a time-to-live is the cheap way to expire event data.

A strong answer includes

  • Estimates the volume (about 20 MB per second, 1.7 TB per day at 200 bytes per event)
  • Explains the B-tree's cost, a random page read and write per index for each insert
  • Explains the LSM write path, a log append and a memtable insert followed by sequential flushes
  • States the price in read amplification, compaction and write amplification
  • Picks a compaction strategy suited to append-only, time-ordered data
  • Says when a B-tree would be the better choice
  • Names operational signals to watch (pending compactions, disk headroom)

Revise: LSM trees

5. Your Cassandra cluster's disks are saturated and read latency spikes every few hours, yet the application's write rate is modest. What is going on?

Stafflsm-treecompactionwrite-amplification

What the interviewer is really testing

Whether you understand that an LSM store does most of its disk work in the background, and can reason from symptoms to compaction strategy, tombstones and data model. This is a debugging conversation, so a structured method matters as much as the answer.

Show the model answer, follow-ups and checklist

Model answer

A modest write rate with saturated disks points at the storage engine’s background work. In an LSM store such as Cassandra, the application’s writes are only the first time each byte reaches the disk. Compaction rewrites that data several times as it merges SSTables. If the application writes 30 MB per second and the write amplification is 15, the disks are doing 450 MB per second.

How I would confirm it. I would look, table by table, at pending compaction tasks, at the number of SSTables consulted per read, at how disk I/O divides between flushes and compaction, and at tombstone warnings in the logs. In Cassandra that is nodetool compactionstats and nodetool tablehistograms. The pattern of spikes every few hours fits large compactions, or repairs that trigger them.

Likely causes, and the fix for each.

  • Levelled compaction on a write-heavy table. It keeps reads and space tight by rewriting data often. If the table is mostly appended to, size-tiered compaction writes far less.
  • Time-series data with a time-to-live under the wrong strategy. The engine keeps merging data that is about to expire. Time-window compaction groups SSTables by time, so whole files are dropped when they expire.
  • Size-tiered compaction on a table with many updates. A key ends up in many SSTables, so reads are slow between merges, and the largest merges need a lot of free disk. Levelled compaction suits that table better.
  • Tombstones. A workload that deletes heavily leaves markers that reads must scan past until compaction is allowed to drop them.
  • A compaction throttle set too low. The backlog builds until the engine has to catch up in bursts.

The trade-off. Write, read and space amplification cannot all be low. Every strategy chooses which one to pay, so the right fix depends on what each table is for.

For the longer term I would size the disks for ingest multiplied by write amplification, keep enough free space for the largest merge, and alert on pending compactions so that the next backlog is seen before latency suffers.

Likely follow-ups

How would you measure write amplification?
Divide the bytes written to the device over a period, from disk statistics or the engine's own counters, by the bytes the application wrote in the same period. Compare like with like, since data on disk is compressed. A ratio in single figures is typical for size-tiered compaction and 10 to 30 for levelled.
Why not switch compaction off during peak hours?
The number of SSTables would grow, so reads would check more files and get slower, and overwritten data would not be reclaimed. The work does not go away. It becomes a larger debt to pay later. Throttling compaction and scheduling the heaviest work off-peak is safer than stopping it.
Do Bloom filters hide this problem?
Partly. They keep point reads cheap even with many SSTables, because most files are skipped in memory. They do nothing for range scans or for reads within a wide partition, and they do not reduce the disk writes. They also use memory, roughly 10 bits per key for a 1% false positive rate.
Would you change the hardware or the data model first?
The data model and the compaction strategy. If the table holds time-series data with a time-to-live, moving to time-window compaction can remove most of the rewriting at no hardware cost. If the application overwrites or deletes rows constantly, I would fix that pattern. Faster disks treat the symptom and cost money every month.

Common mistakes

  • Looking only at the application's write rate and not at what the storage engine writes.
  • Proposing more nodes before finding out which table and which strategy cause the load.
  • Not knowing that deletes and expired rows remain on disk as tombstones until compaction removes them.
  • Treating compaction as optional maintenance instead of a core part of the engine.
  • Running the cluster too full for size-tiered compaction to merge its largest files.

A strong answer includes

  • Identifies compaction and write amplification as the likely cause
  • Checks pending compactions, SSTables per read and tombstone counts, table by table
  • Relates the periodic spikes to large compactions or repairs
  • Matches compaction strategy to workload (size-tiered, levelled, time-window)
  • Considers tombstones and wide partitions as causes of slow reads
  • Plans disk throughput and free space for ingest multiplied by write amplification
  • States the trade-off between write, read and space amplification

Revise: LSM trees

6. The product page joins five tables and is too slow at peak. When would you denormalize, and how would you keep the copies correct?

Seniordata-modellingdenormalizationconsistency

What the interviewer is really testing

Whether you treat denormalization as a measured trade with a maintenance plan, not a reflex. The interviewer is listening for cheaper fixes tried first, a named source of truth, an update path that survives failures, and a stated tolerance for stale data.

Show the model answer, follow-ups and checklist

Model answer

I would not start by denormalizing. Five joins on indexed keys should take a few milliseconds, so first I would look at the query plan. The usual causes are a missing index, a query issued once per item in a loop, or a join that fans out to far more rows than the page shows. If the queries are sound and the page is still too slow at peak, a cache in front of the assembled result is the next cheapest step.

I would denormalize when four things are true: the read is hot and measured, reads outnumber changes by a wide margin, the page can show data that is a few seconds old, and the cheaper fixes are not enough. A join that crosses shards or services is a strong reason on its own.

What I would build. For a product page I would keep a read model: one row or document per product that holds what the page shows, including the seller’s name, the category path, the rating average and the review count.

How it stays correct.

  • The normalized tables remain the source of truth. Nothing writes to the read model except its updater.
  • Changes flow from the database’s log through change data capture to a consumer that rebuilds the affected product’s row. The consumer is idempotent, and it carries a version so that an older event cannot overwrite a newer one.
  • I can rebuild the whole read model from the source with a batch job, which is how I repair drift.
  • I monitor the consumer’s lag, since that is the staleness users see.

What stays on the source of truth. Price and stock are shown from the read model, and checked again against the normalized tables at checkout. I never make a decision about money from a copy.

The cost is that every change to a product, seller or review now triggers extra writes, and I own a pipeline. That is a fair price for a page that is read thousands of times for every change.

Likely follow-ups

A seller renames their shop, and the shop name is copied onto 2 million product rows. What happens?
The rename becomes a background job that updates the copies in batches, so the name is stale for a while and the job must be safe to resume. For a value with that much fan-out I would question copying it at all. The seller record is small and hot, so the page can fetch it from a cache by seller id. I decide field by field from how often it changes multiplied by how many copies exist.
How do you detect that a copy has drifted from the source?
A scheduled reconciliation job compares the copy with the source, either fully for small data or by sampling and checksums for large data, and repairs or reports differences. I would also alert on the lag of the change stream, because a stalled consumer is the most common cause of drift.
Why not update the copy from the application code that makes the change?
That is a dual write. With no transaction across the two stores, a crash or timeout between the writes leaves them different, and no component knows it needs fixing. Deriving the copy from the database's log, or from an outbox row written in the same transaction, means the change is retried until it lands.
When is a cache better than a denormalized table?
When the value can be recomputed cheaply on a miss and a short time-to-live is acceptable. A cache can be thrown away, so there is less to maintain. A denormalized table is the better tool when you need to filter or sort by the precomputed value, or when recomputing is expensive, as with an aggregate over millions of rows.

Common mistakes

  • Denormalizing before checking the query plan, the indexes and repeated queries in a loop.
  • Saying joins are slow as a general truth.
  • Copying data with no stated owner, update path or staleness limit.
  • Updating two stores from application code and assuming both writes succeed.
  • Trusting a denormalized copy for decisions about money or stock.
  • Copying a frequently changing value into millions of rows.

A strong answer includes

  • Tries indexes, query fixes and caching before changing the schema
  • Gives conditions for denormalizing (hot read, high read-to-write ratio, tolerable staleness, join across shards or services)
  • Names the technique (duplicated columns, precomputed aggregate, read model or materialised view)
  • Names the source of truth and keeps it normalized
  • Describes an update path that survives failure (same transaction, or change data capture with idempotent consumers)
  • States how stale the copy may be and how it is rebuilt
  • Says which reads still go to the source of truth

Revise: Normalization vs denormalization

7. Two customers buy the last item in stock at the same moment and both orders succeed. What went wrong, and how do you fix it?

Seniortransactionsisolationconcurrency

What the interviewer is really testing

Whether you can recognise a read-modify-write race, name it, and choose between an atomic update, a row lock, a version check and a stricter isolation level with reasons. Good candidates know that wrapping the code in a transaction does not by itself fix it.

Show the model answer, follow-ups and checklist

Model answer

This is a lost update. Both requests ran the same three steps: read the stock, check that it is above zero, write back the stock minus one. Both read 1 before either wrote. Both passed the check, both wrote 0, and both created an order. Each write was valid alone. Together they sold one item twice.

A transaction does not prevent it by default. At read committed, which is PostgreSQL’s default, each transaction reads committed data and nothing stops the second write. The bug is the gap between reading and writing in application code.

The fix I would choose is to close that gap by letting the database do the check and the write as one statement:

UPDATE inventory SET stock = stock - 1
WHERE product_id = ? AND stock > 0;

The database locks the row for the update. The second request waits, then evaluates the condition against the new value and changes zero rows. The application checks the affected row count. One means it inserts the order in the same transaction and commits. Zero means sold out, so it rolls back.

Alternatives, and when they fit.

  • SELECT ... FOR UPDATE when the logic must read before deciding. It locks the row at read time. Keep that transaction short.
  • A version column when the read and the write happen in different requests, such as a user editing a form. The write succeeds only if the version is unchanged.
  • Stricter isolation with retries if the team already runs that way.

Backstops. I would add a check constraint that stock cannot go below zero, so a future code path with the same bug fails loudly. I would also accept an idempotency key on the purchase request, so that a retried request cannot decrement twice.

For a very popular item the row lock becomes a queue, and that is a separate scaling problem. The correctness fix comes first.

Likely follow-ups

Would raising the isolation level to repeatable read fix it?
It depends on the database. In PostgreSQL, repeatable read is snapshot isolation and aborts the second transaction when it tries to update a row changed since its snapshot, so the application must retry. In MySQL InnoDB, repeatable read does not detect this. A plain read followed by an update silently overwrites, so you still need a locking read or an atomic update.
Stock is spread over several warehouses and the code must choose one. Can it still be a single statement?
Usually not, because the code has to read candidates before deciding. I would select the candidate rows with FOR UPDATE inside the transaction, pick one, and decrement it. Adding SKIP LOCKED lets concurrent buyers take different warehouses instead of queueing behind one row.
Ten thousand people press buy for 100 items in the same second. Does the row lock hold up?
It stays correct, and it does not stay fast. Every request queues on one row, connections pile up and the database becomes the bottleneck for the whole site. I would put admission control in front, such as an atomic counter in Redis or a queue, so that only about 100 winners reach the database.
The client times out and retries the purchase. How do you avoid selling two items to one customer?
The client sends an idempotency key with the request, and the orders table has a unique constraint on it. The retry either finds the existing order and returns it, or fails the constraint inside the same transaction as the decrement, which rolls the second decrement back.

Common mistakes

  • Saying "put it in a transaction" without considering the isolation level.
  • Reading the stock in application code and writing back a computed value.
  • Assuming repeatable read behaves the same in every database.
  • Using a distributed lock or a cache as the first fix when the database can serialise the update itself.
  • Forgetting to check the affected row count after a conditional update.
  • Ignoring retries, so a timeout turns into a double purchase.

A strong answer includes

  • Names the anomaly as a lost update caused by a read-modify-write race
  • Explains why the default isolation level allows it
  • Gives the atomic conditional update and checks rows affected
  • Offers SELECT FOR UPDATE and a version column as alternatives, and says when each fits
  • Keeps the decrement and the order insert in one transaction
  • Adds a constraint as a backstop and an idempotency key for retries
  • Addresses contention on a hot item

Revise: ACID and isolation levels

8. Each user may hold at most three active bookings. The code checks the count inside a transaction, yet under load some users have four. How is that possible?

Stafftransactionsisolationwrite-skew

What the interviewer is really testing

Whether you can tell write skew from a lost update, explain why snapshot isolation and row locks on existing rows do not stop it, and pick a fix that fits the invariant. This separates candidates who know the isolation level names from those who know what the levels actually allow.

Show the model answer, follow-ups and checklist

Model answer

This is write skew. Two requests for the same user arrive together. Each starts a transaction and counts the user’s active bookings. Each sees two, which is under the limit. Each inserts a new booking and commits. The user now has four.

The transaction did not help, because of what isolation actually guarantees. At read committed, and also under snapshot isolation, each transaction reads committed data and neither sees the other’s uncommitted insert. The two inserts are different rows, so there is no write conflict for the database to detect and no lock to wait on. Each transaction was correct on its own. The rule spans rows, and nothing guards a rule that spans rows unless you ask for it.

It is not a lost update, because nothing was overwritten. It is also a phantom problem: the rows that would have changed the count did not exist when the check ran.

Three fixes.

  1. Lock a parent row first. Begin with SELECT ... FROM users WHERE id = ? FOR UPDATE. All booking transactions for one user now run one at a time, and at read committed the second one counts three. Contention is per user, so the cost is low.
  2. Turn the rule into a single-row update. Keep an active_bookings counter on the user row and run an update that increments it only where it is below three. The rule now lives in one row, where the database serialises writers, and it holds at every isolation level.
  3. Use serializable isolation. The database detects that each transaction read what the other wrote and aborts one. The application must retry aborted transactions.

For a rule of “at most one”, a unique or exclusion constraint is simpler than any of these.

I would choose the counter with a check constraint. It is cheap, it does not depend on the isolation level, and the database enforces it even if a new code path forgets the lock. I would move to serializable if the system had many such rules and a standard retry wrapper already in place.

Likely follow-ups

Would SELECT FOR UPDATE on the user's existing bookings fix it?
Not in general. The row that causes the violation does not exist yet. In PostgreSQL a row lock cannot cover a row that has not been inserted, so the second transaction waits, gets the locks and still does not see the new booking. With zero existing bookings there is nothing to lock at all. InnoDB differs at repeatable read, because a locking read also locks the gaps in the index range and so blocks the other insert, sometimes by way of a deadlock that aborts one transaction.
Does locking the user row work at every isolation level?
At read committed, yes. The second transaction waits for the lock, and its next statement sees the first one's committed booking. Under snapshot isolation its snapshot may already be older than that commit, so the count is still stale. There the parent row must be modified as well as locked, for example by updating a counter, so the database detects a conflict.
What does running at serializable cost?
Transactions can be aborted with a serialization failure even when they are correct on their own, so every one needs retry logic. The database tracks what each transaction read, which costs memory and CPU, and throughput drops when many transactions touch the same data. Long transactions make it worse. It is a good trade for a ledger and a poor one for a high-volume feed.
How would you find this class of bug before it reaches production?
Look in review for any code that checks a condition across rows and then writes. Write concurrency tests that fire the same request in parallel many times. Put the invariant in the database where a constraint can express it. Run a periodic query that counts violations, so that a bug shows up as an alert and not as a support ticket.

Common mistakes

  • Calling it a lost update, when no row was overwritten.
  • Assuming that code inside a transaction is serialised.
  • Believing repeatable read or snapshot isolation prevents all anomalies.
  • Locking only the rows that already exist, when the conflict comes from rows not yet inserted.
  • Reaching for a distributed lock when a row lock or a constraint in the database would do.
  • Switching to serializable without adding retries.

A strong answer includes

  • Names the anomaly as write skew and explains the two-transaction interleaving
  • Explains that the transactions write different rows, so there is no write conflict to detect
  • Notes that the conflicting rows do not exist when the check runs (a phantom)
  • Offers at least two fixes from parent-row lock, counter column with a conditional update, serializable isolation
  • Explains the snapshot isolation caveat for the parent-row lock, or chooses the counter to avoid it
  • Mentions retries for serializable and a monitoring query as a backstop

Revise: ACID and isolation levels

9. You need to store CPU, memory and request metrics from 50,000 hosts, and serve dashboards and alerts. What do you store them in?

Seniortime-seriesstoragecapacity-estimation

What the interviewer is really testing

Whether you estimate the volume before choosing, recognise the properties of time-series data that a specialised store exploits, and know the failure mode that matters most, which is cardinality. The interviewer also wants to hear when a general database would have been enough.

Show the model answer, follow-ups and checklist

Model answer

I would start with the size. Say each host exposes about 200 series, so 50,000 hosts give 10 million active series. Sampling every 15 seconds is about 670,000 points per second, or about 58 billion points per day. A raw point is a 16-byte timestamp and value, so that is over 900 GB per day before any indexing.

The workload has a distinctive shape. Writes are appends, in roughly time order, and are never updated. Reads are time ranges over a few series, or aggregates across many hosts, mostly over the last hour. Data expires by age.

That shape is what a time-series database is built for. A general relational table would spend 50 bytes or more per point on row overhead and a B-tree index, which is several terabytes per day, and expiring old data would mean deleting billions of rows. A time-series store does four things differently:

  • It stores data in blocks by time window, so retention is dropping a block.
  • It compresses each series with delta encoding for timestamps and XOR encoding for values. At 1 to 2 bytes per point, the day shrinks to roughly 60 to 120 GB.
  • It keeps an index from label values to series, so “all hosts in region eu” is fast.
  • It downsamples old data.

The design. Collectors send samples to a cluster that is sharded by a hash of the series labels, with two or three replicas. Each node keeps recent data in memory, backed by a write-ahead log, and writes compressed blocks every couple of hours. Older blocks move to object storage for long retention, which is the pattern Thanos and Mimir use around Prometheus. Alerts are evaluated against recent data.

The main risk is cardinality. The number of series, not the number of points, is what breaks these systems.

When I would not do this. For a few hundred hosts, a single Prometheus server is enough. If the metrics had to be joined with business data in SQL, I would look at TimescaleDB to stay inside PostgreSQL.

Likely follow-ups

A developer adds a customer_id label to the request metrics. What happens?
Each distinct combination of label values is its own series, so the number of series is multiplied by the number of customers. The series index and the memory for recent data grow until ingestion slows or the database runs out of memory. I would enforce limits on series per metric at ingestion, and send per-customer detail to logs or traces.
How do you keep a year of history affordably?
Downsample. Keep full resolution for a few weeks, then 5-minute and 1-hour rollups for longer periods, since nobody reads 15-second points from last spring. Move older blocks to object storage, which is far cheaper than local SSD, and query them on demand.
Would Cassandra work for this?
It can, and several early metrics systems were built that way, with one partition per series per day and time-window compaction. It gives write scale and replication. You then have to build the label index, the compression and the query engine yourself, and a purpose-built store compresses numeric samples far more tightly than generic rows.
How do alerts keep working when the metrics store is degraded?
Keep the alerting path short. Evaluate rules close to ingestion against recent data in memory, not through the long-term query path. Run more than one replica of the evaluator, and have a separate, simple check that fires if the monitoring system itself stops reporting.

Common mistakes

  • Choosing a store before estimating points per second and bytes per day.
  • Putting unbounded values such as user ids or request ids in labels.
  • Planning to expire data with row-by-row deletes.
  • Keeping every sample at full resolution for ever.
  • Making alerting depend on the slowest and least available part of the pipeline.
  • Using a time-series database for records that need updates and joins.

A strong answer includes

  • Estimates series count, points per second and storage per day, raw and compressed
  • States the workload properties (append-only, time-ordered, range reads, expiry by age)
  • Chooses a time-series database and explains time partitioning and compression
  • Covers retention and downsampling
  • Raises cardinality as the main risk and says how to limit it
  • Describes how the store scales out and where long-term data lives
  • Says when a single node or a plain relational table would be enough

Revise: Graph, time-series and object storage

10. Users upload photos and videos of up to 2 GB. Where do you store them, and how does the upload work?

Mid-levelobject-storageuploadspresigned-urls

What the interviewer is really testing

Whether you separate blobs from metadata, keep large uploads off your application servers, and think through failure cases such as abandoned uploads and unvalidated content. It is a common building block, so the interviewer expects fluency and attention to detail.

Show the model answer, follow-ups and checklist

Model answer

The bytes go in object storage and the facts about them go in a database.

Why not the database or a local disk? Putting 2 GB blobs in database rows bloats backups, replication and the page cache, on the most expensive storage in the system. A local disk on an application server is not shared between servers, and is lost with the instance. Object storage such as S3 is built for this: very high durability, effectively unlimited capacity, and a low price per gigabyte.

The upload flow.

  1. The client asks the API to start an upload and sends the size and type.
  2. The API authenticates the user and checks quotas. It creates a metadata row with the owner, a generated object key and the status pending. It starts a multipart upload and returns presigned URLs for the parts.
  3. The client sends the parts straight to object storage, several in parallel. With 16 MB parts, a 2 GB file is 128 parts. A failed part is retried alone, which matters on mobile networks.
  4. When all parts are in, a completion call assembles the object.
  5. Storage emits an event. A worker validates the real size and type, creates thumbnails or transcodes, and sets the row to ready.

The API servers never handle the file bytes.

Downloads go through a CDN in front of the bucket. The bucket stays private, and private content uses signed URLs or signed cookies. Object keys are never reused for different content, so the CDN can cache for a long time.

Details that matter.

  • The object key is generated by the server, never taken from the file name, so users cannot overwrite each other’s files or guess keys.
  • The database is the source of truth. A file exists for the product only when its row says ready.
  • A lifecycle rule aborts multipart uploads that are unfinished after a few days, and a sweeper removes rows that have been pending too long.
  • Presigned URLs expire after minutes and each permits one operation on one key.

Likely follow-ups

Why not send the file through your API servers?
A 2 GB upload on a mobile connection can take many minutes. Each one would hold a connection, memory and bandwidth on a server sized for short requests, and would hit load balancer timeouts. The API fleet would have to scale with bytes instead of with requests, and a dropped connection would restart the upload from zero.
A user uploads a photo and views it immediately. Is there a consistency problem?
Not from the storage itself. S3 has been strongly consistent for reads after writes since December 2020, so the object is readable as soon as the upload completes. The gap is processing, which is asynchronous. The app should show its local copy or a pending state until the metadata row is marked ready, and should not request a thumbnail URL before it exists, or the CDN may cache the miss.
How do you delete a file?
Mark the metadata row as deleted first, so nothing new links to the file. Then a background job deletes the object and every derived rendition, and purges the CDN. Doing it in that order means a failure leaves an orphaned object, which costs a little storage, and not a live link to a missing file. Versioned buckets and backups need their own expiry.
How do you stop someone uploading 50 GB, or a file that is not really a video?
Limit the size when granting the upload, by signing the expected length or by capping the number and size of parts, and enforce a per-user quota. Never trust the declared content type. After upload, a worker checks the real size and inspects the bytes, and only then marks the file ready. Process untrusted media in an isolated environment.

Common mistakes

  • Storing large files in the database or on an application server's local disk.
  • Proxying the upload through the API servers.
  • Having no metadata row, and listing the bucket to find a user's files.
  • Leaving abandoned multipart uploads and pending rows to accumulate.
  • Making the bucket public instead of using signed URLs or a CDN with signed access.
  • Marking a file ready before validating what was actually uploaded.

A strong answer includes

  • Stores bytes in object storage and metadata in a database, linked by object key
  • Explains why the database and local disk are poor places for blobs
  • Uses presigned URLs so the client uploads directly
  • Uses multipart upload with parallel parts and per-part retry
  • Tracks status (pending, then ready) and processes asynchronously from a storage event
  • Serves downloads through a CDN with access control
  • Cleans up abandoned uploads and validates content after upload

Revise: Graph, time-series and object storage

11. A user updates their profile, refreshes the page and sees the old data. What is going on, and how do you fix it?

Mid-levelreplicationconsistency

What the interviewer is really testing

Whether you recognise replication lag from a symptom, know the guarantee the user needs by name (read-your-writes), and fix it with targeted routing instead of making everything synchronous.

Show the model answer, follow-ups and checklist

Model answer

That symptom is replication lag. The write went to the leader. The refresh was served by an asynchronous replica that had not applied the change yet, and a moment later it had. Nothing was lost. The read was stale.

I would confirm it first: find which node served the read, and look at that replica’s lag at the time.

The guarantee the user needs is read-your-writes: after a user writes, that same user’s reads reflect it. Everyone else can see the change a second later and nobody will notice. So I would not make replication synchronous everywhere, which slows every write and stalls when a replica is slow, to fix one narrow case.

Options, simplest first:

  1. Read a user’s own data from the leader. Their own profile and settings come from the leader, other people’s profiles from replicas. This works when “own data” is easy to define.
  2. Pin to the leader for a short window after a write. Record the time of the user’s last write and send their reads to the leader for a few seconds, longer than normal lag. It is simple, but the window is a guess and it fails when lag exceeds it.
  3. Track the log position. Return the commit position (an LSN in PostgreSQL, a GTID in MySQL) from the write and keep it with the session. On a read, use a replica that has replayed past it, wait briefly, or fall back to the leader. This is exact and keeps most reads off the leader.

I would also alert on lag and take a replica out of the read pool when it falls too far behind, because the same lag causes other anomalies, such as a refresh that goes back in time between two replicas.

The trade-off is leader load. Every rule that sends reads to the leader spends the capacity the replicas were meant to save, so I would keep the rule as narrow as the product allows.

Likely follow-ups

The user saves on their phone and then looks on their laptop. Does your fix still work?
Not if the marker lives in a cookie or in one device's session. For cross-device read-your-writes the last write time or log position has to be stored on the server against the user, or the rule has to be "a user's own data always comes from the leader".
A user refreshes twice. A comment appears, then disappears. Is that the same problem?
Same cause, different guarantee. The two reads went to replicas with different lag. Monotonic reads fixes it: send each user to the same replica, for example by hashing the user id, and move them only to a replica that is at least as up to date.
Why not make replication synchronous and be done with it?
Every write would wait for the replicas, and one slow or failed replica would stall all writes. In PostgreSQL the default synchronous mode waits for the standby to flush the log, not to apply it, so a read from the standby could still be stale unless you use remote_apply, which is slower again. That is a high price for something only the writing user notices.
How do you tell replication lag from a stale cache?
Check whether a cache is on the read path and what its TTL is. Then read the same row directly from the leader and from the replica: if the leader has the new value and the replica does not, it is lag. Lag usually clears within moments, while a stale cache entry persists until it expires or is invalidated.

Common mistakes

  • Calling it lost data or a bug in the write path without checking which node served the read.
  • Proposing fully synchronous replication for every write.
  • Adding a fixed sleep after the write, with no fallback when lag is longer than the sleep.
  • Sending all reads to the leader, which throws away the reason for having replicas.
  • Forgetting that a cache in front of the database can produce the same symptom.

A strong answer includes

  • Names replication lag and explains that the read was served by an asynchronous replica
  • Names the guarantee, read-your-writes, and limits it to the user who wrote
  • Gives at least two fixes and what each costs
  • Mentions tracking a log position (LSN or GTID) as the precise fix
  • Keeps the rule narrow to protect leader capacity
  • Monitors lag and removes replicas that fall too far behind

Revise: Replication

12. Your database leader stops responding. Walk me through the failover and tell me what can go wrong.

Seniorreplicationfailoveravailability

What the interviewer is really testing

Whether you see failover as a distributed decision with real failure modes: false detection, lost writes and two leaders. Strong candidates raise fencing and data loss before they are asked.

Show the model answer, follow-ups and checklist

Model answer

I will assume a single leader with asynchronous or semi-synchronous followers and an automated failover manager.

The sequence. First, detect: the manager and the followers see heartbeats stop for longer than a timeout. Second, decide: only one node may become leader, so the manager holds a leader lock in a consensus store such as etcd, and only the lock holder may act as leader. Third, promote the follower with the most recent log position. Fourth, repoint the other followers and the clients, through a proxy, a virtual IP or DNS with a short TTL.

What goes wrong.

  • False detection. The leader was slow, not dead: a long pause, a saturated disk, a network blip. An aggressive timeout fails over under load and makes things worse. I would use a timeout of some tens of seconds and require more than one observer to agree.
  • Lost writes. With asynchronous replication the promoted follower may lack the last few writes that clients were told had committed. Requiring one standby to confirm each commit removes that, at the cost of write latency.
  • Split brain. The old leader was only partitioned and still accepts writes from clients with open connections. Now two copies diverge. The defence is fencing. The old leader must stop by itself when it cannot renew its lock, the manager shuts it down or isolates it where it can, and an epoch number lets followers reject a stale leader.
  • The old leader’s extra writes. When it rejoins it must discard or rewind writes the new leader never saw. Anything derived from them elsewhere, such as cache entries or rows in another store, may now be inconsistent.

The trade-off is between recovery time and safety. A fast automatic failover risks unnecessary failovers and lost writes. A cautious one means a longer outage. For most systems I would automate it with a consensus-backed lock, semi-synchronous replication and fencing, and I would test it regularly by failing the leader on purpose.

Likely follow-ups

The old leader is partitioned from everything. How does it know it should stop?
Nobody can tell it, so it has to stop by itself. Its leadership is a lease in the consensus store that it must keep renewing. If it cannot renew before the lease expires, it demotes itself or its local agent shuts the database down. The new leader is promoted only after that lease has expired, with a margin for clock drift.
Is a lease enough? Suppose the old leader pauses for 30 seconds just after checking it.
No. A process can pause, for garbage collection or a virtual machine migration, between checking the lease and performing the write. The robust fix is a fencing token: a number that increases with each promotion and is checked by whatever accepts the write, so a write carrying an old token is rejected however late it arrives.
The failover lost five acknowledged writes. How do you prevent that next time?
With asynchronous replication that loss is expected and is bounded by the lag at the moment of the crash, so the recovery point objective was never zero. To make it zero, require at least one standby, ideally in another zone, to confirm each commit before acknowledging. That adds latency and needs two standbys so that one failure does not block writes.
Would you automate failover or page a person?
It depends on what each mistake costs. Automatic failover recovers in under a minute but can trigger wrongly. Manual failover is safer and takes many minutes. Many teams automate within a region with strict fencing and keep cross-region failover a human decision, because lag and blast radius are both larger.

Common mistakes

  • Describing only the happy path: detect, promote, done.
  • Assuming that a node which misses heartbeats is dead.
  • Not mentioning that asynchronous replication can lose acknowledged writes.
  • Relying on timeouts alone to prevent two leaders, with no fencing.
  • Letting a single monitor process decide, which is itself a single point of failure.

A strong answer includes

  • Lists the steps: detect, decide, promote, reroute
  • Explains why detection by timeout is ambiguous and how to choose the timeout
  • States that asynchronous failover can lose acknowledged writes, and how semi-synchronous replication changes that
  • Defines split brain and gives a fencing mechanism
  • Puts the leader decision in a majority-based system
  • Covers what happens when the old leader rejoins
  • States the trade-off between recovery time and safety

Revise: Replication

13. We want to accept writes in both our US and EU regions. How do you handle conflicting writes?

Staffreplicationmulti-regionconflict-resolution

What the interviewer is really testing

Whether you question the requirement before building it, know that avoiding conflicts beats resolving them, and can match a resolution strategy (last write wins, version vectors, CRDTs) to a specific kind of data.

Show the model answer, follow-ups and checklist

Model answer

First I would ask why. If the goal is low write latency for EU users, or surviving the loss of a region, there may be a cheaper design than letting both regions write every table.

Avoid conflicts where possible. Most data belongs to one user or one tenant. I would give each a home region and route their writes there, so every record has a single leader even though the system as a whole has two. A user who travels still writes to their home region, a little more slowly. Failing a region over moves the home. This covers most tables with no conflict logic at all.

For data that really is written in both regions, replication between them is asynchronous, so both can change the same record before either sees the other. The right strategy then depends on the data:

  • Last write wins where losing one of two concurrent updates is acceptable, such as a last-seen time or a profile photo. It is simple, it does lose data, and with clock skew it can discard the newer write. I would never use it for balances or stock.
  • Version vectors with an application merge when both writes matter. The store detects that two versions are concurrent and keeps both, and the application merges them, for example by taking the union of two shopping carts.
  • CRDTs where the data type fits: counters for likes, sets for tags, sequence types for shared text. They converge automatically, at the cost of extra metadata and a limited set of operations.

Some things cannot be merged. Uniqueness, such as two users claiming one username, and invariants such as “the balance never goes below zero” need a single decision point. Those writes go through one region or a consensus-backed store, and I would accept the latency for them.

Finally the operational side: count and log conflicts, make replication idempotent so that changes do not loop between regions, and decide what a user sees when their write loses.

Likely follow-ups

Why is last write wins dangerous with wall-clock timestamps?
Clocks on different machines differ by milliseconds to seconds even with NTP. A write that happened later can carry an earlier timestamp and be silently discarded, and a node whose clock runs ahead wins every conflict until it is corrected. Last write wins also cannot tell a concurrent write from a later one. It just picks.
How does a version vector show that two writes conflict?
Each replica increments its own entry when it accepts a write, and the vector travels with the value. If every entry in A is greater than or equal to the matching entry in B, A descends from B and replaces it. If each vector has an entry larger than the other, neither write saw the other, so they are concurrent and must both be kept or merged.
Two people register the same username in different regions at the same moment. What happens?
With asynchronous multi-leader replication both succeed locally, and the conflict is found later when one of them has to be told the name is taken. To prevent it, the claim must be decided in one place: a single home region for the uniqueness table or a consensus-backed store. The cross-region latency is then paid only on registration.
How do deletes behave when replicas merge?
A plain delete can be undone when an old replica that still has the item syncs it back. So deletions are recorded as tombstones that replicate like writes and must be kept until every replica has seen them, which costs space. CRDT sets such as the observed-remove set define exactly which additions a removal cancels.

Common mistakes

  • Jumping to CRDTs or vector clocks without asking whether both regions need to write the same records.
  • Proposing last write wins for money, stock or anything where a lost update matters.
  • Assuming synchronised clocks make timestamps a safe way to order writes.
  • Ignoring uniqueness constraints and invariants, which cannot be merged after the fact.
  • Forgetting deletes and tombstones.

A strong answer includes

  • Questions the requirement and separates the latency goal from the availability goal
  • Proposes avoiding conflicts by giving each user or tenant a home region
  • Explains why asynchronous multi-leader replication produces conflicts
  • Matches last write wins, version vectors and CRDTs to specific data
  • States what last write wins loses and why clocks make it worse
  • Identifies operations that need a single decision point, such as uniqueness and non-negative balances
  • Says how conflicts are monitored and what the losing user sees

Revise: Replication

14. In a Dynamo-style store with three replicas, how do you choose W and R, and can a quorum read still return stale data?

Seniorreplicationquorumsconsistency

What the interviewer is really testing

Whether you can reason from the overlap rule to concrete latency, availability and consistency trade-offs, and whether you know the limits of quorums instead of treating W + R > N as strong consistency.

Show the model answer, follow-ups and checklist

Model answer

N is the number of replicas of each key, W is the number of acknowledgements a write waits for, and R is the number of replies a read waits for. If W + R > N, the replicas that acknowledged the latest write and the replicas that answer a read share at least one node, so the read can return the newest value.

With N = 3 the realistic choices are:

  • W = 2, R = 2. The sets overlap, and both reads and writes survive one replica being down. This is my default.
  • W = 3, R = 1. Fast reads that still overlap, but one dead replica blocks every write. It suits data that is read heavily and written rarely.
  • W = 1, R = 3. Fast writes, but one dead replica blocks every read.
  • W = 1, R = 1. Fastest and most available, with no overlap, so reads can be stale. Fine for metrics or a view counter.

Requests are sent to all N replicas. W and R only say how many replies to wait for, so latency follows the W-th or R-th fastest replica, not the slowest.

A quorum read can still be stale, in several ways.

  • Concurrent writes. Two clients write the same key at once and the store picks a winner by timestamp.
  • Partial failure. A write that reached one replica and not W is reported as failed, but it is not rolled back. A later read may or may not return it.
  • Sloppy quorums. If stand-in nodes accept writes during an outage, the nodes that took the write may not be among those the read asks.
  • A read during a write can see the new value from one replica, and the next read can see the old value from the other two.

So a quorum makes fresh reads very likely. It is not linearizability. For compare-and-set or uniqueness I would use a consensus-based feature such as Cassandra’s lightweight transactions, or a different database.

Likely follow-ups

A replica was down for an hour. How does it catch up?
Three mechanisms. Hinted handoff: other nodes kept the writes it missed and replay them when it returns, within a limited window. Read repair: a read that touches a stale copy writes the newer version back. Anti-entropy repair: a background job compares Merkle trees of each replica and streams the differences, which covers keys nobody reads.
Why does deleted data sometimes come back in these systems?
A delete is stored as a tombstone. If one replica misses the tombstone and the others purge it after the grace period, the stale replica's old value looks like live data and repair copies it back. The rule is to run repair on every node more often than the grace period, which is ten days by default in Cassandra.
You have two data centres with three replicas in each. Which consistency level do you use?
Usually a local quorum, two of the three replicas in the client's own data centre. That gives read-your-writes within a data centre with no cross-region round trip, and the other data centre receives the write asynchronously. A quorum over all six needs four acknowledgements, so every request pays wide-area latency.
With no failures at all, does W + R > N give you linearizability?
Not by itself. A read that overlaps a write in progress can return the new value, and a following read can return the old one, unless the read repairs the replicas before it returns. Concurrent writes ordered by wall-clock timestamps can also disagree with real time. Linearizable operations need a consensus protocol.

Common mistakes

  • Saying W + R > N gives strong consistency, with no qualification.
  • Believing the write is sent to only W replicas. It is sent to all N.
  • Forgetting that a failed write is not rolled back on the replicas that took it.
  • Choosing W = 3 "for safety" without noticing that one node failure then stops every write.
  • Ignoring how concurrent writes to the same key are resolved.

A strong answer includes

  • Defines N, W and R and states the overlap rule
  • Gives at least two settings and what each trades in latency and fault tolerance
  • Notes that requests go to all replicas and wait for W or R replies
  • Lists at least two ways a quorum read can still be stale
  • Mentions read repair, hinted handoff or anti-entropy
  • Says when to use a consensus-based operation instead

Revise: Replication

15. You need to shard a multi-tenant orders table. How do you choose the shard key, and what happens to queries that do not include it?

Seniorshardingpartitioningdata-modelling

What the interviewer is really testing

Whether you derive the key from the access patterns, see the tension between even distribution and keeping related data together, and have a plan for the queries and transactions the key makes expensive.

Show the model answer, follow-ups and checklist

Model answer

I would start from the queries, because the shard key decides which of them stay on one shard. Say the main ones are: list a tenant’s recent orders, fetch one of a tenant’s orders by id, create an order with its line items in one transaction, and an occasional internal report across all tenants.

Candidates.

  • tenant_id. Every customer-facing query carries it, a tenant’s orders and line items sit together so order creation is a single-shard transaction, and it never changes. The risk is skew, since tenants differ in size by orders of magnitude.
  • order_id. It spreads perfectly, but listing a tenant’s orders becomes a query to every shard, and related rows scatter.
  • created_at. Every insert lands on the newest shard, which is a hot spot by design.

I would choose tenant_id, hash partitioned, with (tenant_id, order_id) as the primary key so that lookups stay local. To deal with skew I would route through a directory from tenant to logical shard, so a large tenant can be moved to a dedicated shard without touching anyone else.

Queries without the key.

  • Fetch by order id alone, for a support tool or a webhook from a payment provider. Either encode the tenant or shard in the order id so that it routes itself, or keep a small global lookup from order id to tenant.
  • Reports across tenants. Scatter-gather works, but it is slow and only as reliable as the weakest shard, so I would keep it off the serving path. Stream changes into a warehouse and report from there.
  • Lookups by another column, such as customer email. Within one tenant a local index answers it. Across tenants it needs a global index, updated asynchronously, and I would say plainly that it can be briefly stale.

Transactions. Anything within one tenant stays a local transaction. An operation across tenants would need two-phase commit or a saga, so I would check that it is rare.

The trade-off I am accepting is uneven shard sizes in exchange for locality, and I am managing it with the directory.

Likely follow-ups

One tenant becomes 40% of your traffic. Now what?
Hashing cannot split a single key, so first move that tenant to its own shard through the directory. If it outgrows one machine, sub-shard it with a compound key such as tenant id plus a hash bucket of the order id, routed specially for that tenant. Reads for the tenant then fan out over its buckets, which is acceptable because it is confined to one customer.
Why not shard by order id and keep a global index on tenant id?
It works, and it reverses the costs. Order writes spread evenly, but the most common query, a tenant's orders, now goes through an asynchronously updated index and then fans out to many shards. I would choose it only if tenants were so skewed that no tenant-based key could balance.
How do you paginate a query that fans out to 32 shards, sorted by time?
Ask each shard for its first page in sort order using a cursor (the last timestamp and id seen), merge the 32 sorted lists in the router and return the top N. Offset pagination is unusable, because page 100 would need 100 pages from every shard. Latency follows the slowest shard, so set a per-shard timeout and decide whether partial results are acceptable.
Can you change the shard key later?
Only by resharding. You build a new set of shards keyed the new way, backfill them, stream changes in, verify and cut over. Every row moves, so it is a project of weeks or months. That cost is why the key deserves careful analysis at the start.

Common mistakes

  • Choosing the primary key or an auto-increment id by reflex, without looking at the queries.
  • Optimising only for even distribution and scattering rows that are always read together.
  • Picking a timestamp or another steadily increasing key.
  • Saying "we will just scatter-gather" for a query on the hot path.
  • Ignoring the difference in size between tenants.
  • Using a key that can change, such as a status or a region the customer can edit.

A strong answer includes

  • Lists the main queries before proposing a key
  • Compares at least two candidate keys and says what each one breaks
  • Keeps rows that change in one transaction on one shard
  • Addresses skew and has a plan for a very large tenant
  • Explains how lookups without the key are served: routing in the id, a lookup table or a global index
  • Keeps cross-shard reports off the serving path
  • Notes that the key is very expensive to change

Revise: Sharding and partitioning

16. One of your 16 shards is at 90% CPU while the others sit at 20%. How do you find the cause and fix it?

Mid-levelshardinghot-keysdebugging

What the interviewer is really testing

Whether you debug from evidence before reaching for a fix, can tell a hot key from a skewed range from a bad query, and know that adding shards does not split a single key.

Show the model answer, follow-ups and checklist

Model answer

I would not add shards yet. One hot shard out of sixteen means the load is skewed, and more shards will not split a single hot key.

Find the cause. Three things produce this picture, and the metrics tell them apart.

  1. Is it more requests, or more expensive ones? Compare the request rate per shard. If the hot shard has a normal request rate and high CPU, look at its slow queries: a missing index, stale statistics, a long-running job, or compaction or vacuum that has fallen behind. That is a problem with one node, not with the sharding.
  2. If it is more requests, is it one key or many? Sample the queries on the hot shard and count them by shard key. One key or a handful dominating means a hot key: a very large tenant, a celebrity account, a bot, or a default value such as an empty id that many rows share.
  3. If it is many keys, the partitioning is skewed. With range partitioning the hot shard probably owns the newest range and takes every insert. With hand-built hashing, the slots may be unevenly assigned.

Fix according to the cause.

  • A hot key that is mostly read: cache it, and add read replicas to that shard.
  • A hot key that is mostly written: move it to a dedicated shard through the routing table. If one machine cannot hold it, split the key with a bucket suffix so that its writes spread over several partitions, and have reads fan out across the buckets.
  • Abuse: rate limit it.
  • A sequential range key: change the key to lead with a hashed or high-cardinality component.
  • Uneven assignment: move some logical shards off the hot node.

While that work is in progress I would give the hot shard a larger machine or shed its least important load, because either takes minutes.

Afterwards I would add load metrics per shard and for the top keys, so that the next hot key raises an alert long before it reaches 90%.

Likely follow-ups

Would consistent hashing with virtual nodes have prevented this?
Only the uneven-assignment case. Virtual nodes even out how many keys each node owns. A single key that takes a large share of the traffic still maps to one node, whatever the ring looks like.
You split the hot key into ten buckets. What did you make worse?
Reads for that key. Anything that needs all of the key's data now queries ten partitions and merges the results, and ordering across buckets is lost unless you sort in the application. Transactions over the whole key are no longer local. So apply it only to the keys that need it, and keep the bucket count small.
The shard is hot only between 9 and 10 each morning. Does that change your answer?
It points to a workload tied to time: a batch job, a large tenant starting its day, or a key with a time bucket that everyone writes to at once. Check what is scheduled, move or spread the batch work, and if the key contains the date, add a second component so that one day spreads across shards.
How does a managed store such as DynamoDB deal with a hot partition?
It splits partitions as they grow and can split one that receives sustained heavy traffic, and adaptive capacity lets a busy partition use throughput that others are not using. A single item can never be split across partitions, though, so one very hot item is still throttled and needs a different key design.

Common mistakes

  • Adding shards or replicas before finding out why one shard is hot.
  • Assuming it must be a hot key, without checking for one slow query or a maintenance job.
  • Believing that a better hash function fixes a single hot key.
  • Proposing to salt the key without mentioning what it costs on the read side.
  • Stopping at the fix, with no per-key monitoring to catch the next one.

A strong answer includes

  • Separates "more requests" from "more expensive requests" using metrics
  • Samples traffic by shard key to tell one hot key from a skewed range
  • Names concrete causes: a large tenant, a sequential key, a shared default value, a bot, a batch job
  • Matches the fix to the cause: cache, isolate, split the key, change the key, rebalance
  • States that adding shards does not split a single key
  • States the read-side cost of splitting a key
  • Gives a short-term mitigation and adds monitoring afterwards

Revise: Sharding and partitioning

17. Your 8 shards are nearly full. How do you get to 16 without downtime?

Staffshardingmigrationsoperations

What the interviewer is really testing

Whether you can plan an online data migration: copy, catch-up, verification, cutover and rollback, with attention to correctness during the switch. Staff-level answers also cover throttling, stale routers and how to avoid repeating the project.

Show the model answer, follow-ups and checklist

Model answer

I would treat this as a migration with a way back at every stage, not as one operation.

What makes it cheap or expensive. If keys map to many logical shards, say 1,024, hosted on 8 machines, going to 16 means moving half of the logical shards and updating the map. If keys map by hash mod 8, doubling is the one friendly case: a key in shard s goes to s or to s + 8, so each shard splits in two. I would use this migration to introduce logical shards, so that the next step does not have to be a doubling.

The procedure, for each shard.

  1. Copy. For a split, the simplest method is to attach the new node as a replica of the old shard. It receives a full copy and then every change through the normal replication stream. Otherwise, backfill from a snapshot and apply changes from the log.
  2. Catch up until the new node is less than a second behind. Throttle the copy so that live traffic is not starved.
  3. Verify. Compare row counts and checksums by key range.
  4. Cut over. Pause writes for the moving keys for a few seconds, let the new shard apply the final changes, promote it, and publish a new version of the routing map. The map lives in a consensus-backed store, and every shard rejects requests for keys it no longer owns, so a router with a stale map cannot write to the wrong place.
  5. Keep a way back. Replicate from new to old for a while so that the switch can be reversed.
  6. Clean up. Delete the rows that no longer belong on each side, slowly.

Throughout, I would watch replication lag, error rates per shard, and requests arriving at a shard that no longer owns the key.

I would migrate one shard first, then the rest in sequence. The whole project takes days to weeks, mostly waiting for copies. The only thing users should notice is a few seconds of slower writes at each cutover.

Likely follow-ups

Why not have the application write to both the old and new shards, instead of using the replication log?
Dual writes are two separate commits. A crash or a timeout between them leaves the copies different with nothing to detect it, and concurrent writers can apply updates in a different order on each side. The replication log already holds every change in commit order. If dual writing is unavoidable, treat one side as the source of truth and reconcile continuously.
During cutover a router with a stale map sends a write to the old shard. What happens?
It must be rejected. Each shard knows which keys it owns and at which map version, and refuses requests for keys it has handed over. The router then refreshes its map and retries. Without that check the write lands on the old shard after the switch and is silently lost.
Can you avoid the write pause at cutover completely?
You can shrink it to well under a second, but something has to order the last write on the old shard before the first write on the new one. The usual answer is a very short pause during which the proxy buffers requests, so clients see a little extra latency and no errors.
How do you avoid this project next time?
Separate logical placement from physical placement: many logical shards or small ranges, a routing map, and tooling that moves one unit at a time as a routine operation. Growth is then a series of small moves. Range-splitting databases and Redis Cluster slot migration provide this out of the box.

Common mistakes

  • Proposing a maintenance window or a stop-the-world copy for a system that must stay up.
  • Changing the modulus and re-hashing everything without working out how much data moves.
  • Relying on dual writes from the application with no reconciliation.
  • No verification before cutover and no rollback plan after it.
  • Forgetting routers and clients that still hold the old map during the switch.
  • Deleting the old data immediately.

A strong answer includes

  • Explains how the mapping from key to shard determines how much data moves
  • Describes copy, catch-up, verify, cutover and clean-up in order
  • Uses the replication log or change data capture to keep the copy current
  • Makes the routing change versioned, and has shards reject keys they no longer own
  • Keeps a rollback path after cutover
  • Throttles the copy and migrates one shard first
  • Proposes logical shards or range splitting so that future growth is routine

Revise: Sharding and partitioning

18. Why not just use hash(key) mod N to pick a shard?

Seniorpartitioningconsistent-hashing

What the interviewer is really testing

Whether you understand what happens to data placement when the cluster changes size, and whether you can reason about the cost of moving data rather than only its steady-state distribution.

Show the model answer, follow-ups and checklist

Model answer

Mod N is fine while N never changes. It spreads keys evenly and needs no state. The trouble starts when a node is added or removed, because the divisor changes and almost every key gets a different answer.

For a cache, that means nearly every lookup misses at once and the full read load lands on the database, often at the moment you were adding capacity because traffic was high. For a database shard, it means migrating nearly all of the data to change the cluster size by one node.

Consistent hashing fixes the mapping. Hash both nodes and keys onto a ring, and give each key to the first node clockwise. Adding a node takes over part of one arc; removing a node hands its arc to the next one. Either way about 1/N of keys move, which is the minimum possible.

Two refinements make it production-ready:

  • Virtual nodes. Place each server at a few hundred points so load is even and a failure is spread across many survivors.
  • Replication. Store each key on the next R distinct servers clockwise, with rack or zone awareness.

I would also say what it does not do: a single hot key still lands on a single node. And I would mention that a fixed slot table, as in Redis Cluster, gets the same low-movement property with more operational control, so the choice depends on whether I want rebalancing to be automatic or explicit.

Likely follow-ups

How many keys move when you go from N to N+1 nodes with consistent hashing?
About K/(N+1) for K keys, which is the share the new node has to take anyway. With mod N the share that moves is close to N/(N+1), so nearly everything.
Your ring has 5 nodes and one holds 35% of the keys. Why, and what do you do?
Five random points rarely split a ring evenly. Give each node 100 or more virtual nodes so its share is an average over many small arcs, and weight the count by machine capacity.
One key receives 20% of all traffic. Does consistent hashing help?
No. It balances the number of keys per node, and a hot key is still one key on one node. Handle it separately with a local cache in front, by splitting the key (for example adding a suffix and fanning reads out), or by giving it dedicated capacity.
When would you choose a fixed slot table instead of a ring?
When you want rebalancing to be an explicit operation. Redis Cluster's 16,384 slots let you move named slots between nodes at a controlled pace. The price is a routing table that clients or a proxy must keep up to date.

Common mistakes

  • Saying mod N distributes keys unevenly. It distributes them well; the problem is only what happens when N changes.
  • Describing the ring but not virtual nodes, then being unable to explain uneven load.
  • Claiming consistent hashing solves hot keys.
  • Forgetting that data still has to be streamed or re-fetched when ownership changes.

A strong answer includes

  • States that changing N remaps nearly every key and explains the consequence (cache wipe-out or mass data migration)
  • Describes the ring and the clockwise ownership rule
  • Adds virtual nodes and says what they fix
  • Quantifies movement as roughly 1/N of keys
  • Mentions at least one alternative (slot table, rendezvous hashing or range partitioning)
  • Notes that hot keys need separate handling

Revise: Consistent hashing

19. In two-phase commit, what happens if the coordinator crashes after the participants have voted yes?

Seniortransactionstwo-phase-commitfailure-modes

What the interviewer is really testing

Whether you understand why two-phase commit blocks, at the level of what each node knows and is allowed to do, and whether you connect that to the practical cost (held locks) and to how modern systems remove the single coordinator.

Show the model answer, follow-ups and checklist

Model answer

The participants are stuck, and it is worth spelling out why.

In phase one each participant wrote the transaction to its log and voted yes. A yes vote is a promise to commit if told to, so the participant has given up its right to abort. The coordinator was collecting the votes, and would then write its decision to its own log and send it out.

If the coordinator crashes at that point, a participant that has voted yes and heard nothing is in doubt:

  • It cannot commit, because another participant may have voted no, in which case the decision is abort.
  • It cannot abort, because the coordinator may have logged commit and already told another participant, which has committed.

A timeout does not help, since either guess can break atomicity. So the participant waits, and while it waits it holds every lock the transaction took. Other transactions that need those rows queue behind them. That is the real damage: the crash of one process becomes stalled queries in every participating database.

What the participants can try. They can ask each other. If any one of them has received the decision, the others can follow it. If one of them has not voted yet, it can still abort, and then the decision must be abort. If all of them voted yes and none has heard, they cannot resolve it.

How it ends. When the coordinator restarts, it reads its log. If it finds a commit record, it resends commit. If it finds no decision, it aborts. If its disk is gone, an operator must resolve each in-doubt transaction by hand, by checking what the other participants did.

How to avoid it. Make the coordinator’s decision survive a machine failure by writing it to a log replicated with Paxos or Raft. Another replica then takes over and completes the protocol within seconds. That is what Spanner and CockroachDB do. The other answer is not to run a transaction across systems at all, and to use a saga with compensations, accepting weaker isolation.

Likely follow-ups

Why can the participants not just elect a new coordinator among themselves?
They can, and it can finish the job if any reachable participant knows the decision or has not yet voted. If every reachable participant is in doubt and one participant is unreachable, that one may already have committed or aborted, so no safe decision exists. That gap is exactly what makes the protocol blocking.
Does three-phase commit solve this?
Only under assumptions that real networks do not meet: bounded message delay and no partitions, so that a silent node is definitely crashed. With a partition, the two sides can time out into different decisions. In practice people run two-phase commit with a coordinator that is replicated by consensus.
What does a stuck prepared transaction look like in PostgreSQL?
It is listed in pg_prepared_xacts and survives restarts. It holds its row locks, so other sessions block on those rows, and it stops vacuum from removing dead row versions, so tables bloat. An operator has to run COMMIT PREPARED or ROLLBACK PREPARED with the correct outcome.
The coordinator crashes before it has sent any prepare message. Is that a problem?
No. Nobody has voted, so each participant can abort on a timeout and release its locks. The dangerous window opens when a participant votes yes and closes when it learns the decision.

Common mistakes

  • Saying the participants simply time out and abort.
  • Saying the transaction is rolled back automatically.
  • Reciting the protocol steps without saying what a participant is forbidden to do after voting yes.
  • Missing that locks stay held and block unrelated transactions.
  • Claiming three-phase commit fixes the problem on real networks.
  • Confusing two-phase commit with two-phase locking.

A strong answer includes

  • States that a yes vote removes the participant's right to abort
  • Explains why neither commit nor abort is safe for an in-doubt participant
  • Names held locks as the practical damage
  • Describes recovery from the coordinator log, including abort when no decision was logged
  • Notes that participants can resolve it if any one of them knows the outcome
  • Gives the modern fix (replicate the coordinator with consensus) or the alternative (a saga)

Revise: Distributed transactions and two-phase commit

20. Checkout must create an order, charge a card and reserve stock across three services. Two-phase commit or a saga, and how do you design the compensations?

Seniorsagastransactionsmicroservices

What the interviewer is really testing

Whether you justify the choice from the properties of the participants, and whether your saga survives failure: step ordering, idempotent compensations, visible intermediate states and what happens when a compensation fails.

Show the model answer, follow-ups and checklist

Model answer

A saga. Two-phase commit needs every participant to support prepare and to hold locks until the decision arrives. The card processor is an external HTTP API with no prepare step, authorisation can take seconds, and I do not want checkout to fail whenever any one of three services is down. If these were three tables in one database I would use an ordinary local transaction.

The steps, ordered by how reversible they are.

  1. Create the order as PENDING. Compensation: mark it REJECTED.
  2. Reserve the stock, with an expiry. Compensation: release the reservation.
  3. Authorise the card (a hold, not a capture). Compensation: release the hold.
  4. Capture the payment. This is the pivot. After it the saga only moves forward.
  5. Confirm the order and schedule fulfilment, retried until they succeed.

Cheap steps that are likely to fail come first, and the step that is expensive to undo comes last. I use a hold because releasing it barely affects the customer, while reversing a capture means a refund.

Coordination. An orchestrator that persists the saga state, because there are five steps with timeouts and I want one place to ask where an order is stuck.

Making compensations safe.

  • Every step and compensation carries the saga id as an idempotency key, because messages are delivered at least once.
  • A compensation can arrive before its step, if the step’s request was slow and timed out. The service records the cancellation and refuses the late step.
  • Compensations are retried with backoff. If one keeps failing, the saga is parked in a failed state and a person is alerted.
  • Each service writes its reply to an outbox table in the same transaction as its state change, so a crash cannot separate the two.

Isolation. The pending order and the reservation are visible while the saga runs. So the user sees “processing”, and other code treats PENDING as a lock.

The trade-off: I give up isolation for a short window, and in return checkout stays available and can include an external system.

Likely follow-ups

The charge succeeded, but the reply was lost and the orchestrator timed out. What happens?
The orchestrator does not know the outcome, so it must not assume failure. It retries with the same idempotency key, and the payment service or processor returns the original result instead of charging twice. Only a definite failure, or a lookup showing that no charge exists, leads to compensation.
The warehouse has already shipped the parcel when a later step fails. How do you compensate?
You cannot undo it, which means the design is wrong. An irreversible step must come after the pivot, where nothing later can force the saga backwards. If it really can happen, the compensation is a business process such as a return label and a refund, not a technical undo.
Would you use choreography instead?
For two or three steps with a stable flow, yes: services react to each other's events and there is no extra component. With five steps, timeouts and compensations, the flow would be spread across several codebases and hard to trace, so I would keep the orchestrator and keep the business rules in the services.
Two sagas try to reserve the last item at the same moment. What stops overselling?
The inventory service does, inside its own local transaction: a conditional update that reduces available stock only if it is greater than zero. One saga's step succeeds, the other fails and compensates. A saga provides no isolation between sagas, so each service must protect its own invariants.

Common mistakes

  • Choosing two-phase commit without noticing that an external payment API cannot take part.
  • Describing compensation as a rollback, as if the earlier steps never happened.
  • Capturing the payment first and refunding on failure, when a hold would avoid the refund.
  • Assuming compensations always succeed and messages arrive exactly once.
  • Ignoring that intermediate states are visible to users and to other requests.
  • Treating a timeout as a failure and compensating a payment that went through.

A strong answer includes

  • Justifies the saga from the participants: external API, lock duration, availability
  • Says when a local transaction or two-phase commit would be the better choice
  • Orders the steps so that irreversible ones come last, and names the pivot
  • Gives a compensation for each reversible step
  • Makes steps and compensations idempotent and handles out-of-order arrival
  • States what happens when a compensation keeps failing
  • Covers the missing isolation with pending states or reservations
  • Mentions the outbox or an equivalent for reliable messaging

Revise: Sagas

21. You put leader election in etcd. Why does it need three nodes and not two, and what does Raft actually guarantee you?

Seniorconsensusraftleader-election

What the interviewer is really testing

Whether you can explain the majority requirement from the overlap of quorums, state the guarantees of Raft precisely without overclaiming, and name what it costs in latency, throughput and availability.

Show the model answer, follow-ups and checklist

Model answer

Why a majority, and why three. Raft commits a write only when a majority of the cluster has stored it, and elects a leader only with votes from a majority. Any two majorities share at least one node. So two leaders cannot both win the same term, and the voters for a new leader always include a node that holds every committed entry.

With two nodes the majority is two, so losing either one stops the cluster, and it is less available than a single node. With three the majority is two, so one node can fail. Five tolerate two. Four still tolerate only one, so an even size adds cost and no safety. I would run three or five, spread over three zones.

What Raft guarantees.

  • At most one leader per term. A stale leader’s messages carry an old term and are rejected.
  • Once a write is acknowledged it is on a majority and will be in the log of every future leader. It is lost only if a majority of nodes lose their data.
  • Every node applies the same commands in the same order. With reads that confirm leadership first, the store is linearizable.

What it does not guarantee.

  • Availability without a majority. In a partition the minority side refuses writes, deliberately.
  • Progress on a very unstable network. Safety always holds, but electing a leader needs a period of stability.
  • Protection against nodes that lie or corrupt data. It assumes nodes fail by stopping.
  • That my own “leader” process is safe to act. A process holding an etcd lease can pause and then act after the lease has expired, so whatever it writes to must check a fencing token.

What it costs. Every write is a round trip to a majority plus a disk flush, and all writes go through one leader. Throughput does not grow when I add nodes. That is fine for elections, locks and configuration, and it is the reason I would not put application data in etcd.

Likely follow-ups

Three nodes across two data centres: is that enough?
No. One data centre holds two of the three nodes, and losing it loses the majority. The majority has to survive the loss of any one failure domain, so use three zones or regions with one node in each, or five nodes placed two, two and one.
An old leader is partitioned away and has not noticed. Can a client read stale data from it?
It cannot commit writes, because it cannot reach a majority. Reads are the risk: if it answers from local state it may return old data. Raft implementations make linearizable reads confirm leadership with a heartbeat round to a majority, or use a leader lease that depends on bounded clock drift. etcd reads are linearizable by default, and its serializable reads trade that away for speed.
How is Raft different from Paxos?
They give the same guarantee and both rely on majorities. Multi-Paxos with a stable leader behaves much like Raft. Raft restricts who may become leader to nodes with an up-to-date log, so entries only ever flow from leader to followers, and it specifies elections and membership changes in full. Paxos is more general and leaves more to the implementer.
Why are election timeouts randomised?
If all followers timed out together they would all become candidates, each would vote for itself and nobody would reach a majority. With random timeouts one node usually times out first, asks for votes and wins before the others start. Split votes still happen occasionally and the next round, with new random timeouts, resolves them.

Common mistakes

  • Saying "you need an odd number to break ties" without explaining why majorities must overlap.
  • Claiming consensus keeps the system available during any partition.
  • Believing that adding nodes increases write throughput.
  • Assuming that holding a lock or lease in etcd makes a paused process safe, with no fencing token.
  • Placing a majority of the nodes in one failure domain.
  • Saying Raft tolerates malicious or corrupted nodes.

A strong answer includes

  • Explains the majority requirement by the overlap of any two majorities
  • Shows why two nodes are worse than one and why cluster sizes are odd
  • States the guarantees: one leader per term, committed entries survive, the same order on every node
  • States the limits: no progress without a majority, crash failures only
  • Gives the cost: a majority round trip and a disk flush per write, through a single leader
  • Spreads nodes across at least three failure domains
  • Mentions fencing tokens or the stale-leader read problem

Revise: Consensus: Raft and Paxos