Courses / System Design Interview / Chapter 2
Module 1 · Foundations · Chapter 2 of 49
Core Concepts: RPCs, Consistency, Failures and Time
Builds on The System Design Interview: How It Runs and How to Answer. Next up: Non-Functional Requirements: Availability, Scale, Latency and More.
Part 1 · Abstractions and partial failure
A call that looks like a function
Every large service is many computers cooperating over a network. The network is where most of the new problems come from.
A distributed system is a set of computers that work on one task and talk only by sending messages. Programming such a system is easier because of an abstraction: a remote call is written as an ordinary function call. You call charge(order) and a value comes back, and it hides the fact that the work ran on another machine.
The abstraction is useful, and it leaks. A local function call is fast, it either returns or raises, and it runs exactly once. A remote call is slower by orders of magnitude, can fail in ways a local call cannot, and may run zero, one or several times. The snippet below measures the first difference. It starts a tiny server on this machine and times a local call against a round trip to it over the loopback network, which never leaves the computer.
import asyncio, sys, time print("python", sys.version.split()[0]) def add(a, b): return a + b async def handle(reader, writer): while line := await reader.readline(): a, b = map(int, line.split()) writer.write(f"{add(a, b)}\n".encode()) await writer.drain() writer.close()
async def main(): server = await asyncio.start_server(handle, "127.0.0.1", 55432) n = 2000 t = time.perf_counter() for i in range(n): add(i, 1) local = (time.perf_counter() - t) / n reader, writer = await asyncio.open_connection("127.0.0.1", 55432) t = time.perf_counter() for i in range(n): writer.write(f"{i} 1\n".encode()) await reader.readline() remote = (time.perf_counter() - t) / n print(f"local call: {local * 1e6:9.3f} us") print(f"localhost trip: {remote * 1e6:9.3f} us") print(f"ratio: about {remote / local:,.0f}x") writer.close() server.close() asyncio.run(main())
python 3.12.10 local call: 0.042 us localhost trip: 46.931 us ratio: about 1,109x
A real run; timings vary from run to run.
On this machine the loopback round trip took about a thousand times longer than the local call. Loopback involves no cable, no router and no other computer. Colin Scott's latency page puts a round trip inside one data centre at about 500 microseconds, and Peter Norvig's table puts a packet from the United States to Europe and back at about 150 ms, so a real call costs far more still.
Three outcomes, and one you cannot see
Speed is the smaller problem. The larger one is that a remote call has more than two outcomes. The next snippet makes two of them happen: it calls a port with no server behind it, and a server that accepts the connection and then never answers.
import asyncio async def silent(reader, writer): # accepts, never answers await asyncio.sleep(10) async def call(port): try: r, w = await asyncio.open_connection("127.0.0.1", port) w.write(b"1 1\n") await asyncio.wait_for(r.readline(), 0.5) return "reply" except ConnectionRefusedError: return "refused: nobody is listening" except TimeoutError: return "timed out: no reply in 0.5 s" async def main(): server = await asyncio.start_server(silent, "127.0.0.1", 55433) print("port 55433 (silent): ", await call(55433)) print("port 55434 (no server):", await call(55434)) server.close() asyncio.run(main())
port 55433 (silent): timed out: no reply in 0.5 s port 55434 (no server): refused: nobody is listening
A real run. The silent server holds the connection open.
The first failure is clear. The caller knows nothing ran because nobody was there to run it. The second is not. After half a second of silence the caller does not know whether the server never got the request, got it and is still working, finished and lost the reply, or crashed halfway. This is partial failure: part of the system fails while the rest keeps running, and the caller cannot tell which part.
A timeout is the only tool a caller has here. It turns "no answer yet" into "I give up", but it says nothing about what happened on the other side. The next lessons build on this: what to do after a timeout, how replicas disagree, and how to detect a failure that you can only guess at.
| Term | Meaning |
|---|---|
| Distributed system | Computers that cooperate on one task by sending messages over a network |
| Abstraction | An interface that hides detail, such as a remote call written like a local one |
Part 2 · RPCs, timeouts and retries
Calling another machine
A remote procedure call (RPC) is a function call whose body runs on another machine. The caller sends the function name and arguments as a message, the server runs the function, and a reply carries the result back. Frameworks such as gRPC generate the message handling so the call looks local.
Because a call can hang, good RPC frameworks give every call a deadline: a point in time after which the caller stops waiting. gRPC's documentation says that when the deadline passes the call ends with a DEADLINE_EXCEEDED error. It also notes that either side can cancel a call, and gives a warning that matters for everything below: changes made before a cancellation are not rolled back.
That warning is the heart of the problem. If a client gives up on a charge after 200 ms, the server may still be halfway through it. The client sees a failure. The server may later see success.
The usual reaction is to retry. Retrying is safe only when the operation is idempotent: doing it several times has the same effect as doing it once. The HTTP specification (RFC 9110) defines it this way and lists PUT, DELETE and the safe methods such as GET as idempotent. It also says a client should not automatically retry a request with another method, such as POST, unless it has some way to know the request is idempotent in practice, or to detect that the first attempt was never applied. A payment is the standard example of an operation that is not idempotent by default.
A retry that runs the work twice
The sequence below shows both runs of the snippet on the next page. First, a client times out and retries a charge, and the server applies it twice. Then the client sends an idempotency key, a unique label for the intended action, and the server uses it to recognise the retry.
Watch for a retry that makes the server run the charge twice
Read it as steps
A client times out on a slow charge and retries; the key makes the server charge once
The first half is the dangerous case. The server never learned that the client gave up, so both requests ran. In the second half the server recognises the key, so the second request waits for the first one's result and returns it.
The code, run twice
The server below takes 0.3 s to apply a charge. The client waits only 0.2 s, so its first attempt always times out. The server runs in one of two modes: plain, which does the work for every request, and keyed, which remembers each idempotency key and shares one result between requests that carry it.
import asyncio, json, sys MODE = sys.argv[1] # "plain" or "keyed" ledger = [] # charges really applied seen = {} # idempotency key -> task async def do_charge(req): await asyncio.sleep(0.3) # slow work ledger.append(req["amount"]) return {"ok": True, "charge_no": len(ledger)} async def handle(reader, writer): req = json.loads(await reader.readline()) key = req.get("key") if MODE == "keyed" and key: if key not in seen: seen[key] = asyncio.ensure_future(do_charge(req)) result = await seen[key] else: result = await do_charge(req) try: writer.write((json.dumps(result) + "\n").encode()) await writer.drain() except OSError: pass # the client already gave up writer.close()
async def call(req, timeout): reader, writer = await asyncio.open_connection("127.0.0.1", 55435) writer.write((json.dumps(req) + "\n").encode()) try: line = await asyncio.wait_for(reader.readline(), timeout) return json.loads(line) finally: writer.close() async def main(): server = await asyncio.start_server(handle, "127.0.0.1", 55435) req = {"op": "charge", "amount": 500, "key": "order-17"} for attempt, timeout in ((1, 0.2), (2, 1.0)): try: print(f"attempt {attempt}:", await call(req, timeout)) break except TimeoutError: print(f"attempt {attempt}: timed out after {timeout} s") await asyncio.sleep(0.5) print("server ledger:", ledger, "total", sum(ledger)) server.close() asyncio.run(main())
The mode is the first command-line argument. Here are both runs, from the same file.
attempt 1: timed out after 0.2 s attempt 2: {'ok': True, 'charge_no': 2} server ledger: [500, 500] total 1000
python c2_l2_rpc.py plain
attempt 1: timed out after 0.2 s attempt 2: {'ok': True, 'charge_no': 1} server ledger: [500] total 500
python c2_l2_rpc.py keyed
In the plain run the ledger holds two charges, 1000 in total, for one order. In the keyed run the second request arrived while the first was still running, found the key in seen, and waited for the same result: one charge and charge_no 1 for both attempts.
Part 3 · Consistency models
Replicas that disagree
To survive failures and serve more readers, systems keep copies of the same data on several machines. Each copy is a replica. A write reaches the replicas at different times, so for a short while they disagree. The time between a write and every replica seeing it is called replication lag, and a read that returns a value older than the latest write is a stale read.
A consistency model is a promise about which values a read may return. Stronger models give simpler behaviour and cost speed or availability. These are the ones worth knowing, roughly from strongest to weakest. The two session guarantees, read-your-writes and monotonic reads, are not stronger or weaker than each other; each rules out a different surprise.
| Model | The promise | Cost |
|---|---|---|
| Linearizable | Every operation appears to happen at one instant, in an order consistent with real time | Under a network partition some or all nodes cannot make progress (Jepsen) |
| Sequential | All operations appear in one order that respects each process's own order, but not necessarily real time | Also not totally available under partition (Jepsen) |
| Causal | Operations that are causally related appear in the same order everywhere | Can stay available if clients keep using the same server (Jepsen) |
| Read-your-writes | After you write, your own reads never return an older value | Needs a session or a route to a fresh replica |
| Monotonic reads | Once you have seen a value, you never see an older one | Needs a sticky replica or a version check |
A write, a lagging follower and an old value
Watch for a read that lands on a follower the write has not reached
Read it as steps
A client writes to the leader, then reads from a follower the write has not reached
The write was acknowledged, yet a later read returned the old value. Nothing broke: replication was simply slower than the read. Whether that is acceptable is a requirement. A like count can be stale for a second. A bank balance shown right after a transfer cannot.
Read rules on three replicas
The snippet below models one leader and two followers. A write reaches the leader at once, the first follower after 2 ticks and the second after 5. There are two writes to x, at tick 0 (value 1) and tick 4 (value 2), and nine reads, one per tick, each sent to a replica chosen at random with a fixed seed. A value of 0 means the replica has no value yet.
import random LAG = {"leader": 0, "r1": 2, "r2": 5} # ticks before a write arrives WRITES = [(0, 1), (4, 2)] # (tick, value) written to x NAMES = list(LAG) def value_at(replica, tick): seen = 0 for t, v in WRITES: if t + LAG[replica] <= tick: seen = v return seen def latest(tick): # last acknowledged write return max(v for t, v in WRITES if t <= tick) rng = random.Random(7) picks = [rng.choice(NAMES) for _ in range(9)] # one pick per read
def run(rule): out, last = [], 0 for tick, pick in enumerate(picks, start=1): v = value_at(pick, tick) if rule == "monotonic" and v < last: v = value_at("leader", tick) # use the leader if rule == "own-writes" and v < latest(tick): v = value_at("leader", tick) # I wrote it if rule == "leader": v = value_at("leader", tick) out.append(v) last = v return out print("tick ", *range(1, 10)) print("latest ", *[latest(t) for t in range(1, 10)]) for rule in ("any", "monotonic", "own-writes", "leader"): vals = run(rule) stale = sum(v < latest(t) for t, v in enumerate(vals, start=1)) back = sum(b < a for a, b in zip(vals, vals[1:])) print(f"{rule:11}", *vals, f" stale={stale} went-back={back}")
Four read rules run over the same random choices. any accepts whatever the chosen replica holds. monotonic falls back to the leader if the answer would go backwards. own-writes falls back to the leader if the answer is older than the client's own latest write. leader always reads the leader.
tick 1 2 3 4 5 6 7 8 9 latest 1 1 1 2 2 2 2 2 2 any 0 1 1 0 2 2 1 2 2 stale=3 went-back=2 monotonic 0 1 1 2 2 2 2 2 2 stale=1 went-back=0 own-writes 1 1 1 2 2 2 2 2 2 stale=0 went-back=0 leader 1 1 1 2 2 2 2 2 2 stale=0 went-back=0
A real run; the seed makes the replica choices repeatable.
Under any, three reads were stale and the value went backwards twice, from 1 to 0 and from 2 to 1, which is the eventual-consistency behaviour. The monotonic rule removed the backwards steps but still returned one stale value at tick 1. The own-writes rule gave no stale reads here because this client wrote every value. Reading from the leader was never stale in the toy, but in a real system a leader can be replaced, and reads that must be current need more care, as a later chapter on databases shows.
Part 4 · Failure models and failure detection
How machines are allowed to fail
To reason about a design you must say how its parts can fail. A failure model is that statement. The common ones, from the friendliest to the hardest, are these.
| Model | What the faulty node does |
|---|---|
| Crash-stop | Works correctly until it halts, and never returns |
| Crash-recovery | Halts, then may restart, possibly having lost its memory |
| Omission | Runs, but some messages it sends or receives are lost |
| Byzantine | Behaves arbitrarily, including sending wrong or conflicting messages |
Most business systems assume crash-recovery plus a network that loses and delays messages. They do not assume Byzantine behaviour, which is expensive to defend against and matters mainly when the parties do not trust each other. Choosing the model is a design decision. If you assume crash-stop, you never plan for a server that comes back with an old state.
Whichever model you pick, you need a way to notice a node has failed. The standard method is the heartbeat: every node sends a small "I am alive" message at a fixed interval, and a failure detector marks a node as suspected if no heartbeat arrives within a timeout.
A detector that guesses wrong
The detector can never be sure. A message may be late because the node is dead, because the node is paused (for example, a long garbage-collection pause), or because the network is slow. From the outside these look the same.
The snippet starts three nodes sending a heartbeat every 50 ms. One keeps going, one pauses for 400 ms and then resumes, and one stops for good. The detector checks every 50 ms and suspects a node after 150 ms of silence.
import asyncio, time T0 = time.perf_counter() last = {} INTERVAL, TIMEOUT = 0.05, 0.15 def log(msg): print(f"{(time.perf_counter() - T0) * 1000:5.0f} ms {msg}") async def node(name, pause_at=None, stop_at=None): for i in range(30): if i == stop_at: return # crashed: sends nothing more if i == pause_at: await asyncio.sleep(0.4) # alive but stalled last[name] = time.perf_counter() await asyncio.sleep(INTERVAL)
async def detector(): suspected = set() for _ in range(28): await asyncio.sleep(INTERVAL) now = time.perf_counter() for name, seen in last.items(): silent = now - seen > TIMEOUT if silent and name not in suspected: suspected.add(name) log(f"suspect {name}") elif not silent and name in suspected: suspected.discard(name) log(f"{name} is back: it was never dead") async def main(): await asyncio.gather(node("a"), node("slow", pause_at=6), node("dead", stop_at=6), detector()) asyncio.run(main())
489 ms suspect slow 489 ms suspect dead 782 ms slow is back: it was never dead
A real run; the timestamps vary by a few milliseconds each time.
The detector suspected slow and dead at the same moment, about half a second in, and had no way to tell them apart. Then slow sent a heartbeat and was taken off the list: a false suspicion. If the system had already moved its work elsewhere, it would now have two nodes believing they own the same job.
Choosing the timeout
The timeout trades speed against false alarms. A short timeout finds a dead node quickly but suspects healthy, briefly slow nodes. A long timeout rarely accuses a healthy node but leaves real failures unnoticed for longer, while requests keep going to the dead node.
Because a suspicion can be wrong, designs treat it as a hint and make the follow-up action safe. Two tools are common. A lease is a lock with an expiry: a node may act only while its lease is valid, so a node that was wrongly suspected stops acting once its time runs out. A fencing token is a number that grows with each new owner, so that the storage layer can reject writes from an old one. Later chapters use leases.
The token covers the case a lease alone cannot. Suppose node A holds a lease with token 33, then stalls in a long pause. Its lease expires, node B gets a new lease with token 34 and starts writing. Then A wakes up and, not knowing it was replaced, sends a write tagged 33. The store has already seen 34, so it rejects 33. Without the token, A and B would both write, a situation called split brain: two nodes each believe they are in charge, and the data ends up with both sets of changes mixed together.
In the run, why did the detector suspect slow even though it was alive?
- It sent no heartbeat for 400 ms, longer than the 150 ms timeout.
- From the detector's side a paused node and a dead node look identical until a heartbeat arrives.
What is the cost of making the timeout much longer?
- Fewer false suspicions, but real failures are noticed later, so more requests go to a dead node.
- The right value depends on how costly a wrong suspicion is compared with a slow detection.
After a failover, the old leader wakes from a pause and sends a write tagged with token 12. The new leader writes with token 13. What should the store do, and why?
- Reject the write tagged 12, because it has already accepted a write tagged 13 from a newer owner.
Part 5 · Ordering without a global clock, and CAP
Why clocks cannot order events
Two machines have two clocks, and the clocks drift apart. If server A stamps an event 10:00:00.005 and server B stamps another 10:00:00.003, you cannot conclude that B's event came first. Their clocks may disagree by more than that.
Leslie Lamport's 1978 paper "Time, Clocks, and the Ordering of Events in a Distributed System" starts from a different idea. Order events by what could have influenced what. Event a happened before event b, written a → b, if one of three things holds: a and b are in the same process and a comes first; a is the sending of a message and b is its receipt; or there is a chain of such steps from a to b. If neither a → b nor b → a, the events are concurrent: neither could have affected the other.
A logical clock is a counter that respects this order. Lamport's rules, in plain words: each process increments its counter between any two of its events; every message carries the sender's counter; and on receiving a message, a process sets its counter to be greater than both its own value and the one in the message.
A Lamport clock on three processes
The snippet runs those rules over three processes, p, q and r. Process p does a local event, sends a message to q, and does another local event. Process q receives the message and sends one to r. Process r also does a local event before it hears from anyone.
clock = {"p": 0, "q": 0, "r": 0}
inbox = {}
def event(proc, what):
clock[proc] += 1
print(f"{proc}: {what:<22} clock={clock[proc]}")
def send(src, dst, name):
event(src, f"send {name} to {dst}")
inbox[name] = clock[src] # the timestamp travels with it
def receive(proc, name):
clock[proc] = max(clock[proc], inbox[name]) # catch up, then tick
event(proc, f"receive {name}")
event("r", "r1 (local)")
event("p", "p1 (local)")
send("p", "q", "m1")
event("p", "p2 (local)")
receive("q", "m1")
send("q", "r", "m2")
receive("r", "m2")
event("r", "r2 (local)")
print("final clocks:", clock)r: r1 (local) clock=1 p: p1 (local) clock=1 p: send m1 to q clock=2 p: p2 (local) clock=3 q: receive m1 clock=3 q: send m2 to r clock=4 r: receive m2 clock=5 r: r2 (local) clock=6 final clocks: {'p': 3, 'q': 4, 'r': 6}
Follow the message m1: p sent it with clock 2, so q jumped to 3 when it received it. Then m2 carried 4 to r, which jumped from 1 to 5. Every cause has a smaller number than its effect: send m1 is 2, receive m1 is 3.
The converse is false. The local event r1 has clock 1 and the send of m1 has clock 2, but they are concurrent: r1 happened on another process before any message reached it. Likewise p2 and the receipt of m1 both have clock 3 and are concurrent. A smaller timestamp does not prove one event caused another. Lamport's paper handles the ties by breaking them with a fixed order of process names, which yields one agreed order of all events that never contradicts cause and effect.
What CAP says in practice
Several of these ideas meet in the CAP statement: when the network is partitioned, a replicated system cannot be both consistent and available. Here consistent means linearizable, the strongest model in the consistency lesson, and available means every request to a working node gets an answer. A partition means some nodes cannot reach others. In that case a system may refuse requests it cannot answer correctly, which keeps the data consistent but is unavailable to those users, or it may answer from what it has, which stays available but can return stale data.
Jepsen's page on linearizability states the first half exactly: a linearizable system cannot be totally available under a partition, because some or all nodes will be unable to make progress. Eric Brewer, who first proposed CAP, wrote in 2012 that the popular "pick two of three" framing is misleading. Partitions are rare, so a system can offer both consistency and availability most of the time. The choice also is not made once for a whole system; it can be made again for each operation, each kind of data and each user.
| During a partition | What the system does | Example of a fit |
|---|---|---|
| Prefer consistency | Rejects or delays requests it cannot answer correctly | Seat booking, account balance |
| Prefer availability | Answers from local data, which may be stale, and reconciles later | Like counts, a news feed |
Two events have Lamport clocks 3 and 5. Can you conclude the first caused the second?
- No. A smaller timestamp is consistent with causing the later event, but concurrent events can also have ordered timestamps.
- In the run, r1 (clock 1) and the send of m1 (clock 2) were concurrent.
What did Brewer say was wrong with "pick two of three"?
All chapters · Previous: The System Design Interview: How It Runs and How to Answer