← Interview prep

System Design interview questions

Scalable architecture, storage, and distributed design.

100 questions · Page 5 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 5 of 5

Questions 81–100 of 100 · 0 of 20 on this page marked learned

81.system-design-0081Mediumfresher

How do geo-indexes work? Compare geohash, quadtrees and cell systems such as Google S2 and Uber H3 for finding nearby points.

All of them turn two-dimensional locations into cells so a "nearby" query becomes a lookup of a few cells instead of a scan. Geohash interleaves latitude and longitude bits into a string where a shared prefix means close by, so it works with any string index. Quadtrees split space adaptively, giving small cells where points are dense. S2 maps the sphere onto cube faces with a space-filling curve, and H3 uses hexagons of equal-ish size, which make neighbour and distance logic simpler.

Full answer

The problem

"Find drivers within 2 km" over millions of moving points cannot compute the distance to every point. A spatial index groups points into cells, so a query reads only the cells that overlap the search circle, then filters by exact distance.

Geohash

Split the world in half by longitude (left or right, one bit), then by latitude (bottom or top, one bit), and repeat, interleaving bits. Every 5 bits become one base32 character. A 6-character geohash is a cell of about 1.2 km by 0.6 km.

python
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"


def geohash(lat, lng, precision=6):
    """Interleave longitude and latitude bits, 5 bits per base32 character."""
    lat_rng, lng_rng = [-90.0, 90.0], [-180.0, 180.0]
    bits, even, out, ch, n = 0, True, [], 0, 0
    while len(out) < precision:
        rng, val = (lng_rng, lng) if even else (lat_rng, lat)
        mid = (rng[0] + rng[1]) / 2
        if val >= mid:
            ch = (ch << 1) | 1
            rng[0] = mid
        else:
            ch <<= 1
            rng[1] = mid
        even, n = not even, n + 1
        if n == 5:
            out.append(BASE32[ch])
            ch, n = 0, 0
    return "".join(out)


if __name__ == "__main__":
    assert geohash(57.64911, 10.40744, 11) == "u4pruydqqvj"     # published reference value
    a = geohash(12.9716, 77.5946)          # Bengaluru centre
    b = geohash(12.9750, 77.5990)          # about 600 m away
    c = geohash(28.6139, 77.2090)          # New Delhi
    assert a[:5] == b[:5] and a[:2] != c[:2]
    print("ok:", a, b, c)

Save as geohash.py and run python3 geohash.py (Python 3.13.5).

Strengths: one string column with a normal B-tree index; prefix queries are range scans. Weaknesses: cells are rectangles whose size depends on latitude, and two points next to each other across a cell edge can have very different hashes, so queries must include the 8 neighbouring cells.

Quadtree

Start with one square; when a node holds more than a set number of points (say 100), split it into four children. Dense city centres end up with tiny cells and oceans with huge ones, so each leaf has a similar load. Usually kept in memory and rebuilt or updated as points move; a good fit for uneven, mostly static data such as business listings.

S2 and H3

  • S2 projects the earth onto the six faces of a cube and orders cells along a Hilbert curve, which keeps nearby cells close in ID order. Cells have 31 levels and cover any region with a small set of cell ID ranges. Used for region coverage and indexing in large map systems.
  • H3 divides the earth into hexagons at 16 resolutions. Every hexagon has six neighbours at the same distance, which suits movement, demand heat maps and pricing zones (as in ride-hailing).

Choosing

  • Need it inside an existing SQL or key-value store: geohash.
  • Very uneven density, in memory: quadtree.
  • Global coverage, polygons, precise covering: S2.
  • Neighbour analysis, aggregation by area, smooth movement: H3.

In every case the query pattern is the same: pick a resolution near the search radius, collect candidate cells, fetch points, filter by exact distance.

By level

Fresher: Explain that the map is divided into named squares and nearby points share most of the name. A fresher should know to check neighbouring squares too.

Mid: Compare geohash and quadtrees on density and storage, and describe the candidate-then-filter query. Pick a resolution from the search radius.

Senior: Discuss S2 coverings and H3 hexagon properties, moving-object updates, polygon queries and when each system fits. Expect awareness of edge effects at every level.

Key points

  • All methods turn locations into cells so nearby queries read a few cells
  • Geohash: interleaved bits, shared prefix means nearby, needs neighbour cells
  • Quadtree adapts cell size to density
  • S2 uses cube faces and a Hilbert curve; H3 uses hexagons
  • Always finish with an exact distance filter

Common mistakes

  • Assuming a shared geohash prefix is the only way points can be close
  • Forgetting the 8 neighbour cells
  • Using one fixed resolution for dense and empty areas
  • Skipping the exact distance check

Follow-ups

  • How would you index moving drivers that update every 4 seconds?
  • Why do hexagons help for heat maps?
  • How do you search within a polygon such as a city boundary?

Tips

  • Explain geohash by halving the map
  • Give one reason to pick each method
  • State the query pattern in three steps

Evaluation rubric

  • Correct explanation of geohash
  • Understands neighbours and edge effects
  • Compares quadtrees, S2 and H3 sensibly
  • Clear selection criteria
82.system-design-0082Hardsenior

CRDTs versus operational transformation: how does each make concurrent edits converge, and when would you choose one over the other?

Operational transformation keeps operations as they are typed and transforms each incoming operation against concurrent ones, usually through a central server that fixes one order. CRDTs design the data type so that concurrent operations commute: merging is commutative, associative and idempotent, so replicas converge in any delivery order without a coordinator. OT fits server-centred editors with compact documents; CRDTs fit offline-first and peer-to-peer apps, at the cost of extra metadata.

Full answer

The shared goal

Several replicas apply edits concurrently and must end in the same state (convergence) while keeping each user's intent.

Operational transformation (OT)

An operation such as "insert 'X' at position 5" depends on the document it was made on. If another user deleted position 2 at the same time, applying the insert unchanged would put X in the wrong place. OT defines a transform function T(op1, op2) that adjusts op1 to apply after op2 (the insert moves to position 4).

In practice a central server orders all operations per document. Each client sends operations with the version it was based on; the server transforms them against everything accepted since and broadcasts the result. Clients transform their own pending operations against incoming ones.

  • Strengths: small operations, compact documents, history is a simple log; proven in large editors.
  • Weaknesses: transform functions are tricky to get right for every pair of operation types; peer-to-peer OT without a central order is hard.

CRDTs

A CRDT (conflict-free replicated data type) guarantees convergence by construction. State-based CRDTs merge whole states with a join that is commutative, associative and idempotent; operation-based CRDTs send operations that commute.

The simplest example is a grow-only counter:

python
class GCounter:
    """Grow-only counter CRDT: each replica increments its own slot; merge takes the max."""

    def __init__(self, replica):
        self.replica, self.slots = replica, {}

    def increment(self, n=1):
        self.slots[self.replica] = self.slots.get(self.replica, 0) + n

    def merge(self, other):
        for r, v in other.slots.items():
            self.slots[r] = max(self.slots.get(r, 0), v)

    def value(self):
        return sum(self.slots.values())


if __name__ == "__main__":
    a, b, c = GCounter("a"), GCounter("b"), GCounter("c")
    a.increment(3)
    b.increment(2)
    c.increment(5)
    a.merge(b); b.merge(c); c.merge(a); a.merge(c); b.merge(a)   # any order, repeated merges
    assert a.value() == b.value() == c.value() == 10
    a.merge(a)                                                    # idempotent
    assert a.value() == 10
    print("ok: all replicas converge to", a.value())

Save as gcounter.py and run python3 gcounter.py (Python 3.13.5).

For text, sequence CRDTs (RGA, Yjs, Automerge) give each character a unique ID and a position defined relative to its neighbours' IDs, so inserts and deletes can be applied in any order. Deleted characters often remain as tombstones.

  • Strengths: no central server needed; works offline for days and merges later; replicas can sync peer to peer.
  • Weaknesses: metadata per character and tombstones increase memory; some intentions (move a paragraph, rich-text formatting spans) need careful design; garbage collection of tombstones needs coordination.

Choosing

  • Central server, always online, very large documents: OT (or a server-ordered CRDT).
  • Offline-first mobile apps, local-first software, peer-to-peer sync: CRDTs.
  • Simple shared state such as counters, sets, flags: CRDTs are easy and safe.

Both guarantee convergence, not that the result is what users wanted; two people retyping the same word still produce a duplicated word.

By level

Fresher: Explain that two people editing at once can conflict, and that both methods make every copy end up the same. A fresher should explain the position shift example.

Mid: Describe OT with a central server and CRDTs with unique IDs and commutative merges. Use the counter example to show convergence.

Senior: Discuss tombstones and metadata cost, rich text, garbage collection, server-ordered CRDTs and correctness of transform functions. Expect a clear decision framework.

Key points

  • OT transforms concurrent operations, usually with a central order
  • CRDT merges are commutative, associative and idempotent
  • Sequence CRDTs give each character a unique ID
  • CRDTs suit offline and peer-to-peer; OT suits server-centred editors
  • Convergence does not guarantee the merged text matches intent

Common mistakes

  • Thinking last-write-wins is a CRDT solution for text
  • Assuming OT works peer to peer without extra machinery
  • Ignoring tombstone growth in CRDTs
  • Claiming either method removes all semantic conflicts

Follow-ups

  • How do you garbage-collect CRDT tombstones?
  • How would you represent bold text ranges in a CRDT?
  • How does a server-ordered CRDT combine both ideas?

Tips

  • Give the insert and delete position example
  • Show a tiny CRDT such as a counter
  • Tie the choice to online versus offline use

Evaluation rubric

  • Correct explanation of OT transforms
  • Correct CRDT properties
  • Balanced trade-offs
  • Clear selection guidance
83.system-design-0083Mediumfresher

What are vector clocks, and how do they tell whether two versions of data happened one after the other or concurrently?

A vector clock is a map from node to counter attached to each version. A node increments its own entry when it writes and merges clocks when it receives data. Version A happened before B if every entry in A is less than or equal to B's; if neither is less or equal, the versions are concurrent and must be merged or shown as a conflict. Physical timestamps cannot tell these cases apart reliably because clocks drift.

Full answer

Why not timestamps?

Servers' clocks differ by milliseconds or more. With "last write wins" by timestamp, a write that happened later can lose to an earlier write from a server with a fast clock, and true concurrent writes are silently dropped. We need to capture causality: did one write see the other?

Lamport clocks first

A Lamport clock is a single counter: increment on each event, and on receiving a message set the counter to max(local, received) + 1. If A caused B, A's counter is smaller. But the reverse does not hold: a smaller counter does not prove A caused B. Lamport clocks give an order, not concurrency detection.

Vector clocks

Each version carries {node: counter}:

  • When node N writes, it increments clock[N].
  • When data is merged, take the per-node maximum, then increment your own entry for the new write.
  • Compare two clocks entry by entry:
    • all entries of A <= B: A happened before B (B can replace A);
    • all entries of A >= B: A happened after B;
    • otherwise: concurrent; keep both versions (siblings) until something resolves them.
python
def merge(a, b):
    return {k: max(a.get(k, 0), b.get(k, 0)) for k in a.keys() | b.keys()}


def compare(a, b):
    """Return 'before', 'after', 'equal' or 'concurrent'."""
    keys = a.keys() | b.keys()
    le = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
    ge = all(a.get(k, 0) >= b.get(k, 0) for k in keys)
    if le and ge:
        return "equal"
    return "before" if le else "after" if ge else "concurrent"


def tick(clock, node):
    c = dict(clock)
    c[node] = c.get(node, 0) + 1
    return c


if __name__ == "__main__":
    v1 = tick({}, "A")                     # A writes:            {A:1}
    v2 = tick(v1, "B")                     # B updates after it:  {A:1, B:1}
    v3 = tick(v1, "C")                     # C updates v1 too:    {A:1, C:1}
    assert compare(v1, v2) == "before" and compare(v2, v1) == "after"
    assert compare(v2, v3) == "concurrent"         # a real conflict: keep both
    v4 = tick(merge(v2, v3), "A")                  # A resolves: {A:2, B:1, C:1}
    assert compare(v2, v4) == "before" and compare(v3, v4) == "before"
    print("ok:", sorted(v4.items()))

Save as vector_clock.py and run python3 vector_clock.py (Python 3.13.5).

Where they are used

Dynamo-style stores (Riak, the original Dynamo) attach vector clocks to values and return siblings to the client on a conflict; the shopping cart example merged sibling carts by union. Version vectors (one entry per replica rather than per client) are the same idea used for replica sync.

Costs

  • Clock size grows with the number of writers. Using replica IDs instead of client IDs bounds it; old entries can be pruned with care (pruning can create false conflicts).
  • The application must know how to merge concurrent versions; the clock only detects them.

Key point

Vector clocks answer "did one write know about the other?" Timestamps answer "which clock said a bigger number?" Only the first question is safe for conflict detection.

By level

Fresher: Explain that each server keeps a count of its own writes inside the data, and that comparing the counts shows which version is newer. A fresher should identify two concurrent versions in an example.

Mid: Explain Lamport clocks, vector clock rules, siblings and Dynamo-style use. Compare clearly with timestamp-based last-write-wins.

Senior: Discuss version vectors, pruning trade-offs, client versus replica IDs, and application-level merges. Expect precise reasoning about causality.

Key points

  • A vector clock maps each node to a counter
  • Increment your own entry on write; take per-node maximum on merge
  • All entries less or equal means happened before
  • Otherwise the versions are concurrent and need merging
  • Timestamps cannot detect concurrency because clocks drift

Common mistakes

  • Treating a larger Lamport counter as proof of causality
  • Using wall-clock last-write-wins and calling conflicts solved
  • Forgetting to merge before incrementing
  • Ignoring clock size growth with many writers

Follow-ups

  • How do version vectors differ from vector clocks?
  • What does a store do with sibling versions?
  • How could pruning cause false conflicts?

Tips

  • Walk through a three-step example with two writers
  • State the comparison rule exactly
  • Contrast with timestamps

Evaluation rubric

  • Correct update and merge rules
  • Correct comparison and concurrency detection
  • Knows practical uses
  • Mentions size and merge costs
84.system-design-0084Mediummid

How do gossip protocols spread information such as cluster membership and failure detection, and why do they scale to thousands of nodes?

In each round, every node picks a few random peers and exchanges what it knows (member list, heartbeats, versions). Information spreads like an epidemic: the number of informed nodes roughly doubles each round, so news reaches all n nodes in about log n rounds while each node sends only a constant number of messages. Failure detection protocols such as SWIM add indirect probes so one slow link does not cause a false failure. The cost is eventual, probabilistic propagation rather than instant agreement.

Full answer

The problem

A cluster of 2,000 nodes must know who is alive. Having every node ping every other node is about 4 million messages per round, and a central monitor is a single point of failure.

How gossip works

Every second (one round), each node:

  1. Picks k random peers (often 1 to 3).
  2. Sends its view: a list of members with heartbeat counters and versions of any shared state.
  3. Merges what it receives, keeping the newer version of each entry.

If one node learns something new, after one round about 2 nodes know it, then 4, then 8. With 2,000 nodes, about log2(2,000), roughly 11 rounds plus a few for the long tail, reach almost everyone. Each node's work per round is constant, so total traffic grows only linearly with cluster size.

Styles:

  • Push: send your news. Pull: ask for theirs. Push-pull converges fastest.
  • Anti-entropy: periodically compare full state (or Merkle tree summaries) to fix anything missed.
  • Rumour mongering: spread a new item for a limited number of rounds, then stop.

Failure detection with SWIM

Heartbeats through gossip detect failures, but slowly and with false alarms. SWIM improves this:

  1. Node A pings a random node B directly.
  2. If there is no reply, A asks k other nodes to ping B for it (indirect probe), which separates "B is down" from "the A-B link is bad".
  3. If still no reply, B is marked suspect and this is gossiped; B can refute it by gossiping a higher incarnation number. After a timeout, B is declared dead.

Phi-accrual detectors (used by Cassandra and Akka) output a suspicion level based on heartbeat arrival history rather than a fixed timeout.

Where it is used

Cassandra and other Dynamo-style stores (membership and token ownership), Consul and Serf (membership and events), and cluster schedulers.

Trade-offs

  • Propagation is probabilistic and takes seconds; it is not consensus. Decisions that need agreement (who is the leader, committed writes) use Raft or Paxos instead.
  • Message size grows with state; large clusters gossip digests and fetch details only when versions differ.
  • Network partitions produce two views until healed; anti-entropy fixes them afterwards.

By level

Fresher: Explain that each server shares news with a few random others each second, and the news spreads quickly to everyone. A fresher should see why this is cheaper than everyone messaging everyone.

Mid: Give the log n reasoning, push and pull styles, anti-entropy and SWIM indirect probes. Name systems that use gossip.

Senior: Discuss phi-accrual detection, incarnation numbers, digest-based exchange, partitions and the line between gossip and consensus. Expect convergence estimates.

Key points

  • Each round, nodes exchange state with a few random peers
  • Information reaches all nodes in about log n rounds
  • Constant work per node per round, so it scales
  • SWIM uses indirect probes and suspicion to reduce false failures
  • Gossip gives eventual propagation, not consensus

Common mistakes

  • Using all-to-all heartbeats in large clusters
  • Treating gossip as a way to agree on a leader
  • Declaring nodes dead on one missed heartbeat
  • Sending full state every round as clusters grow

Follow-ups

  • How does Cassandra use gossip for token ownership?
  • What is the incarnation number in SWIM for?
  • How would you estimate convergence time for 10,000 nodes?

Tips

  • Explain the doubling intuition with numbers
  • Describe indirect probing
  • State clearly what gossip cannot do

Evaluation rubric

  • Correct gossip mechanics and log n spread
  • Explains failure detection and false positives
  • Names real uses
  • Clear limits compared with consensus
85.system-design-0085Mediummid

How do services elect a single leader using a coordination service such as etcd or ZooKeeper, and how do leases and fencing prevent two leaders during a network partition?

Candidates try to create the same key (or the lowest sequential ephemeral node) in the coordination service; the winner holds a lease that it must renew, and others watch the key. If the leader stops renewing because it crashed or is cut off, the lease expires and another candidate wins. Because an old leader may not know it lost, each new term gets a higher number (fencing token) that storage systems check, so stale leaders' writes are rejected.

Full answer

Why one leader

Some jobs must run on exactly one instance: a scheduler that assigns work, a primary database, a process that sends invoices. Running two at once (split brain) causes duplicate or conflicting actions.

Recipe with etcd

  1. Each candidate creates a lease with a TTL (for example 10 seconds) and tries a transaction: "create key /election/billing with my ID and this lease, only if the key does not exist".
  2. The one that succeeds is the leader; it renews the lease every few seconds.
  3. Others watch the key. When it disappears (lease expired or leader resigned), they try again.
  4. The key's creation revision is a monotonically increasing number that can serve as a fencing token.

ZooKeeper's recipe: every candidate creates an ephemeral sequential node under /election; the lowest number is leader, and each candidate watches only the node just before it, which avoids a thundering herd when the leader goes.

The coordination service itself runs Raft (etcd) or Zab (ZooKeeper), so its view is consistent across its own replicas.

The dangerous case

The leader pauses for 15 seconds (a long garbage collection pause or a network partition). Its lease expires and a new leader is elected. The old leader wakes up still believing it is leader and continues writing.

Defences:

  • Leases with margin. The leader stops acting before its lease would expire by its own clock, minus a safety margin for clock drift. This helps but cannot cover every pause.
  • Fencing tokens. Every leader term has a number that increases. The leader attaches it to each write; the storage system remembers the highest token seen and rejects lower ones. The old leader's writes then fail even if it never notices.
  • Checking leadership on each action through the coordination service adds latency but narrows the window.

Other approaches

  • Raft and Paxos build election into the data system itself (for example a database's replicas elect their own primary), so no external service is needed.
  • The bully algorithm (highest ID wins) is simple but unsafe under partitions without a quorum.

Trade-offs

Short leases give fast failover but risk spurious elections during brief network blips; long leases mean longer outages when a leader truly dies. 5 to 15 seconds is common.

By level

Fresher: Explain that servers race to write one shared key and the winner becomes leader until it stops renewing. A fresher should explain why two leaders would be harmful.

Mid: Describe etcd and ZooKeeper recipes, watches, lease renewal and the pause scenario. Introduce fencing tokens.

Senior: Discuss safety margins and clock drift, fencing with real storage systems, quorum loss in the coordination service, and embedded Raft as an alternative. Expect precise failure timelines.

Key points

  • Candidates race to create one key or the lowest sequential ephemeral node
  • The leader renews a lease; others watch and retry
  • An old leader may not know it lost leadership
  • Fencing tokens let storage reject stale leaders' writes
  • Lease length trades failover speed against false elections

Common mistakes

  • Trusting the old leader to notice it lost the lease
  • Electing a leader without a quorum-based service
  • Every candidate watching the leader node and stampeding on change
  • Very short leases that flap during network blips

Follow-ups

  • How would you run leader election without an external coordination service?
  • What happens if the coordination service loses quorum?
  • How do fencing tokens work with a storage system that cannot check them?

Tips

  • Walk through the GC pause scenario
  • Show the conditional create step
  • Explain fencing in one sentence

Evaluation rubric

  • Correct election recipe
  • Explains leases and renewal
  • Handles split brain with fencing
  • Discusses lease trade-offs and alternatives
86.system-design-0086Mediummid

Walk through what happens when a two-phase commit coordinator crashes after the prepare phase, and then design a saga with compensations for a trip booking that reserves a flight, a hotel and a payment.

In two-phase commit, a participant that voted "yes" in prepare must hold its locks until it learns the outcome; if the coordinator crashes then, participants are blocked and cannot decide alone. A saga avoids that by running local transactions in sequence with a compensating action for each, such as cancel the flight if the hotel fails. Sagas trade atomic isolation for availability, so steps must be idempotent, compensations must be designed per step, and irreversible steps go last.

Full answer

Two-phase commit failure timeline

Participants: flight service, hotel service, payment service. Coordinator: booking service.

  1. Coordinator sends PREPARE to all three.
  2. Each participant writes its changes and a "prepared" record to its log, keeps the rows locked and votes YES.
  3. Coordinator crashes before sending COMMIT or ABORT.

Now each participant is in doubt. It cannot commit (another participant might have voted NO) and cannot abort (the coordinator might have decided COMMIT and told someone). It must keep locks and wait for the coordinator to recover and read its decision log. Other transactions that need those rows wait too. This is the blocking problem of 2PC. Making the coordinator highly available (replicating its log with consensus) reduces but does not remove the cost, and every participant must support the prepare protocol, which most external services (payment gateways, airline systems) do not.

Saga design for the trip

Orchestrated saga, run by a booking orchestrator that stores its state durably:

StepActionCompensation
1Hold flight seat (expires in 15 min)Release hold
2Reserve hotel roomCancel reservation
3Charge paymentRefund
4Confirm flight ticket (issue)None: pivot step
5Send confirmationRetry until success

Rules:

  • Order steps so that easy-to-undo actions come first, the pivot (point of no return, here issuing the ticket) after them, and only retryable steps after the pivot, which must eventually succeed.
  • Idempotency. Each step and compensation carries the saga ID and step number, so retries after timeouts do not double-book or double-refund.
  • Compensation is semantic. A refund is a new transaction, not an erasure; the customer may see a charge and a refund.
  • Isolation is lost. Between steps, others can see partial state (a room reserved but not yet paid). Use status fields such as PENDING and countermeasures like re-reading values before the pivot.

If payment fails at step 3, the orchestrator runs compensations in reverse: cancel the hotel, release the flight hold, then mark the saga FAILED.

Choosing

Use 2PC (or a single database transaction) inside one database or a tightly controlled set of resources that support it. Use sagas across services and external partners, where availability matters and blocking locks are unacceptable.

By level

Fresher: Explain that in 2PC everyone must agree before committing and can get stuck if the coordinator disappears. A fresher should describe undoing earlier steps when a later one fails.

Mid: Walk through the in-doubt timeline, design the saga table with compensations and idempotency, and explain why external services prevent 2PC. Mention orchestration.

Senior: Discuss pivot steps, semantic compensation, lost isolation and countermeasures, coordinator replication and choreography versus orchestration. Expect a careful failure timeline.

Key points

  • After voting yes, a 2PC participant is in doubt and must hold locks until the coordinator recovers
  • External services rarely support prepare
  • Sagas run local steps with compensations in reverse on failure
  • Put reversible steps first, the pivot next, retryable steps last
  • Steps and compensations must be idempotent; isolation is lost

Common mistakes

  • Assuming participants can safely abort on their own after preparing
  • Designing a saga without a compensation for each step before the pivot
  • Treating compensation as deleting history
  • Forgetting idempotency for retries and compensations

Follow-ups

  • How would you implement the same saga with choreography instead of an orchestrator?
  • What is the three-phase commit and why is it rarely used?
  • How do you show users a booking that is still pending?

Tips

  • Narrate the in-doubt state clearly
  • Use a table of steps and compensations
  • Name the pivot step

Evaluation rubric

  • Correct 2PC blocking analysis
  • Sound saga with compensations and ordering
  • Idempotency and isolation addressed
  • Clear choice between the two
87.system-design-0087Hardsenior

Explain write-ahead logs, and compare LSM trees with B-trees as storage engines: how does each handle writes, reads and crashes?

A write-ahead log records every change sequentially before it is applied, so after a crash the engine replays the log to recover. B-trees update fixed-size pages in place and are fast for reads and range scans, but random writes cost page writes. LSM trees buffer writes in memory, flush sorted files sequentially and merge them in the background, so they absorb high write rates at the cost of read work and compaction. Choose by workload: read-heavy and transactional for B-trees, write-heavy for LSM trees.

Full answer

Write-ahead log (WAL)

Changing data pages directly is risky: a crash halfway through writing a page leaves it corrupt. Instead, the engine first appends a record ("set row 42 balance to 900") to a log and forces it to disk (fsync). Only then is the change acknowledged. Pages are updated later, in memory, and written lazily. After a crash, the engine replays log records after the last checkpoint. Sequential appends are fast even on spinning disks, and group commit (one fsync for many transactions) raises throughput.

Both B-tree and LSM engines use a WAL. It also feeds replication (PostgreSQL streaming replication ships WAL records) and change data capture.

B-trees

Data lives in pages (often 8 to 16 KB) arranged as a balanced tree. A lookup reads about 3 to 4 pages for billions of keys, and the upper levels are usually cached. An update finds the leaf page and changes it in place; a full page splits.

  • Reads: predictable, one path down the tree; excellent range scans.
  • Writes: each small update may rewrite a whole page (write amplification), and random updates mean random I/O.
  • Used by PostgreSQL, MySQL InnoDB, SQL Server, SQLite.

LSM trees

  1. Writes go to the WAL and to an in-memory sorted table (memtable).
  2. When the memtable is full, it is written to disk as an immutable sorted file (SSTable), sequentially.
  3. Background compaction merges SSTables, dropping overwritten values and tombstones.
  4. Reads check the memtable, then SSTables from newest to oldest; Bloom filters skip files that cannot contain the key, and a sparse index finds the block.
  • Writes: sequential and batched, so very high throughput.
  • Reads: may touch several files; range scans merge several sorted runs.
  • Space and I/O: compaction rewrites data repeatedly; leveled compaction lowers read and space cost, tiered compaction lowers write cost.
  • Used by RocksDB, Cassandra, ScyllaDB, LevelDB, and many time-series stores.

Comparing

AspectB-treeLSM tree
Write throughputModerate, random I/OHigh, sequential I/O
Point readsFast and predictableGood with Bloom filters, more variable
Range scansExcellentGood, merges runs
SpaceSome fragmentationTemporary duplicates until compaction
Background workLittleCompaction can spike latency

The three amplifications summarise it: B-trees have lower read amplification, LSM trees lower write amplification, and compaction strategy moves LSM costs between write, read and space amplification.

By level

Fresher: Explain that the database writes changes to a log first so it can recover after a crash. A fresher should describe a B-tree lookup as a few page reads.

Mid: Describe LSM writes, flushes, compaction and reads with Bloom filters, and compare with B-tree updates. Name example systems.

Senior: Discuss read, write and space amplification, compaction strategies, group commit, latency spikes and workload-based choice. Expect careful reasoning about crash recovery.

Key points

  • WAL: append and fsync before acknowledging; replay after a crash
  • B-trees update pages in place; fast reads and range scans
  • LSM trees buffer in memory, flush sorted files, compact later
  • Bloom filters cut LSM read cost
  • Read, write and space amplification frame the trade-off

Common mistakes

  • Thinking LSM trees do not need a WAL
  • Claiming B-trees are always slower for writes regardless of workload
  • Ignoring compaction cost and latency spikes
  • Forgetting that deletes in LSM trees are tombstones

Follow-ups

  • How does leveled compaction differ from tiered compaction?
  • Why does PostgreSQL need VACUUM?
  • How does group commit improve throughput?

Tips

  • Explain the crash scenario that motivates the WAL
  • Walk through an LSM write and read
  • Use amplification terms in the comparison

Evaluation rubric

  • Correct WAL purpose and recovery
  • Accurate B-tree and LSM mechanics
  • Clear trade-off comparison
  • Knows real systems and compaction strategies
88.system-design-0088Mediumfresher

What is change data capture (CDC), and how do tools like Debezium stream database changes to caches, search indexes and analytics without dual writes?

CDC reads the database's own change log (the MySQL binlog or PostgreSQL WAL) and turns every committed insert, update and delete into an event on a stream such as Kafka. Downstream consumers update caches, search indexes or warehouses from that stream. Because events come from committed transactions, in commit order, it avoids the dual-write problem where the application writes to the database and to another system and one of them fails.

Full answer

The dual-write problem

An application saves a course to PostgreSQL and then updates Elasticsearch. If the second call fails or the process crashes between them, the search index is wrong forever. Doing it in the other order risks indexing something that was never saved. Two writes to two systems cannot be made atomic without distributed transactions.

How CDC works

  1. The database already writes every committed change to its log for crash recovery and replication.
  2. A CDC connector (Debezium, or managed services from cloud providers) connects like a replica, reads the log and converts each change into an event: table, primary key, before and after values, operation type, transaction ID and log position.
  3. Events go to a stream, typically one Kafka topic per table, partitioned by primary key so changes to one row stay in order.
  4. Consumers apply events: update the cache, upsert into the search index, load into the warehouse.

The connector stores its log position, so after a restart it continues where it stopped. Delivery is at-least-once, so consumers must be idempotent (an upsert by primary key is naturally idempotent).

Initial snapshot

A new consumer needs existing data too. Connectors take a consistent snapshot of the tables, stream it, then switch to the log from the snapshot's position, with no gap.

The outbox pattern

Raw table changes expose internal schemas. With an outbox, the application writes its business row and an outbox row (a clean event such as CourseCreated) in the same transaction. CDC streams the outbox table. Consumers get stable, meaningful events, still without dual writes.

Uses

  • Keeping caches and search indexes in sync.
  • Feeding a data warehouse in near real time instead of nightly dumps.
  • Migrating between databases with live replication before the switch.
  • Building event-driven services from an existing monolith.

Trade-offs

  • Consumers are eventually consistent, usually seconds behind.
  • Schema changes in the source must be handled by consumers (a schema registry helps).
  • The database must keep log files until the connector reads them; a stopped connector can fill the disk, so monitor its lag.

By level

Fresher: Explain that the database already records every change in a log, and CDC turns that log into messages other systems can use. A fresher should describe the problem of writing to two systems.

Mid: Describe connectors, log positions, per-key ordering, snapshots and idempotent consumers. Introduce the outbox pattern.

Senior: Discuss schema evolution, log retention risks, migration use, ordering across tables and lag monitoring. Expect a clear comparison of raw CDC and the outbox.

Key points

  • CDC reads the database's change log and emits an event per committed change
  • Avoids dual writes to the database and another system
  • Partition by primary key to keep per-row order
  • At-least-once delivery needs idempotent consumers
  • Outbox pattern gives clean business events through CDC

Common mistakes

  • Writing to the database and the search index from application code and hoping both succeed
  • Assuming CDC events are exactly-once
  • Exposing internal table schemas as public events with no outbox
  • Forgetting that a stopped connector can fill the database disk

Follow-ups

  • How does the initial snapshot avoid missing changes?
  • How would you handle a column rename in the source table?
  • When would you use the outbox instead of raw table CDC?

Tips

  • Start with the dual-write failure
  • Describe one event's fields
  • Mention idempotent consumers

Evaluation rubric

  • Explains dual-write risk
  • Correct CDC mechanics with logs and positions
  • Idempotency, ordering and snapshots
  • Outbox and operational trade-offs
89.system-design-0089Mediummid

What are event sourcing and CQRS, how do they work together, and when are they worth the extra complexity?

Event sourcing stores the sequence of events that changed an entity (OrderPlaced, ItemAdded, OrderShipped) as the source of truth and rebuilds current state by replaying them. CQRS separates the write model, which validates commands and appends events, from one or more read models built from those events and shaped for queries. Together they give full history, audit and flexible new views, but add eventual consistency, event versioning and replay costs, so they suit complex domains, not simple CRUD.

Full answer

Event sourcing

Instead of a row saying "balance = 900", store:

  1. AccountOpened {id: 7}
  2. Deposited {amount: 1000}
  3. Withdrawn {amount: 100}

Current state is the result of applying events in order. To handle a command ("withdraw 200"), the system loads the account's events, rebuilds state, checks rules (enough balance) and appends a new event. Appends use optimistic concurrency: "append only if the stream is still at version 3", so two concurrent commands cannot both succeed on stale state.

Snapshots (state at version 500) avoid replaying thousands of events each time.

CQRS

Command Query Responsibility Segregation means using different models for writes and reads.

  • Write side: small aggregates that enforce invariants and emit events.
  • Read side: projections that consume events and maintain views such as "orders by customer" in SQL, "search by product" in a search index, or a dashboard counter in Redis.

You can use CQRS without event sourcing (read replicas, materialised views), but event sourcing makes CQRS natural, because events are the feed for every projection.

Benefits

  • Complete audit trail: every change and why, in order. Useful for finance, compliance, and debugging ("what did this order look like on Tuesday?").
  • New read models can be built later by replaying history.
  • Events integrate naturally with other services.

Costs

  • Eventual consistency between writes and read models: a user may not see their change in a list immediately. Return the result from the write side, or wait for the projection to reach the event's version, for read-your-writes.
  • Event schema evolution: old events live forever. Version events and write upcasters that convert old versions when reading.
  • Replays of large streams take time; plan for rebuilding projections in parallel.
  • Deleting personal data conflicts with immutable logs; use crypto-shredding (encrypt personal fields per user and delete the key).
  • More moving parts: event store, projectors, monitoring of projection lag.

When to use

Good fit: complex business rules, strong audit needs, many different read views, collaboration domains (orders, payments, bookings, inventory). Poor fit: simple CRUD screens, small teams without the need for history. Many systems use event sourcing for one or two core areas only.

By level

Fresher: Explain that instead of saving only the current value, the system saves every change as an event and can rebuild the value. A fresher should describe a separate read view for listing data.

Mid: Describe optimistic appends, snapshots, projections and eventual consistency, and when CQRS appears without event sourcing. Give fit criteria.

Senior: Discuss schema evolution with upcasters, projection rebuilds, read-your-writes strategies, crypto-shredding and partial adoption. Expect a clear cost-benefit judgement.

Key points

  • Event sourcing stores events as the source of truth and replays them for state
  • Optimistic concurrency on stream version for appends
  • CQRS separates the write model from query-shaped read models
  • Projections are eventually consistent and can be rebuilt
  • Costs: schema evolution, replay time, deletion of personal data

Common mistakes

  • Using event sourcing for simple CRUD
  • Ignoring event versioning
  • Expecting read models to be updated instantly
  • Storing personal data in immutable events with no deletion plan

Follow-ups

  • How do you give users read-your-writes with CQRS?
  • How would you rebuild a projection with 2 billion events?
  • How does crypto-shredding work?

Tips

  • Use a bank account event list as the example
  • Separate event sourcing from CQRS clearly
  • Be honest about when not to use them

Evaluation rubric

  • Correct definitions and how they combine
  • Concurrency and snapshots
  • Benefits and costs balanced
  • Sensible fit guidance
90.system-design-0090Easyfresher

What is backpressure, and how do systems use it to stay healthy when producers send data faster than consumers can process it?

Backpressure is any signal from a slow consumer that tells a fast producer to slow down, instead of letting work pile up until memory runs out or latency explodes. Examples are bounded queues that block or reject when full, TCP flow control windows, pull-based consumers that ask for only what they can handle, and HTTP 429 or 503 responses. When slowing down is not possible, systems shed load deliberately by dropping low-priority work.

Full answer

The problem

A producer sends 10,000 messages per second; the consumer handles 8,000. Every second, 2,000 more wait. With an unbounded queue, memory grows until the process crashes, and every message waits longer and longer, so by the time work is done it may be useless (the user has given up).

Ways to apply backpressure

  1. Bounded queues. Give each queue a maximum size. When it is full, the producer blocks (waits), gets an error, or the oldest or lowest-priority item is dropped. Blocking pushes the slowdown upstream, which is exactly the point.
  2. Pull instead of push. Consumers request a batch when ready (Kafka consumers poll; Reactive Streams request(n)). They can never be given more than they asked for.
  3. Flow control in protocols. TCP's receive window tells the sender how much more data the receiver can buffer; HTTP/2 and gRPC have stream-level windows.
  4. Explicit rejection. Services return 429 (too many requests) or 503 with Retry-After. Well-behaved clients back off with exponential delays and jitter.
  5. Concurrency limits. Allow only N requests in progress per service; adaptive limiters lower N when latency rises.

Load shedding

If the source cannot slow down (users clicking, sensors sending), drop work on purpose:

  • Reject new requests early, before spending resources on them.
  • Prefer important traffic (checkout over recommendations).
  • Drop requests that have already waited longer than their deadline.

Example

A video platform sends upload events to a transcoding queue. During a viral event, uploads double. The queue is bounded; when it reaches its limit, the upload API keeps accepting files (cheap) but marks transcoding as "queued", workers autoscale, and low-priority tasks such as thumbnail regeneration pause. Nothing crashes and important work continues.

Signs you need it

Growing queue lengths, rising memory, timeouts cascading from one service to its callers, and retries making overload worse. Monitor queue depth and age, not only throughput.

By level

Fresher: Explain that when a receiver is too slow, the sender must be told to slow down or work will pile up. A fresher should describe a queue with a size limit.

Mid: Describe bounded queues, pull consumers, flow control, 429 responses with backoff and concurrency limits. Explain when to shed load.

Senior: Discuss adaptive limits, deadline-based dropping, priority classes, retry storms and queue age monitoring. Expect end-to-end thinking across services.

Key points

  • Backpressure tells fast producers to slow down
  • Bounded queues block, reject or drop when full
  • Pull-based consumption and protocol flow control limit what is sent
  • 429 or 503 with Retry-After plus client backoff
  • Load shedding drops low-priority or expired work when slowing is impossible

Common mistakes

  • Using unbounded queues and hoping consumers catch up
  • Retrying immediately on overload errors
  • Doing expensive work before deciding to reject
  • Monitoring throughput but not queue age

Follow-ups

  • How does TCP flow control work?
  • How would you choose a queue size?
  • What is an adaptive concurrency limit?

Tips

  • Give the 10,000 versus 8,000 example
  • List three concrete mechanisms
  • Explain load shedding as the last resort

Evaluation rubric

  • Correct definition
  • Several mechanisms explained
  • Load shedding and prioritisation
  • Monitoring signals
91.system-design-0091Hardsenior

How do you run a service active-active across several regions? Cover traffic routing, data replication, write conflicts and what happens when a region fails.

Every region serves reads and writes for nearby users, with traffic steered by latency-based DNS or anycast. Data replicates asynchronously between regions, so concurrent writes to the same item in two regions can conflict; avoid that by giving each record a home region, or resolve conflicts with CRDTs or last-write-wins where acceptable. When a region fails, routing moves its users elsewhere, accepting that writes not yet replicated may be lost or delayed. Strongly consistent global writes cost a cross-region round trip per write.

Full answer

Why active-active

Active-passive keeps a standby region idle until disaster; failover is slow, rarely tested and the standby may not handle full load. Active-active uses every region all the time, gives low latency to users everywhere and makes failover a routing change.

Routing

  • Latency-based or geo DNS sends each user to the nearest healthy region; TTLs of 30 to 60 seconds limit how long clients stick to a dead region.
  • Anycast (one IP announced from many places) with a global load balancer reacts faster, in seconds.
  • Sticky homes: route a signed-in user to their home region when possible, so their reads see their own writes.

Data replication options

  1. Home-region partitioning (most common). Each user, tenant or account has one home region that accepts its writes; other regions get asynchronous copies for reads. No write conflicts, because only one region writes each record. Moving a user's home is an explicit migration.
  2. Multi-leader with conflict resolution. Any region writes any record and replicates asynchronously. Concurrent updates conflict:
    • last-write-wins by timestamp (simple, silently loses updates);
    • CRDTs for counters, sets, carts (merge without loss);
    • application merge rules or showing conflicts to users.
  3. Globally consistent databases (Spanner, CockroachDB, YugabyteDB with global tables) use consensus across regions. Every write waits for a majority of regions, adding tens to hundreds of milliseconds, but there are no conflicts.

Many systems mix: global consistency for small critical data (usernames, payments), home-region writes for user data, CRDTs for counters.

Region failure

  • Routing removes the failed region within seconds to minutes.
  • With asynchronous replication, the last few seconds of writes in that region (the replication lag) may be missing elsewhere: the recovery point objective is the lag, not zero.
  • For home-region data, another region is promoted as the new home for affected users; when the old region returns, its unreplicated writes must be reconciled, not blindly applied.

Other concerns

  • Data residency laws may require some users' data to stay in a region, which limits replication.
  • Capacity: each region must absorb a failed region's traffic; with three regions, run each at under about 66% of peak.
  • Global services such as ID generation, auth keys and configuration must also be multi-region, or they become the hidden single point of failure.
  • Test failover regularly by draining a region on purpose.

By level

Fresher: Explain that several regions serve users at once and copy data to each other. A fresher should see that two regions editing the same thing at once can conflict.

Mid: Compare home-region partitioning, multi-leader with conflict resolution and global consensus. Describe failover with replication lag.

Senior: Discuss mixed strategies per data type, recovery point objectives, reconciliation after failback, residency, headroom and failover drills. Expect precise trade-offs.

Key points

  • Every region serves traffic; routing by latency DNS or anycast
  • Home-region ownership avoids write conflicts
  • Multi-leader needs LWW, CRDTs or app merges
  • Global consensus databases avoid conflicts at the cost of cross-region latency
  • Async replication means failover can lose the last few seconds of writes

Common mistakes

  • Assuming async replication gives zero data loss on failover
  • Using last-write-wins for money or inventory
  • Forgetting capacity headroom to absorb a failed region
  • Leaving global dependencies in a single region

Follow-ups

  • How would you migrate a user's home region?
  • How do you handle unique usernames across regions?
  • How would you test region failover safely?

Tips

  • Separate routing, data and failure handling
  • Present home-region ownership as the default
  • State the recovery point honestly

Evaluation rubric

  • Clear routing design
  • Correct replication options and conflicts
  • Realistic failure analysis
  • Capacity, residency and global dependency awareness
92.system-design-0092Mediummid

How should you partition and lay out data for analytics in a data lake or warehouse, and how do partitioning, clustering and columnar formats speed up queries?

Partition large tables by the column most queries filter on, usually date, so queries skip whole partitions (partition pruning). Inside partitions, store data in a columnar format such as Parquet with sorting or clustering on other common filters, so min and max statistics let the engine skip files and row groups. Keep files large (around 128 MB to 1 GB) and partitions coarse enough; too many small files or high-cardinality partitions make queries slower, not faster.

Full answer

The goal

Analytics queries scan huge tables: "revenue by course for last week". The fastest data is data you do not read. Layout decides how much can be skipped.

Partitioning

A table stored as events/date=2026-12-03/, events/date=2026-12-04/ lets a query with WHERE date >= '2026-11-27' read only seven folders. That is partition pruning.

Good partition keys:

  • Appear in most query filters (date or hour for event data).
  • Have moderate cardinality: days, maybe days plus region. Not user_id: millions of partitions mean millions of tiny files and huge metadata.

Skew matters too: if one partition holds 80% of data, parallel jobs wait on it.

Columnar formats

Parquet and ORC store each column separately, compressed, in row groups with min and max statistics. A query that needs 3 of 80 columns reads only those 3. Similar values compress very well (dictionary and run-length encoding).

Clustering and sorting

Within a partition, sort data by a second common filter (for example course_id). Then each file and row group covers a narrow range of course_id, and the engine skips files whose min and max cannot match. Z-ordering mixes several columns when queries filter on different ones. Warehouses call this clustering keys (Snowflake, BigQuery) or sort keys (Redshift).

File sizes

Streaming ingestion writes many small files. Each file costs an open, metadata reads and scheduling overhead. Compact them into files of roughly 128 MB to 1 GB. Table formats such as Iceberg, Delta Lake and Hudi track files in metadata, support compaction and allow changing the partition scheme later without rewriting queries.

Example

A learning platform stores 2B video events per day. Layout: partition by event_date, cluster by course_id, Parquet files of about 512 MB. A query for one course over 7 days reads 7 partitions and only the files whose course_id range includes it, perhaps 1% of the week's data.

Trade-offs

  • More partitions mean better pruning only up to a point; past it, metadata and small files dominate.
  • Sorting on ingest costs compute; periodic background clustering spreads the cost.
  • Partitioning for one query pattern can hurt another; pick the dominant pattern and use clustering for the rest.
  • OLTP-style partitioning (by user for load spread) is different from analytics partitioning (by time for pruning).

By level

Fresher: Explain that data is split into folders by date so queries only open the days they need. A fresher should know that columnar files read only the needed columns.

Mid: Discuss partition key choice, columnar statistics, clustering within partitions and compaction of small files. Give an example layout.

Senior: Cover Z-ordering, table formats, partition evolution, skew, and choosing between conflicting query patterns. Expect cost-aware reasoning about scanned bytes.

Key points

  • Partition by the most common filter, usually date
  • Partition pruning skips whole folders
  • Columnar formats read only needed columns and skip by min-max statistics
  • Cluster or sort within partitions on secondary filters
  • Avoid small files and high-cardinality partitions

Common mistakes

  • Partitioning by user ID or another high-cardinality column
  • Ignoring small files from streaming ingestion
  • Storing analytics data in row formats like CSV or JSON long term
  • Assuming more partitions always mean faster queries

Follow-ups

  • How does Z-ordering work?
  • How would you change the partition scheme of a 500 TB table?
  • How do Iceberg or Delta Lake help with compaction?

Tips

  • Use a date-filter example to explain pruning
  • Mention column pruning and statistics
  • Warn about small files with numbers

Evaluation rubric

  • Correct partitioning guidance
  • Columnar and statistics-based skipping explained
  • Clustering and file size handled
  • Trade-offs between query patterns
93.system-design-0093Easyfresher

What is the difference between OLTP and OLAP systems, and why do companies keep a separate data warehouse instead of running reports on the production database?

OLTP (online transaction processing) systems handle many small, fast reads and writes of individual records, such as placing an order, and need strong consistency. OLAP (online analytical processing) systems run fewer but huge queries that scan and aggregate millions of rows, such as revenue by month. They use different storage layouts (row-oriented versus column-oriented), so analytics run in a separate warehouse fed by ETL or change data capture, keeping heavy reports from slowing down users.

Full answer

OLTP

Examples: placing an order, updating a profile, recording a quiz attempt.

  • Query shape: touch a few rows by key; SELECT * FROM orders WHERE order_id = 812.
  • Many concurrent users, thousands of transactions per second, millisecond latency.
  • Normalised schema to avoid duplicated data; transactions and constraints.
  • Row-oriented storage: all columns of a row are stored together, ideal for reading or updating whole records.
  • Databases: PostgreSQL, MySQL, SQL Server, Oracle.

OLAP

Examples: monthly revenue by country, course completion rates by cohort, which videos learners drop out of.

  • Query shape: scan millions or billions of rows, few columns, with group-by and aggregates.
  • Fewer users (analysts, dashboards); seconds to minutes per query is acceptable.
  • Denormalised star or snowflake schemas: a fact table (enrolments, events) with dimension tables (course, user, date).
  • Column-oriented storage: each column stored together, compressed; a query reading 3 columns skips the other 50.
  • Systems: BigQuery, Snowflake, Redshift, ClickHouse, Databricks.

Why separate them

  1. Performance isolation. A report scanning 500M rows on the production database competes for CPU, memory and disk with checkout queries and slows them down.
  2. Storage layout. Row storage is slow for big scans; column storage is slow for single-row updates. One layout cannot be best for both.
  3. History and integration. A warehouse combines data from many sources (orders, payments, marketing, product events) and keeps years of history that the production database does not need.

Getting data from OLTP to OLAP

  • ETL or ELT: batch jobs extract data (often nightly), transform and load it.
  • Change data capture: stream every change from the production database's log into the warehouse within minutes.

Example

An edtech company keeps enrolments and payments in PostgreSQL (OLTP). Each change streams to a warehouse where analysts ask "what share of learners who watch lesson 3 finish the course?" Running that on PostgreSQL during exam season would slow down every learner's dashboard.

A middle ground

HTAP databases and read replicas can serve light analytics, but heavy, long-running reporting still belongs in a dedicated OLAP system.

By level

Fresher: Explain OLTP as everyday app operations and OLAP as big reports, with one example each. A fresher should say why reports should not run on the live database.

Mid: Compare row and column storage, schema styles and data movement with ETL and CDC. Give a realistic separation example.

Senior: Discuss HTAP options, freshness requirements, cost of warehouse scans, schema design for analytics and governance. Expect clear judgement on when a replica is enough.

Key points

  • OLTP: many small transactional reads and writes by key
  • OLAP: few large scans and aggregations
  • Row storage suits OLTP; column storage suits OLAP
  • Separate warehouses isolate heavy reports from users
  • Data moves by ETL or change data capture

Common mistakes

  • Running heavy reports on the production primary database
  • Assuming one storage layout is best for both workloads
  • Normalising warehouse schemas like transactional ones without reason
  • Ignoring data freshness needs when choosing nightly ETL

Follow-ups

  • What is a star schema?
  • When would a read replica be enough for reporting?
  • How does columnar compression work?

Tips

  • Give one example query of each type
  • Explain row versus column layout simply
  • Mention how data gets to the warehouse

Evaluation rubric

  • Correct definitions and examples
  • Storage layout difference explained
  • Clear reasons for separation
  • Knows ETL and CDC
94.system-design-0094Hardsenior

Explain the core ideas of stream processing: event time versus processing time, tumbling, sliding and session windows, watermarks, late data and how engines like Flink achieve exactly-once results.

Stream processors compute results continuously over unbounded data. Windows group events in time (tumbling: fixed and non-overlapping; sliding: overlapping; session: separated by gaps of inactivity), usually by event time so results do not depend on delays. Watermarks tell the engine when a window is probably complete; late events can update results within an allowed lateness or go to a side output. Exactly-once results come from consistent checkpoints of state and input offsets plus transactional or idempotent sinks.

Full answer

Event time versus processing time

Event time is when something happened (the click's timestamp). Processing time is when the engine sees it. A phone that was offline for 5 minutes sends old events late. Counting by processing time would put those clicks in the wrong minute and make results change every time you rerun. Event time gives correct, repeatable results.

Windows

  • Tumbling: fixed size, no overlap. Clicks per minute: [10:00, 10:01), [10:01, 10:02).
  • Sliding (hopping): fixed size, overlapping. Last 5 minutes, updated every minute; each event belongs to 5 windows.
  • Session: per key, closes after a gap of inactivity (for example 30 minutes without activity ends a learner's study session). Window lengths vary.
  • Global windows with triggers: custom rules such as "emit every 100 events".

Watermarks and late data

A watermark is a statement "no more events with timestamp before T are expected". A common strategy is max event time seen minus a bound (for example 2 minutes). When the watermark passes a window's end, the window fires.

Late events (older than the watermark) are handled by:

  • Allowed lateness: keep window state a bit longer and emit an updated result.
  • Side outputs: send them to a separate stream for batch correction.
  • Dropping: acceptable for some metrics.

The bound is a trade-off: a larger delay catches more late data but makes results slower.

Exactly-once

Exactly-once means each event affects the results once, even after failures (events may still be processed more than once internally).

Flink's approach:

  1. Periodically inject checkpoint barriers into the streams. When an operator has received the barrier on all inputs, it snapshots its state. The snapshot of all operators plus the source offsets is a consistent checkpoint.
  2. After a failure, restore every operator's state from the last checkpoint and rewind sources (for example Kafka offsets) to the stored positions.
  3. Sinks must not double-write the replayed output: use two-phase commit sinks (Kafka transactions committed when the checkpoint completes) or idempotent upserts keyed by (window, key).

Other concepts

  • Keyed state is partitioned by key and scales out with the job.
  • Backpressure slows sources when operators fall behind.
  • Kappa architecture: one streaming pipeline that can reprocess history by replaying the log, instead of separate batch and stream code.

By level

Fresher: Explain that events are grouped into time windows such as one minute, and that some events arrive late. A fresher should explain the difference between when an event happened and when it arrived.

Mid: Describe window types, watermarks, allowed lateness and side outputs, and the checkpoint-based exactly-once mechanism. Give example uses.

Senior: Discuss watermark strategies, session merging, state size and TTLs, sink semantics, backpressure and Kappa-style reprocessing. Expect precise end-to-end guarantees.

Key points

  • Use event time for correct, repeatable results
  • Tumbling, sliding and session windows serve different questions
  • Watermarks decide when windows fire; lateness is a trade-off
  • Late data: allowed lateness, side outputs or drop
  • Exactly-once: consistent checkpoints, rewindable sources, transactional or idempotent sinks

Common mistakes

  • Counting by processing time
  • Thinking exactly-once means each event is processed only once internally
  • Using a watermark delay of zero and losing late events
  • Writing to non-idempotent sinks after replay

Follow-ups

  • How would you choose the watermark delay?
  • How do session windows merge when a late event bridges two sessions?
  • What happens to state size with a 30-day sliding window?

Tips

  • Use an offline phone example for event time
  • Draw one window and the watermark crossing it
  • Explain barriers simply

Evaluation rubric

  • Correct time semantics
  • Accurate window types
  • Watermarks and late data handling
  • Correct exactly-once mechanism
95.system-design-0095Mediumfresher

How does full-text search work? Explain inverted indexes, tokenisation and BM25 ranking with a small example.

An inverted index maps each term to the list of documents that contain it (a posting list), often with positions and counts, so a query looks up a few lists instead of scanning every document. Text is tokenised and normalised (lowercase, remove punctuation, sometimes stem words) the same way at index and query time. BM25 scores each matching document higher when query terms appear often in it, rarer terms count more, and long documents are normalised so they do not win only by length.

Full answer

Inverted index

Documents:

  1. "binary search on a sorted array"
  2. "binary search tree insert and delete"
  3. "sorting an array with merge sort"

The index maps term to postings:

  • binary to {1, 2}
  • search to {1, 2}
  • array to {1, 3}
  • sort (after stemming "sorting" and "sorted") to {1, 3}

A query for "binary array" fetches two posting lists and combines them: intersection for AND (doc 1), union for OR (docs 1, 2, 3). Posting lists are sorted by document ID and compressed, so merging is fast even with millions of entries. Storing positions enables phrase queries ("binary search" as adjacent words).

Analysis (tokenisation)

The same analyser runs on documents and queries:

  1. Split text into tokens.
  2. Lowercase, remove accents, drop very common stop words if desired.
  3. Stem or lemmatise ("searching" to "search").
  4. Language-specific steps; for Hindi or Japanese text, tokenisation rules differ (character n-grams or dictionary-based segmentation).

If analysis differs between indexing and querying, matches are missed.

BM25 ranking

For each query term t in document d:

score += IDF(t) x tf x (k1 + 1) / (tf + k1 x (1 - b + b x len(d) / avg_len))

  • tf (term frequency): more occurrences raise the score, but with diminishing returns controlled by k1 (about 1.2).
  • IDF: terms in fewer documents are more informative; "the" adds almost nothing, "dijkstra" adds a lot.
  • Length normalisation (b about 0.75): a match in a short title-like document counts more than in a long page.
python
import math
from collections import Counter, defaultdict

docs = {
    1: "binary search on a sorted array",
    2: "binary search tree insert and delete",
    3: "sorting an array with merge sort",
    4: "search engine ranking with bm25",
}

index = defaultdict(dict)                 # term -> {doc_id: term frequency}
lengths = {}
for d, text in docs.items():
    words = text.split()
    lengths[d] = len(words)
    for term, tf in Counter(words).items():
        index[term][d] = tf
avg_len = sum(lengths.values()) / len(lengths)


def bm25(query, k1=1.2, b=0.75):
    n = len(docs)
    scores = defaultdict(float)
    for term in query.split():
        postings = index.get(term, {})
        idf = math.log(1 + (n - len(postings) + 0.5) / (len(postings) + 0.5))
        for d, tf in postings.items():
            norm = tf + k1 * (1 - b + b * lengths[d] / avg_len)
            scores[d] += idf * tf * (k1 + 1) / norm
    return sorted(scores.items(), key=lambda x: -x[1])


if __name__ == "__main__":
    ranked = bm25("binary search array")
    assert ranked[0][0] == 1                       # has all three terms
    assert {d for d, _ in ranked} == {1, 2, 3, 4}
    assert bm25("heap") == []
    print("ok:", [(d, round(s, 3)) for d, s in ranked])

Save as bm25.py and run python3 bm25.py (Python 3.13.5).

This snippet skips stemming for brevity, so "sorting" and "sorted" are different terms here.

In practice

Search engines such as Elasticsearch, OpenSearch and Solr (built on Lucene) store indexes in immutable segments, merge them in the background, and shard the index across nodes; each shard answers queries and a coordinator merges the top results. BM25 is often the first stage, followed by a re-ranker that uses more signals (popularity, freshness, personalisation, learned models).

By level

Fresher: Explain that the index lists, for each word, which documents contain it, like the index at the back of a book. A fresher should show how a two-word query is answered.

Mid: Describe analysis, posting list merging and the parts of BM25, with the small example. Mention phrase queries.

Senior: Discuss segments and merging, sharding and top-k merging, multilingual analysis, typo tolerance and two-stage ranking. Expect clear reasoning about relevance trade-offs.

Key points

  • Inverted index maps terms to sorted, compressed posting lists
  • Same analysis at index and query time
  • AND intersects posting lists; OR unions them
  • BM25 combines term frequency with saturation, IDF and length normalisation
  • Shard indexes and re-rank top results with extra signals

Common mistakes

  • Scanning documents with LIKE '%term%' at scale
  • Using different analysers for indexing and querying
  • Thinking raw term counts alone give good ranking
  • Ignoring language-specific tokenisation

Follow-ups

  • How do phrase queries use positions?
  • How would you support typo tolerance?
  • How do you keep the index updated when documents change?

Tips

  • Build a tiny index by hand
  • Explain each part of BM25 in words
  • Mention analysis consistency

Evaluation rubric

  • Correct inverted index explanation
  • Tokenisation and normalisation understood
  • BM25 components explained
  • Awareness of real search systems
96.system-design-0096Hardsenior

How does erasure coding protect data in blob storage, how does it compare with replication on durability, storage cost and repair cost, and when is each the better choice?

Erasure coding splits data into k data fragments and computes m parity fragments so that any k of the k + m fragments rebuild the data. A 6 + 3 Reed-Solomon code survives any 3 lost fragments using 1.5 times the space, while three-way replication survives 2 losses using 3 times the space. The costs are CPU for encoding and decoding, slower small reads, and expensive repairs that read k fragments to rebuild one. Hot or small data often stays replicated; large or cold data is erasure coded.

Full answer

Replication

Store 3 full copies on different machines or zones. Survives 2 failures, reads from any copy are cheap, and repairing a lost copy means copying one replica. Storage overhead: 3x.

Erasure coding

Split a chunk into k data fragments, compute m parity fragments, store all k + m on different failure domains. Any k fragments reconstruct the chunk.

The simplest case is k data fragments plus one XOR parity fragment (m = 1), like RAID 5:

python
from functools import reduce


def xor_bytes(blocks):
    return bytes(reduce(lambda x, y: x ^ y, col) for col in zip(*blocks))


if __name__ == "__main__":
    data = [b"lesson01", b"lesson02", b"lesson03", b"lesson04"]   # 4 data fragments
    parity = xor_bytes(data)                                      # 1 parity fragment
    lost = 2
    survivors = [blk for i, blk in enumerate(data) if i != lost] + [parity]
    rebuilt = xor_bytes(survivors)
    assert rebuilt == data[lost]
    print("ok: rebuilt", rebuilt.decode(), "| overhead", (len(data) + 1) / len(data))

Save as xor_parity.py and run python3 xor_parity.py (Python 3.13.5).

Reed-Solomon codes generalise this to any m, for example:

  • 6 + 3: overhead 9 / 6 = 1.5x, survives 3 losses.
  • 10 + 4: overhead 1.4x, survives 4 losses.

Comparing at 1 PB of data

SchemeRaw storageFailures survived
3 replicas3 PB2
RS 6 + 31.5 PB3
RS 10 + 41.4 PB4

Erasure coding gives both higher fault tolerance and half the storage of replication.

The costs

  • Repair bandwidth. Rebuilding one lost 64 MB fragment in 6 + 3 reads 6 fragments (384 MB) across the network, versus 64 MB for replication. When a 20 TB disk fails, repair traffic is large. Locally repairable codes (used in Azure storage) add local parity groups so most repairs read fewer fragments.
  • Latency. A read must contact k nodes and wait for all of them (or decode from parity when one is slow), and small objects fragmented into tiny pieces are inefficient. Systems pack small objects into large chunks first.
  • CPU for encoding and decoding, modest with modern instruction sets.
  • Writes need all fragments (or enough of them) to be stored before acknowledging.

Durability depends on repair speed

Data is lost only if more than m fragments of the same chunk fail before repair finishes. Fast failure detection, spreading fragments across racks and zones, and quick parallel repair matter as much as the code parameters.

When to use which

  • Replication: small objects, hot data with heavy reads, low-latency needs, metadata.
  • Erasure coding: large objects, warm and cold data, archives, most bytes in object stores.
  • Many systems write new data replicated and convert it to erasure-coded form once it cools down.

By level

Fresher: Explain that extra parity pieces let you rebuild lost pieces, using the XOR example. A fresher should compare the storage used with keeping three copies.

Mid: Compare replication and Reed-Solomon codes on storage, failures survived, repair and latency. Explain packing small objects.

Senior: Discuss locally repairable codes, durability modelling with repair time, failure domains, tiering from replicated to coded data and read latency strategies. Expect numbers behind each claim.

Key points

  • Any k of k + m fragments rebuild the data
  • RS 6 + 3 survives 3 losses at 1.5x storage; 3 replicas survive 2 at 3x
  • Repairs read k fragments, so repair bandwidth is high
  • Small objects are packed before coding
  • Durability depends on fast detection and repair

Common mistakes

  • Assuming erasure coding is always better than replication
  • Ignoring repair bandwidth after large disk failures
  • Placing several fragments in the same failure domain
  • Erasure coding tiny objects one by one

Follow-ups

  • What are locally repairable codes?
  • How would you calculate the probability of data loss?
  • Why convert data from replicated to erasure-coded form over time?

Tips

  • Do the storage comparison table
  • Explain the XOR example first
  • Raise repair cost before being asked

Evaluation rubric

  • Correct explanation of k + m coding
  • Accurate cost and durability comparison
  • Repair and latency trade-offs
  • Sensible usage guidance
97.system-design-0097Easyfresher

What are the three pillars of observability: logs, metrics and traces? What question does each answer, and how do they work together during an incident?

Metrics are numbers over time (request rate, error rate, latency percentiles) that are cheap to store and great for dashboards and alerts: they tell you that something is wrong. Traces follow one request across services as a tree of timed spans: they show where time is spent or where an error starts. Logs are detailed event records: they explain why something happened. Linking them with shared IDs (trace IDs in logs, exemplars on metrics) lets an engineer go from an alert to the exact failing request.

Full answer

Metrics

  • Counters (requests total), gauges (queue length), histograms (latency distribution).
  • Aggregated and cheap: one number per series per interval, regardless of traffic.
  • Answer: "Is the error rate above 2%? Is p99 latency rising?"
  • Basis for alerts and SLOs. A common starting set per service is RED: Rate, Errors, Duration.
  • Keep label cardinality low; a label per user ID creates millions of series.

Traces

  • A trace is the path of one request through many services. Each step is a span with start time, duration, service name and attributes; spans form a tree through parent IDs.
  • Context (the trace ID) travels in request headers (the W3C traceparent header) so each service can attach its spans.
  • Answer: "This checkout took 3 seconds; 2.6 of them were in the inventory service waiting on the database."
  • Usually sampled (for example 1% of requests, plus all errors and slow requests) to control cost.

Logs

  • Timestamped records of events, best written as structured JSON: {"level": "error", "msg": "payment declined", "order_id": "o_55", "trace_id": "4bf9..."}.
  • Answer: "Why did this request fail? What exact error did the payment provider return?"
  • The most detailed and most expensive at scale; set retention and log levels deliberately, and never log secrets or full card numbers.

Working together in an incident

  1. An alert fires: checkout error rate is 5% (metric).
  2. The dashboard shows errors started at 10:42, only in one region (metric labels).
  3. An exemplar or trace search finds failed checkout traces; they show the error comes from the inventory service's database call (trace).
  4. Logs filtered by those trace IDs show "connection pool exhausted" after a deploy at 10:40 (log).
  5. Roll back the deploy; the error rate returns to normal.

Tools

OpenTelemetry provides standard SDKs and a collector for all three signals, so you can send them to Prometheus and Grafana, Jaeger or Tempo, Elasticsearch or Loki, or a commercial platform without changing application code.

Observability versus monitoring

Monitoring checks known failure conditions. Observability means having enough rich data to answer new questions about failures nobody predicted.

By level

Fresher: Explain metrics as numbers on dashboards, traces as the journey of one request, and logs as detailed messages. A fresher should say which one fires alerts.

Mid: Describe RED metrics, span trees and context propagation, structured logs, and a correlated incident workflow. Mention sampling.

Senior: Discuss cardinality control, tail-based sampling, retention and cost, SLO-based alerting and OpenTelemetry pipelines. Expect a practised incident narrative.

Key points

  • Metrics show that something is wrong, cheaply
  • Traces show where in a request path the problem is
  • Logs explain why, with full detail
  • Shared trace IDs link all three
  • OpenTelemetry standardises collection

Common mistakes

  • Logging everything at debug level in production
  • Putting user IDs or request IDs in metric labels
  • Tracing without propagating context between services
  • Logging secrets or personal data

Follow-ups

  • How would you choose a trace sampling strategy?
  • What is an SLO and how do metrics support it?
  • How do you control log storage costs?

Tips

  • Give one question each pillar answers
  • Walk through a short incident using all three
  • Mention correlation by trace ID

Evaluation rubric

  • Correct description of each pillar
  • Clear use of each in practice
  • Explains correlation between them
  • Awareness of cost and cardinality
98.system-design-0098Mediummid

How do you deploy new code and change a database schema with zero downtime? Cover rolling, blue-green and canary deploys and the expand-and-contract migration pattern.

Replace instances gradually behind a load balancer (rolling), switch traffic between two full environments (blue-green), or send a small share of traffic to the new version and watch metrics before continuing (canary). Because old and new code run at the same time, schema changes must be compatible with both: expand the schema first (add nullable columns or new tables), deploy code that writes both and reads safely, backfill, switch reads, and only then contract by removing the old structures. Every step must be reversible.

Full answer

Deploy strategies

  • Rolling. Replace instances a few at a time; the load balancer stops sending traffic to an instance (draining in-flight requests) before it restarts. Cheap, but old and new versions serve traffic together for a while, and a rollback is another rolling deploy.
  • Blue-green. Run the new version (green) next to the old (blue), test it, then switch all traffic at the load balancer or DNS. Instant rollback by switching back. Costs double capacity during the switch.
  • Canary. Send 1%, then 10%, then 50% of traffic to the new version, comparing error rates and latency with the old one automatically. Stop and roll back if metrics worsen. The safest for large services.
  • Feature flags separate deploying code from releasing features, so risky behaviour is turned on gradually after the deploy.

Requirements for all: health checks that reflect real readiness, graceful shutdown, and backward-compatible APIs between services (a new client may talk to an old server and the other way round).

Schema changes: expand and contract

Example: rename users.fullname to users.display_name.

  1. Expand. Add display_name as a nullable column. Old code ignores it. (On large tables, use online schema change tools or database features that avoid long locks.)
  2. Dual write. Deploy code that writes both columns and reads display_name when present, falling back to fullname.
  3. Backfill. Copy fullname into display_name in small batches to avoid locking and replication lag.
  4. Switch reads. Deploy code that reads only display_name (still writing both, for rollback safety).
  5. Contract. After a safe period, stop writing fullname, then drop the column.

Each step is a separate deploy and can be rolled back without data loss, because at every point both old and new code can run against the schema.

Dangerous changes

  • Adding a NOT NULL column without a default, or adding an index without the online option, can lock a large table.
  • Dropping or renaming a column in the same deploy as the code change breaks the instances still running old code.
  • Changing an enum or a message format that other services read; version messages and accept both formats during the transition.

Checklist

Automated migrations run before the code that needs them, migrations are backward compatible, long backfills are throttled and resumable, and dashboards are watched during each step.

By level

Fresher: Explain that servers are updated a few at a time so users never see the site go down. A fresher should know why removing a column early breaks old servers.

Mid: Compare rolling, blue-green and canary deploys, and walk through expand and contract with a backfill. Mention feature flags.

Senior: Discuss online schema change tools, large backfills, cross-service compatibility, mobile client lag and automated canary analysis. Expect a reversible plan at every step.

Key points

  • Rolling, blue-green and canary trade cost against rollback speed and safety
  • Old and new code run together, so changes must be compatible
  • Expand, dual write, backfill, switch reads, contract
  • Backfill in small throttled batches
  • Every step separately deployable and reversible

Common mistakes

  • Renaming or dropping a column in the same release as the code change
  • Long locking migrations on large tables
  • Canary releases without automatic metric comparison
  • No graceful shutdown, so in-flight requests fail during deploys

Follow-ups

  • How would you split one table into two with zero downtime?
  • How do you handle a migration on a 2 TB table?
  • How do mobile apps that update slowly affect API changes?

Tips

  • Use the column rename example
  • Say clearly that both versions run at once
  • Pair canaries with automated rollback

Evaluation rubric

  • Correct deploy strategies and trade-offs
  • Expand-and-contract explained step by step
  • Identifies dangerous migrations
  • Rollback and compatibility reasoning
99.system-design-0099Easyfresher

What is the difference between authentication and authorisation, and how do sessions, JWTs and role-based access control fit together in a web application?

Authentication answers "who are you?" by checking credentials such as a password plus a second factor; authorisation answers "what are you allowed to do?" by checking permissions for each action. After login, the server remembers the user with a session ID in a secure cookie or with a signed token such as a JWT. Each request is then authorised, often with role-based access control (roles grant permissions) plus ownership checks such as "a learner can see only their own submissions".

Full answer

Authentication (authN)

Proving identity:

  • Something you know (password), have (phone with an authenticator app, security key) or are (fingerprint).
  • Passwords are stored as slow, salted hashes (bcrypt, scrypt, Argon2), never in plain text.
  • Multi-factor authentication stops most account takeovers from leaked passwords.
  • Sign-in with Google or another identity provider delegates authentication (see OAuth and OpenID Connect).

Remembering the user

Server-side sessions. After login, the server creates a random session ID, stores session data (user ID, expiry) in a database or Redis, and sends the ID in a cookie marked HttpOnly, Secure and SameSite. Logging out deletes the session, which takes effect immediately.

Tokens (JWT). The server signs a token containing claims (user ID, roles, expiry). Any service with the public key can verify it without a lookup, which suits APIs and microservices. But a JWT cannot be revoked before it expires, so keep access tokens short-lived (for example 15 minutes) and use refresh tokens that can be revoked.

Authorisation (authZ)

Checking each action:

  • RBAC (role-based): users have roles (learner, instructor, admin); roles have permissions (course:edit, grades:view).
  • Ownership and attribute checks (ABAC): "an instructor can edit only courses they own", "a learner can view a submission only if it is theirs".
  • Check on the server for every request; hiding a button in the UI is not security.
  • Deny by default, and centralise checks in middleware or a policy service so they are not forgotten in one endpoint.

Example request

  1. A learner sends GET /v1/submissions/s_731 with a session cookie.
  2. Authentication middleware looks up the session: user u_42, role learner.
  3. Authorisation: learners need submission:view (granted) and the submission's owner must be u_42. It belongs to u_77, so return 403 Forbidden (or 404 to avoid revealing that it exists).

401 Unauthorized means "not authenticated"; 403 Forbidden means "authenticated but not allowed".

Common mistakes in practice

Insecure direct object references (changing an ID in the URL shows someone else's data), long-lived JWTs with no revocation, storing tokens in localStorage where injected scripts can read them, and checking permissions only in the front end.

By level

Fresher: Explain authentication as logging in and authorisation as what you are allowed to do after logging in. A fresher should give an example of each.

Mid: Compare sessions and JWTs, describe RBAC with ownership checks and the 401 versus 403 difference. Mention password hashing.

Senior: Discuss revocation strategies, token storage in browsers, ABAC and policy engines, central enforcement and common access-control vulnerabilities. Expect a defence-in-depth view.

Key points

  • Authentication proves identity; authorisation checks permissions
  • Sessions in secure cookies are revocable; JWTs are verifiable without lookups but hard to revoke
  • Keep access tokens short-lived with revocable refresh tokens
  • RBAC plus ownership checks on every server request
  • 401 means not authenticated; 403 means not allowed

Common mistakes

  • Checking permissions only in the user interface
  • Forgetting ownership checks so users can read others' records by changing an ID
  • Long-lived JWTs with no revocation plan
  • Storing passwords with fast hashes or in plain text

Follow-ups

  • How would you log out a user everywhere when they change their password?
  • When would you choose ABAC over RBAC?
  • How do you store tokens safely in a browser?

Tips

  • Define both terms in one sentence each
  • Walk through one request with both checks
  • Explain 401 versus 403

Evaluation rubric

  • Clear distinction between authN and authZ
  • Correct session and JWT trade-offs
  • RBAC and ownership checks on the server
  • Awareness of common vulnerabilities
100.system-design-0100Mediummid

Explain OAuth 2.0 and OpenID Connect, including the authorisation code flow with PKCE, and how mutual TLS secures service-to-service communication.

OAuth 2.0 lets a user grant an application limited access to their data at another service by issuing access tokens, without sharing the password. OpenID Connect adds an identity layer on top, returning a signed ID token that says who the user is, which enables "Sign in with Google". Browser and mobile apps should use the authorisation code flow with PKCE. For service-to-service calls, mutual TLS makes both sides present certificates, so each service proves its identity and traffic is encrypted, a common base for zero-trust networks.

Full answer

Roles in OAuth 2.0

  • Resource owner: the user.
  • Client: the application that wants access (for example a study planner that reads your Google Calendar).
  • Authorisation server: issues tokens after the user consents (Google's accounts service).
  • Resource server: the API that accepts tokens (Google Calendar API).

OAuth is about authorisation (delegated access, limited by scopes such as calendar.readonly), not about proving who the user is.

Authorisation code flow with PKCE

  1. The client creates a random code_verifier and sends its hash, the code_challenge, with the user to the authorisation server: /authorize?response_type=code&client_id=..&redirect_uri=..&scope=..&state=..&code_challenge=..&code_challenge_method=S256.
  2. The user signs in and consents.
  3. The authorisation server redirects back with a short-lived code (and the same state, which the client checks to prevent cross-site request forgery).
  4. The client exchanges the code plus the original code_verifier at the token endpoint for an access token (and often a refresh token).
  5. The client calls the API with Authorization: Bearer <access_token>.

PKCE ensures that an attacker who intercepts the code cannot exchange it without the verifier, which matters for mobile and single-page apps that cannot keep a client secret. The older implicit flow, which returned tokens in the URL, is no longer recommended.

For machine-to-machine access with no user, the client credentials flow exchanges the client's own credentials for a token.

OpenID Connect (OIDC)

OIDC adds authentication: request the openid scope and the token response includes an ID token, a signed JWT with claims such as sub (stable user ID), email, iss (issuer), aud (your client ID) and exp. Your application validates the signature, issuer, audience and expiry, then creates its own session. Access tokens are for calling APIs; ID tokens are for your app to learn who logged in. Do not send ID tokens to APIs as access tokens.

Mutual TLS for services

In normal TLS only the server shows a certificate. In mTLS both sides do:

  1. The client service connects and checks the server's certificate against a trusted internal certificate authority.
  2. The server requests and verifies the client's certificate.
  3. Both now know each other's identity (for example spiffe://schoolabe/payments), and traffic is encrypted.

Service meshes (Istio, Linkerd) issue short-lived certificates automatically and rotate them, so application code does not handle keys. Authorisation policies then say "only the checkout service may call payments".

How they combine

Users sign in with OIDC; the front end calls APIs with OAuth access tokens; services call each other over mTLS, passing the user's token or a derived one when the downstream service needs the user context. Network location alone is never trusted.

By level

Fresher: Explain that OAuth lets an app access your data elsewhere without your password, and OIDC tells the app who you are. A fresher should describe the redirect to the sign-in page and back.

Mid: Walk through the code flow with PKCE, validate ID tokens and explain client credentials. Describe how mTLS works between services.

Senior: Discuss refresh token rotation, token exchange, service mesh certificate management, authorisation policies between services and zero-trust design. Expect precise token handling rules.

Key points

  • OAuth 2.0 delegates limited access with scoped tokens
  • OIDC adds an ID token that says who the user is
  • Authorisation code flow with PKCE for browser and mobile apps; state prevents CSRF
  • Client credentials for machine-to-machine
  • mTLS gives both services certificates for identity and encryption

Common mistakes

  • Using OAuth access tokens as proof of identity without OIDC
  • Using the implicit flow in new apps
  • Skipping validation of issuer, audience and expiry on ID tokens
  • Trusting internal traffic because it is inside the network

Follow-ups

  • How do refresh token rotation and reuse detection work?
  • How would you revoke a compromised service certificate?
  • When should a backend exchange a user token for a downstream token?

Tips

  • Name the four OAuth roles
  • Walk through PKCE step by step
  • Separate ID tokens from access tokens

Evaluation rubric

  • Correct OAuth roles and flows
  • PKCE and state explained
  • Correct OIDC ID token use and validation
  • mTLS mechanics and zero-trust context