APIs and Services
What changes when a function call has to cross a network that can lose, duplicate and delay it?
The part opens with the eight fallacies of distributed computing, three outages matched to them, and the Job split into three services: over a network that loses 5% of messages and duplicates 2%, retries without keys count 'the' 2,924 times instead of 2,733. Birrell and Nelson's stubs make a remote call look local, and Waldo's four reasons say why it never is. The part then derives what goes on the wire: JSON's integers stop being exact at 2^53, and Protocol Buffers' varints, tags and zigzag are built byte by byte and checked against the published examples. Schema evolution is treated as subtyping, with seven changes checked for forward and backward compatibility. The centre of the part is delivery: at most once loses counts, at least once adds them, and at least once plus deduplication is exact, which a model checker confirms over every execution of two retried increments. From there it covers Hyrum's law, queues with visibility timeouts, backpressure and retry storms, the transactional outbox and sagas, load balancing by two choices, forged JWTs and clock pitfalls. It ends with the Job's counts staying exact under 20% loss with idempotency keys, and at the frontier: session types, TLA+ and verified distributed systems.
What you need. Binary and hexadecimal, HTTP's methods at the level of a first web course, and the exponential distribution for the queueing chapter.
- Mathematics, ideas and history
- RPC, protobuf varints and schema evolution, REST and pagination, idempotency and exactly-once, Hyrum's law, queues and backpressure, microservices, outbox and sagas, OAuth and JWT
- What we build or compute
- the Job as services under message loss
What you will be able to do
Degree
- Encode an integer as a varint and a signed integer with zigzag, and decode a short protobuf message by hand.
- Explain why a request that got no reply cannot be told from one that was never received, and what at most once and at least once each promise.
- Say which HTTP methods are safe and which are idempotent, and what a repeated POST does.
Graduate
- Prove in a model that retrying until acknowledged plus deduplication by id applies every operation exactly once.
- Decide whether a schema change is backward compatible, forward compatible, both or neither.
- Compute the time in an M/M/1 queue against load, and what a bound on the queue trades for it.
Research
- Explain how a multiparty session type projects a global protocol onto each service and what it guarantees.
- Compare what model checking, proof and deterministic simulation each establish about a distributed protocol, and state what remains open.
Industry
- Design an endpoint that is safe to retry, with an idempotency key recorded atomically with its effect.
- Replace a dual write by a transactional outbox, and a distributed transaction by a saga with compensations.
- Choose retry backoff, jitter and a retry budget so that an outage does not become a retry storm.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 20 min · Graduate 50 min · Research 52 min · Industry 36 min.
- 0Eight fallacies, and the Job in three piecesDegree3 min
- 1Calls across a networkDegree3 min
- 2Bytes on the wireDegree4 min
- 3Schemas that evolveGraduate3 min
- 4API stylesDegree4 min
- 5At most, at least, exactly onceDegree4 min
- 6Designing and versioning APIsIndustry3 min
- 7Queues and pub/subIndustry4 min
- 8BackpressureGraduate4 min
- 9Monoliths and microservicesIndustry3 min
- 10Data across servicesGraduate4 min
- 11Finding, routing and trusting servicesIndustry3 min
- 12Time in APIsIndustry3 min
- 13The Job as three servicesGraduate3 min
- 14Frontier: services you can proveResearch2 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Eight fallacies, and the Job in three piecesDegree3 min
In the nineties, engineers at Sun Microsystems wrote down the assumptions that programmers new to networks tend to make, and that are false. The network is reliable. Latency is zero. Bandwidth is infinite. The network is secure. Topology doesn't change. There is one administrator. Transport cost is zero. The network is homogeneous. Peter Deutsch set down seven of them in 1994, building on an earlier list by Bill Joy and Tom Lyon, and James Gosling added the eighth. Every one of them is tempting, because a remote call looks exactly like a local one. And every one of them has taken down real systems.
Three examples. In October 2018, GitHub lost connectivity between two data centres for forty-three seconds. Its databases failed over across the country, writes landed on both sides, and the site ran degraded for about a day while engineers reconciled them. The network is not reliable. In October 2016, a botnet of hacked cameras and home routers, called Mirai, flooded the DNS provider Dyn, and many of the largest sites on the web were unreachable for hours. The network is not secure. And in October 2021, a routine command withdrew the routes of Facebook's backbone. Its DNS servers, seeing no backbone, took themselves offline, and the tools engineers needed to fix it were behind the same network. Topology changes, sometimes all at once.
Here is this part's experiment. We split the Job into three services: one tokenizes text, one counts words, one ranks them. The tokenizer sends its counts to the counter in 353 messages, over a network that loses five percent of messages and duplicates two. To survive loss, the tokenizer retries until the counter acknowledges. But a retried message may have arrived after all, and a duplicated one arrives twice. Without protection, the counts drift upward: the word the is counted 2,924 times instead of 2,733, and 1,403 of the 5,882 distinct words are wrong. Add one idea, an idempotency key on each message, and every count is exact. Most of this part is about ideas of that size, and the mathematics that says they work.
1Calls across a networkDegree3 min
In 1984 Andrew Birrell and Bruce Nelson, at Xerox PARC, described how to make a call to a procedure on another machine look like an ordinary call. The caller calls a local procedure, the client stub, with the same name and arguments. The stub marshals the arguments into bytes, and the runtime sends them across the network. On the server, a matching stub unmarshals the bytes and dispatches to the real procedure. The result travels back the same way, and the caller just sees a return value. A program called Lupine wrote the stubs.
In 1994 Jim Waldo, Geoff Wyant, Ann Wollrath and Sam Kendall, at Sun, wrote A Note on Distributed Computing, arguing that this illusion cannot be kept. They gave four reasons. The first is latency. A local call costs nanoseconds. A remote call, in this part's latency model, takes about ten milliseconds at the median and thirty at the ninety-ninth percentile: six or seven orders of magnitude more. A thousand local calls go unnoticed; a thousand remote calls take ten seconds. Remote interfaces need few calls, each doing a lot.
The fourth reason is the deepest: partial failure. A single computer works or it does not; a distributed system can be half broken. A client sends a request, no reply comes, and its timeout fires. What happened? Perhaps the request was lost, and the call never ran. Perhaps the server did the work, then crashed before replying. Perhaps it replied, and the reply was lost. From the client, all three look the same: silence. Retry, and the last two run the call twice: harmless for a read, a disaster for a payment.
Could a cleverer protocol remove the doubt? Part 38 proved it cannot. The client says do it; the server says done; but the server cannot know its done arrived, so the client acknowledges, and that acknowledgement needs one too. Take the shortest exchange that supposedly works. Its last message might be lost, so its sender cannot depend on it, and a shorter exchange would do just as well. There is no shortest. So an RPC system runs a call at most once, never retrying, or at least once, retrying until answered. Exactly once must be built into the call itself.
2Bytes on the wireDegree4 min
Start with the most common format of all. JSON writes numbers as decimal text and says nothing about precision, but JavaScript reads every number as a double, Part 4's sixty-four-bit float, with fifty-three significant bits. Up to two to the fifty-three, every integer is exact; above it, doubles are two apart. So two to the fifty-three plus one arrives as two to the fifty-three: it lies halfway, and rounds to the even neighbour. A nineteen-digit id is worse. Near a billion billion, doubles are two hundred and fifty-six apart, and the last digits change. So APIs send large ids as strings, and the JSON standard warns that larger integers may not survive.
Protocol Buffers, which Google open-sourced in 2008, write integers another way, as varints. Take a hundred and fifty. In binary it needs eight bits. Cut them into groups of seven, starting from the low end. Write the low group first, and give every byte a top bit that says whether another byte follows: one for the first byte, zero for the last. In hexadecimal that is nine six, zero one, exactly the bytes the encoding guide gives. So small numbers cost one byte, every further seven bits cost one more, and the very largest sixty-four-bit values need ten.
A message is a sequence of fields, and each field begins with a tag. The tag is the field number shifted left by three bits, combined with a wire type: zero for a varint, one and five for eight and four fixed bytes, two for anything with a length. So field one holding a varint has the tag zero eight, and the message a equals a hundred and fifty is zero eight, nine six, zero one. A string is wire type two: field two gives the tag one two, then the length, seven, then the seven bytes of the word testing. Nested messages and packed lists are length-delimited too. Our encoder reproduces every example in the guide, byte for byte.
Negative numbers expose a flaw. In two's complement, minus two has its top bit set, so as a varint all sixty-four bits must be sent, and it takes ten bytes. The sint types fix this with zigzag encoding, which interleaves the signs. Zero becomes zero, minus one becomes one, one becomes two, minus two becomes three. In code, shift left by one and exclusive-or with the sign bit copied across the word. Our version matches the guide's table, even at the extremes. Now minus two is the single byte zero three, and small numbers of either sign stay small: minus a thousand takes two bytes rather than ten.
Put it together on one record: an id, a word, its count, its novel, a score and three tags. As compact JSON it is 90 bytes. As Protocol Buffers it is 34, with the score as a zigzag sint and the tags as a packed list. The saving comes mostly from names: JSON repeats every field name in every record, and writes numbers as decimal text, where protobuf sends a one-byte tag and a varint. The price is that the bytes mean nothing without the schema: zero eight says field one, not id. Both sides must agree on the schema, and keep agreeing as it changes: the next chapter.
3Schemas that evolveGraduate3 min
A schema is never changed everywhere at once. Servers are upgraded a few at a time, in a rolling deploy, so for a while old and new code run side by side and send each other messages. And data outlives code: a database or a log, which Part 46 takes up, holds bytes written years ago. So a change must be backward compatible: new code can read old data. And usually it must be forward compatible as well: old code, not yet upgraded, can read what new code writes.
Part 14 has the answer. New code writes a record with three fields; old code expects two. The reader matches fields by number: word and count are there, with the types it expects. Novel is unknown, so it is skipped, though protobuf keeps its bytes to pass on. This is width subtyping: a record with more fields can go wherever fewer are expected. A reader accepts a writer's record when every field it requires is present, with a compatible type. Turn it round, and a reader that requires novel rejects every old record.
Our checker applies that rule both ways to seven changes of a small schema: a required word, field one, and an optional count, field two. Adding or removing an optional field is safe both ways. Adding a required field breaks backward compatibility: old data never contains it. Removing one breaks forward compatibility: old readers still demand it. Changing a type breaks both. Widening a 32-bit integer to 64 bits passes, since both are varints, though an old reader truncates values that no longer fit. And renumbering a field passes, both ways. That verdict is wrong.
Here is why. Old code writes the count, one thousand two hundred and twenty-six, as field two: the tag one zero, then a varint. New code expects the count in field five. To it, field two is unknown and is skipped, and field five is absent, so the count reads as zero. Nothing fails; every count is silently lost. The real rule: a field's number is its identity. Never change it, never reuse it, and reserve the number and name of a deleted field. And because a required field can never be safely added or removed, proto3 dropped required fields altogether.
4API stylesDegree4 min
Roy Fielding, one of the authors of HTTP's specification, named the web's architecture in his doctoral dissertation of 2000: representational state transfer, or REST. Everything the server knows about is a resource with a name, a URL, like book forty-two. A client receives only a representation of it, here in JSON, which links to other resources, like the book's author. Every resource answers the same few methods, so a cache or a proxy can understand any request. And each request is stateless: it carries everything needed to answer it, so any replica can reply.
RFC 9110, the definition of HTTP's semantics published in 2022, sorts its methods by two properties. A safe method asks for no change at all: GET, HEAD and OPTIONS only read. An idempotent method may change things, but sending it twice has the same intended effect as sending it once: PUT replaces a resource, DELETE removes it, however often you repeat them. POST is neither, and PATCH need not be. This is what makes retries safe. A client whose request timed out cannot know whether it was applied. Repeating the PUT leaves the cart as intended. Repeating the POST may place a second order: the next chapter's problem.
Long lists come in pages, and there are two ways to ask for the next one. With an offset, the client says: skip the rows I have, give me four more. Page one of this feed is rows twenty to seventeen. Now two new rows arrive at the top, everything shifts down, and skipping four lands on rows already seen. A cursor says instead: rows older than the last one I saw. It cannot repeat. We measured both on a thousand rows in pages of fifty. With three new rows per page, offsets repeat 63 rows; with ten, 240. Cursors repeat none. And since the database steps past every skipped row, offsets scan ten and a half thousand rows even with no inserts; a cursor reads only the thousand it returns.
GraphQL, released by Facebook in 2015, puts the client in charge of the shape. A query names the fields it wants, nested as deeply as it likes, and the response has exactly that shape, with no second round trip for the books. The server fills it in with a resolver per field, and the obvious resolvers hide a trap. One query fetches fifty authors; then each author's books resolver runs its own query. That is 51 queries, the N plus one problem; with each book's reviews, 251. The fix is batching, in the style of Facebook's DataLoader: collect every key requested in one tick, and fetch them together. 51 queries become 2, and 251 become 3. And since clients can write any query, public servers defend themselves with persisted queries and cost limits.
5At most, at least, exactly onceDegree4 min
A sender can promise one of three things about how often a message takes effect. At most once: send it once, never retry. Nothing repeats, but a lost message is gone. At least once: retry until acknowledged. Nothing is lost, but if the acknowledgement went missing, the retry applies the increment twice. Exactly once: retry until acknowledged, and have the receiver remember the identifier of every message it applied, skipping a repeat but acknowledging it again.
We ran all three on one simulated network: ten thousand increments, with five percent of messages lost, acknowledgements included, and two percent duplicated. At most once counted nine thousand six hundred and ninety-four: three hundred and six lost. At least once counted ten thousand seven hundred and fifty-four: seven hundred and fifty-four too many. Exactly once counted ten thousand, exactly. And it cost nothing extra on the wire: the same messages, in the same four rounds of retries, as at least once. The whole difference is a set of identifiers.
A simulation samples executions; a model checker visits all of them. Our model: two increments, each sent up to three times until acknowledged, over a network that may drop any message or acknowledgement, duplicate one, and deliver in any order. A breadth-first search visits every reachable state. With deduplication there are four thousand three hundred and nineteen, and in none does the counter exceed two; whenever both increments were acknowledged, it is exactly two. Without deduplication there are nine thousand five hundred and seventy-nine, and a violation six steps from the start. The catch is size: each extra increment multiplies the states about twenty-fold.
Because the search is breadth-first, the violation it found is a shortest one. The sender sends increment zero; its timer fires before any acknowledgement could arrive, so it sends it again, and a third time. The network delivers all three copies, and the counter, keeping no identifiers, adds three. Nothing was lost or invented: a slow network and a hasty timer are enough. With deduplication, the last two deliveries would change nothing.
A model checker covers one small case; a proof covers them all. Suppose the sender resends each message until it is acknowledged, the receiver acknowledges every copy but applies each identifier at most once, and the network is fair: a message sent infinitely often is eventually delivered. Then every message is applied exactly once. Never twice: an identifier is applied only if it is not yet in the receiver's set, and joins the set in the same step. Never zero: an acknowledgement is sent only after a copy arrived, so an acknowledged message was applied, and an unacknowledged one is resent until fairness delivers it. And with fair acknowledgements, the sender stops. Our bounded model checked the conditional form instead.
Payment APIs make this part of their interface. The client chooses a fresh random key for each operation it intends, and sends it with the request. The server charges the card and stores the key with the result, in one transaction. The response is lost, so the client retries with the same key, and the server returns the stored result instead of charging again. Part 38's two generals showed that a client can never be certain its message arrived: exactly-once delivery is impossible. But exactly-once processing needs only at-least-once delivery and a receiver that remembers, and that we have just proved.
6Designing and versioning APIsIndustry3 min
Part 40 met Hyrum Wright's law: with enough users, every observable behaviour of a system will be depended on by somebody, and an API's users are programs written by strangers. Suppose each consumer, independently, relies on some incidental behaviour with a small probability p. Then somebody does with probability one minus one minus p, to the power N. However small p is, the curve passes one half at about seven tenths over p consumers, then climbs towards certainty. And the behaviours are things nobody promised: the order of fields, an error's wording, a list that happened to be sorted.
So the only safe changes are ones nobody could have observed: additions. A new response field is safe, if every client ignores fields it does not recognise; so is a new optional parameter. Removing a field breaks whoever read it. So does renaming one, or changing its type, here a price in cents becoming a string, or adding a required parameter. Some changes only look additive: a new enumeration value breaks clients that handle every case with no default. These are chapter three's compatibility rules, applied to a whole API.
When a break is unavoidable, it becomes a new version, and the old one is retired slowly. Version two is released beside version one, which keeps working. Then version one is deprecated: its responses announce the date it will stop, in a Sunset header, standardised as RFC 8594 in 2019, so clients can see it coming. Only after that window does it stop answering. The version can travel in the path, visible and easy to route, or in a header, keeping one URL per resource. Either way only the major number belongs there: minor and patch changes are additive.
How can a provider know which changes are safe, when that depends on what consumers actually do? It asks them. In consumer-driven contract testing, with tools such as Pact, each consumer's own tests record the requests it makes and the response fields it reads, and publish them as a contract. The provider's build replays every contract against the new code. Here the provider renames the author's name field. The web client and billing never read it, and pass. The mobile app does, and fails, so the change stops before it ships. The contracts turn Hyrum's law from a surprise into a list.
7Queues and pub/subIndustry4 min
Every call so far has been a conversation: the caller waits while the callee works, and if the callee is down, the call fails. A message queue puts a buffer between them. The producer hands its message to the queue and moves on, even while the consumer is in the middle of a deploy. When the consumer comes back, the messages are waiting, and it works through them at its own pace. Producer and consumer are decoupled in time, and in rate. This is the idea behind Amazon's Simple Queue Service, RabbitMQ, Apache Kafka and Google's Cloud Pub/Sub, and Gregor Hohpe and Bobby Woolf catalogued its patterns in 2003.
A queue must not lose a message when a consumer crashes halfway through it. So receiving a message does not remove it. Worker A receives this order, and the queue hides it for a visibility timeout, here thirty seconds, which is also the default of Amazon's queue. Only when the worker has finished does it delete the message: that is its acknowledgement. But worker A is slow. The timeout expires, the message reappears, and worker B takes it. B finishes and deletes it. Then A, which never crashed, finishes as well. The work has been done twice, and nothing malfunctioned: this is at-least-once delivery, working as designed.
Some messages can never succeed: a malformed order, say, that crashes every worker that touches it. Each failure returns it to the queue, and without a limit it would circle forever, wasting a worker each time. So queues count receives, and after a maximum, here five, move the message to a dead-letter queue for a person to inspect. We ran two thousand messages through a simulated queue, with work of five to twenty seconds, one message in twenty slow, at forty to ninety seconds, and one in five hundred poisoned. Ninety-eight messages were processed more than once, some of them three times, and two were dead-lettered. The lesson is chapter five's: a consumer must be idempotent.
A queue gives each message to one consumer. Workers compete for messages, and the work is shared among them. Publish and subscribe gives each message to everyone who is interested. The orders service publishes an event, order placed, to a topic. Each subscription receives its own copy, in its own queue: email, billing and analytics each read at their own pace, and a slow one does not hold back the others. The publisher does not know who is listening, so a new subscriber can be added without changing it. That is decoupling again, in who as well as when.
What about order? One queue with many workers cannot promise it: two workers race, and a slow one finishes last. Kafka's answer, from LinkedIn in 2011, is a partitioned log. Each message carries a key, a customer, say, and a hash of the key picks one of the partitions, so every message for the same key lands in the same partition, in order. Order holds within a partition and not across them, and order per customer is usually the order that matters. A consumer group divides the partitions among its members, and each consumer commits an offset: how far it has read. After a crash it resumes from its offset. The log can be replayed, which is where Part 46 begins.
8BackpressureGraduate4 min
Put a queue in front of a service, and Part 31's arithmetic takes over. With random arrivals and random service times, an M M 1 queue, the mean time in the system is one over one minus the load, in service times: two at half load, ten at ninety percent, a hundred at ninety-nine. Simulated: two, five point three, eleven point four, twenty-three point seven, and a hundred and seven. Above a load of one there is no steady state: after fifty thousand arrivals the mean is over a thousand service times at one point oh five, and four thousand at one point two.
An unbounded queue never refuses work. It turns overload into waiting. So bound it. With room for twenty requests, an arrival that finds the queue full is turned away at once, with an error that says, try later. Now the mean time in the system stays under sixteen service times, even at a hundred and twenty percent load. The price is explicit: three requests in a thousand shed at a load of point eight, rising to seventeen percent at one point two. That is backpressure. The queue pushes back on whoever is sending, and overload becomes visible to the party that can act on it.
Now add retries. A service answers a hundred requests a second, and its clients send ninety. For ten seconds it is down, and clients retry each failure a second later, on top of new work. When the service returns it is offered nine hundred and ninety requests a second. With only ten a second to spare, the backlog takes ninety seconds to drain: recovery at a hundred and nineteen seconds. Real services also slow down when overloaded, and then a storm can sustain itself, what Bronson and colleagues in 2021 called a metastable failure. Exponential backoff with jitter spreads the retries out: a peak of three hundred and eighty-one, and recovery at sixty-nine seconds. A retry budget does better still.
gRPC's retry throttling gives each client a bucket of tokens. Each failure costs a token, each success earns back a tenth of one, and when the bucket is less than half full, the client stops retrying and reports the failure at once. In our outage the bucket falls below half within the first second: only forty-nine failures are retried. The peak is a hundred and thirty-nine, and the service is back to normal as soon as it returns. The cost: nine hundred requests, every one that arrived during the outage, got an error instead of an answer. Whether that is acceptable is a product decision; the alternative was almost ninety more seconds of overload for everyone.
These are one family of defences. A circuit breaker, described in Michael Nygard's book Release It! in 2007, watches calls to a dependency. When failures pass a threshold it opens, and calls fail at once, unsent. After a cool-down it lets a trial call through: success closes it, failure opens it again. Load shedding refuses work at the door, the cheapest first. Admission control caps the requests in flight, adapting the cap as TCP adapts its window. And deadlines, which chapter nine sends down a call chain, let a service drop work whose caller has already given up. An infinite buffer only turns overload into latency, latency into timeouts, and timeouts into retries.
9Monoliths and microservicesIndustry3 min
Now the architectural question. A monolith is one program, deployed as a unit. Its modules call each other in nanoseconds, share one database, and fail together. Microservices split the modules into separate programs, each with its own data, talking over the network. The gain is mostly organisational. Each team deploys its own service when it is ready, and scales it on its own; Conway's law, from Part 40, says the system will mirror the teams anyway. What is lost is that every call can now fail, be slow, or be repeated, chapter one's lesson, and every piece of data two services share becomes a problem for chapter ten.
So where should the cuts go? Eric Evans' book Domain-Driven Design, in 2003, gave the answer most teams use: bounded contexts. A word like customer means different things to sales, to billing and to shipping, and each context should own its own model rather than share one giant one. Cut well, and each team deploys when it likes. Cut badly, and you get the worst of both: a distributed monolith, services that can only be deployed together because they share a database, or a library version, or a chain of synchronous calls. It has all the network's failures and none of the independence.
Microservices also turn one request into many. Suppose a request fans out to k back ends in parallel and waits for all of them. Each back end is usually fast, ten milliseconds at the median, but one call in a hundred hits a bad moment, a pause or a retransmission. With one back end, under two percent of requests take more than a hundred milliseconds. With a hundred back ends, forty-six percent do, and the median itself has quadrupled. The chance that at least one of k back ends has a bad moment is one minus point nine nine to the k: sixty-three percent at a hundred. At many back ends the measured share is lower, because not every bad moment crosses a hundred milliseconds. It is Part 39's tail at scale: the slowest of many decides.
If a request must be answered within a deadline, the deadline should travel with it. This request has a hundred and fifty milliseconds. The gateway spends five of them and passes the rest, a hundred and forty-five, to auth, which spends eight and passes a hundred and thirty-seven to orders, and so on down the critical path. Payments receives eighty-two milliseconds, uses sixty, and twenty-two are left as slack. gRPC carries the remaining time in every call, so a service that sees its deadline has passed can stop at once, instead of doing work nobody will read. That is chapter eight's lesson, made exact.
10Data across servicesGraduate4 min
Chapter nine left us data that more than one service needs. The rule is that each service owns its database: orders, payments and stock each keep their own tables. No service reads another's tables directly; that would weld them back into one program. Others ask through its interface, or listen to its events. So placing an order is two writes: a row in the orders database, and an event on the broker. Two systems, and no transaction that spans both: the dual-write problem.
Suppose the service simply does the two writes in turn. We simulated ten thousand orders, with a one percent chance of a crash between them. Commit first, then publish: every order is saved, but after a crash no event is sent. A hundred and ten orders were never heard of. Publish first, then commit: a crash leaves an event for an order that was never saved. A hundred and ten phantom orders were announced. Swapping the order only swaps the failure, and retrying cannot help: the process that would retry is the one that crashed.
The cure is to make the two writes one. In the same local transaction as the order, the service inserts the event into an outbox table. Both rows commit, or neither does. A relay publishes unsent rows, then marks them sent. If it crashes in between, it publishes again when it restarts. So an outbox never loses an event or invents one. It can only duplicate, and chapter five's deduplication removes duplicates. Over the same ten thousand orders: nothing lost, no phantoms, a hundred and ten harmless duplicates. Change data capture tools such as Debezium read the database's own write-ahead log instead, as Part 46 will show.
An action that spans services needs more. In 1987 Hector Garcia-Molina and Kenneth Salem proposed the saga: a long transaction written as a sequence of short local ones, each committed at once and paired with a compensation that undoes it. Our order saga reserves stock, charges the card, books a courier and confirms. Here stock is reserved, the card is charged, and then no courier can be booked. So the saga runs backwards: refund the card, then release the stock. A compensation is a semantic undo, a refund rather than an erased charge, and it is retried until it succeeds, so it must be idempotent.
We ran ten thousand orders through the saga, with failures injected at the first three steps. Nine thousand three hundred and fifty-nine completed; six hundred and forty-one were compensated. A hundred and six failed reserving stock, three hundred and seventeen at the charge, and two hundred and eighteen at the courier. Fifty-seven compensations failed and were retried. And the number of orders left half done, money taken with no stock or a courier with no payment, was zero.
Sagas pay for this. Each step commits at once, so there is no isolation: another request can see the order paid, just before the refund. Designs work around it with semantic locks, marking the order pending until the saga ends, and commutative updates that add and subtract rather than overwrite. An orchestrator can drive the steps, or services can react to each other's events: choreography. Why not two-phase commit across services? Part 39 showed that participants hold their locks until the coordinator decides, and a dead coordinator blocks them all.
11Finding, routing and trusting servicesIndustry3 min
Before a client can call a service, it must find one of its servers. Each instance registers as it starts, and the registry keeps checking that it is healthy. A client asks for the current healthy addresses. An instance that stops answering its health checks is dropped, and requests stop going to it. The plainest registry is DNS: a name for the service, an address per instance. But answers are cached, so DNS is slow to forget a dead server.
Which server should take each request? Choosing at random, some queues grow long by bad luck. The power of two choices asks two random servers how busy they are and picks the less loaded. With fifty servers at ninety percent load, random choice gives a mean of ten service times and a ninety-ninth percentile of forty-nine; round robin roughly halves the mean and cuts the tail to twenty-one; two choices brings them to two point six and nine. Part 20's balls into bins explains why: with one random choice the fullest of n bins holds about log n over log log n; with two, about log log n. Azar, Broder, Karlin and Upfal proved it in 1994.
Services must also know who is calling. OAuth 2.0, RFC 6749, lets a user grant an app limited access without sharing a password. The app sends the browser to the authorization server, where the user logs in and consents. The server sends the browser back with a short-lived code, and the app exchanges it for an access token and a refresh token. With PKCE, the app first sent only the hash of a secret, and reveals the secret now, so a stolen code is useless. The access token rides on each call to the resource server, and the refresh token renews it.
Access tokens are often JSON Web Tokens, RFC 7519. Three base64 parts joined by dots: a header naming the algorithm, a payload of claims, here ada with the role reader, and a signature over both. Our first verifier does whatever the header says. Edit the payload to say admin, and the signature fails. But set the algorithm to none, which the standard allows for unsecured tokens, drop the signature, and that verifier accepts a token claiming admin. The fix, in RFC 8725, is for the server to pin the algorithm it expects. Our pinned verifier rejects both forgeries.
12Time in APIsIndustry3 min
A computer has more than one clock, and Part 38 showed that no two machines' clocks agree. The wall clock tells the date and time of day. It is set by NTP, by people, and it can jump, backwards as well as forwards. Time a request with it, and if the clock is stepped back while the request runs, the duration comes out negative. The monotonic clock only ever moves forwards. It means nothing as a date and nothing on another machine, but it is the right clock for timeouts, retries and latency.
Time zones make the wall clock stranger still. In New York on the eighth of March 2026, clocks jump from two in the morning straight to three. The hour between never happens there. Start at half past one and add one hour of wall-clock time, and Python's zoneinfo hands back half past two, a time that does not exist that day. Normalized through UTC, it is half past three, daylight time: exactly one real hour later. Nor are offsets whole hours. Lord Howe Island is ten and a half hours ahead of UTC, and its clocks change by half an hour.
UTC also has extra seconds. The Earth's rotation wanders, and to keep clocks in step with it a leap second is occasionally inserted: the clock reads twenty-three fifty-nine and sixty seconds. Twenty-seven have been added since 1972. Code that assumes every minute has sixty seconds meets one with sixty-one, and the leap second of 2012 hung servers at several large sites. Since 2008 Google has smeared the extra second instead, running its clocks slightly slow for hours, so that no clock ever shows sixty. And in 2022 the General Conference on Weights and Measures decided to stop adding leap seconds by 2035.
Then there are the bits a time is stored in. Unix time counts seconds since 1970. In a signed 32-bit integer, the largest value, two to the thirty-one minus one, is seven seconds past three fourteen in the morning of the nineteenth of January 2038. One second later, the carry ripples all the way into the sign bit, and the clock reads December 1901. Operating systems have moved to 64 bits, but the bug lives on wherever a file format, a database column or a protocol field kept only 32.
Clocks also meet chapter five's idempotency keys. A key is kept for a limited time, here ten minutes, and a request that arrives after it expires is treated as new. If the service that checks the key runs two minutes fast, the key expires early, and a retry at nine minutes is charged a second time. So let one clock decide expiry, keep keys far longer than any client retries, and where order across machines matters, use Part 39's hybrid logical clocks rather than trusting wall clocks to agree.
13The Job as three servicesGraduate3 min
Here is the Job split across a network. The tokenizer reads the first 70,588 words of our thirty novels and sends the counter one message per chunk of two hundred words, each message carrying that chunk's word counts. The counter adds them up, and the ranker asks it for the top words. Our simulated network loses five percent of messages, acknowledgements included, and duplicates two percent. So the tokenizer retries every chunk until it is acknowledged. That took three rounds and, counting retries and acknowledgements, 772 messages. 39 were lost and 22 were duplicated.
Now vary the network. On a perfect network, retries never happen and both versions are exact. As the network gets worse, the counter without protection counts more and more words wrongly: at twenty percent loss and ten percent duplication, 2,890 of the five thousand eight hundred and eighty-two words are wrong, 23,200 counts too many in all. Every error is an over-count. Retrying never loses data; it repeats it. With idempotency keys the counts are exact at every rate. The only price is traffic: the messages grow from 706 to 992 as the network worsens.
What did the fix cost? Each message carries a key that names it: which tokenizer, which chunk. The counter keeps the set of keys it has applied. A message whose key it has seen is skipped, but acknowledged again, because the first acknowledgement may be the one that was lost. Here that is one key per chunk, 353 in all, and the key must be recorded in the same transaction as the counts, or a crash between the two breaks the guarantee. Keys cannot be kept for ever. Either keep each for as long as a retry might still arrive, or give each sender a sequence number and keep only the highest one applied, as TCP does with bytes. This is what industry does: payment APIs accept an idempotency key with every request, and since 2017 Kafka's producers number their messages so that brokers can drop duplicates.
Why not let the network layer handle it? TCP already delivers bytes exactly once and in order. But TCP's guarantee ends at the socket. If the counter adds a chunk and then crashes before acknowledging it, a new connection carries the retry, and TCP has no way to know it is a repeat. This is the end-to-end argument of Jerome Saltzer, David Reed and David Clark, from 1984: a function that needs the application's knowledge can only be completed at the endpoints. Lower layers can make it faster, but never make it correct. So exactly-once is a property of a whole system, not of any one protocol: at-least-once delivery, plus an effect that is idempotent, and recorded together with the effect itself.
14Frontier: services you can proveResearch2 min
Can a system of services be shown to be correct? One line of research treats a protocol between services as a type. Write the whole conversation once, from above: the client sends an order, the order service asks payments to charge, payments answers ok or declined, and the order service confirms or rejects. That global description can be projected onto each participant, giving each service its own local type: what it receives, what it sends, and in what order. A compiler can check each service against its projection, and if every one conforms, the system as a whole cannot deadlock or receive a message it does not expect. These are session types, introduced by Kohei Honda in 1993 and extended to many parties in 2008, and choreographic programming, developed by Fabrizio Montesi and others. The open question is how far they stretch to the failures this part is about: lost messages, retries and crashes.
In chapter five we checked every execution of a small protocol. With one message and one retry there are 47 states; with four messages, 442,169. The space grows exponentially with the system, so a model checker covers small instances completely and large ones not at all. Even so, small instances find real bugs. Amazon's engineers wrote TLA-plus models of DynamoDB, S3 and other services, and found subtle errors that no test had caught. To cover every size, you need proof. In 2015, IronFleet, written in Dafny, and Verdi, written in Coq, proved distributed systems correct, a replicated state machine and a key-value store among them, all the way down to the code that runs.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Protocol Buffers' wire format from first principles, byte for byte against the published examples, and schema evolution as a question about subtypes. Pagination with offsets that repeats rows and pagination with cursors that never does. Exactly-once delivery, checked in every execution of a model, as at-least-once delivery plus deduplication. Retry storms, and the backoff and budgets that end them. Outboxes that turn lost events into duplicates we can remove, and sagas that undo what they cannot finish. And tails that grow with fan-out. One idea runs through it: a remote call can fail in ways a local one cannot, so every message must be safe to lose, and safe to repeat.
Where this comes back. Part 44 measures what a change does to the people who use it, with controlled experiments. Part 45 runs services on rented machines that come and go. Part 46 turns the outbox into a stream, with logs and change data capture. Parts 48 and 49 design whole systems from these blocks. And Part 50 keeps them running, with service-level objectives and error budgets.
In practice. Change APIs only by adding, never reuse a field number, and page with cursors rather than offsets. Put a deadline on every call and pass it down, and retry with backoff, jitter and a budget. Give every write an idempotency key, and publish events through an outbox rather than two separate writes. Build workflows as sagas whose compensations are themselves idempotent, and make sure someone reads the dead-letter queue. Authenticate services to each other with mutual TLS, pin the algorithm your tokens are verified with, and store times in UTC.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: add a courier timeout to our saga, and show that an idempotent compensation keeps every order consistent. The last, marked with a star, is a research problem: proving that a new version of a service keeps every existing client working, even on a network that loses, duplicates and reorders.
Next time, Part 44: people and products. Software is used by people, and both can be measured. Fitts's law falls out of Shannon's channel capacity, Hick's law is the entropy of a choice, and where intuition runs out, industry runs controlled experiments, with statistics that are easy to get wrong.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 44 measures what a change does to the people who use it, with controlled experiments. Part 45 runs services on rented machines that come and go. Part 46 turns the outbox into a stream, with logs and change data capture. Parts 48 and 49 design whole systems from these blocks, and Part 50 keeps them running with service-level objectives and error budgets.
Key results
The part's results in one place, for revision.
Try it
Lab 43 · At most once, at least once, exactly once
Send 4,000 increments to a counter through the series' lossy, duplicating network under the three delivery promises and compare each count with its expected value; explore every execution of two retried increments with and without deduplication; and check the varint's length against one byte per seven bits.
python -m videos.cs.labs 43
needs numpy, scipy, matplotlib · download lab43.py ·
source on GitHubloss 5%, dup 2%: at most once 3,860 of 4,000 (expected 3,876)
loss 5%, dup 2%: at least once 4,294 of 4,000 (expected 4,290)
loss 5%, dup 2%: exactly once 4,000 of 4,000 with the same 8,736 messages
model check, with dedup 4,319 states, the counter never exceeds 2
model check, without 9,579 states; counter 3 after: send 0, send 0, send 0, deliver m0, deliver m0, deliver m0
varint 150 is 96 01; -2 takes 10 bytes as an int, 1 after zigzag
Losing messages makes a counter too low, retrying makes it too high, and remembering which ids were applied makes it exact with the same traffic: exactly-once processing is at-least-once delivery plus deduplication.
The code (94 lines; it asserts its own result)
"""Lab 43: count increments over a network that loses and duplicates messages under three delivery promises, model-check deduplication, and measure varints."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import numpy as np
from explainer.cs.api import delivery as dl
from explainer.cs.api import wire
TITLE = "At most once, at least once, exactly once"
GOAL = ("Send 4,000 increments to a counter through the series' lossy, duplicating network under the three delivery "
"promises and compare each count with its expected value; explore every execution of two retried "
"increments with and without deduplication; and check the varint's length against one byte per seven bits.")
TASKS = [
"Set dup to 0 and compare 'at least once' with 'exactly once' again. Where do the extra counts come from when the network never duplicates?",
"Call dl.model_check(False, n_msgs=1, retries=1, max_dups=0) and read the trace: what is the shortest execution that counts one increment twice?",
"Encode -1 with wire.varint and with wire.varint(wire.zigzag(-1)), then find the largest magnitude that zigzag still fits in two bytes.",
]
def expected(loss, dup):
"""Expected count per increment: at most once, and at least once (retry until an acknowledgement arrives)."""
delivered = (1 - loss) * (1 + dup) # copies of one send that arrive
acked = (1 - loss) * ((1 - dup) * (1 - loss) + dup * (1 - loss ** 2)) # some copy arrives and some ack returns
return delivered, delivered / acked
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
n, dup = 4000, 0.02
# 1. three promises over the same network, at several loss rates
losses = [0.0, 0.05, 0.1, 0.2, 0.3]
got = {p: [] for p in ("at most once", "at least once", "exactly once")}
for k, loss in enumerate(losses):
r = dl.semantics(n=n, loss=loss, dup=dup, seed=seed * 100 + k)["policies"]
for p in got:
got[p].append(r[p]["count"])
most, least = expected(loss, dup)
assert r["exactly once"]["count"] == n, "deduplication makes the count exact at every loss rate"
assert r["exactly once"]["messages"] == r["at least once"]["messages"], "and costs no extra traffic"
assert abs(r["at most once"]["count"] / n - most) < 0.03, "at most once: (1 - loss)(1 + dup) per increment"
assert abs(r["at least once"]["count"] / n - least) < 0.04, "at least once: deliveries per acknowledged send"
if loss > 0:
assert r["at most once"]["count"] < n < r["at least once"]["count"]
if loss == 0.05:
lab.row("loss 5%, dup 2%: at most once", f"{r['at most once']['count']:,} of {n:,} (expected {most * n:,.0f})")
lab.row("loss 5%, dup 2%: at least once", f"{r['at least once']['count']:,} of {n:,} (expected {least * n:,.0f})")
lab.row("loss 5%, dup 2%: exactly once", f"{r['exactly once']['count']:,} of {n:,} with the same "
f"{r['exactly once']['messages']:,} messages")
# 2. every execution of two increments, each sent up to three times
safe, unsafe = dl.model_check(True, 2, 2), dl.model_check(False, 2, 2)
assert not safe["violation"] and unsafe["violation"] and unsafe["counter_at_violation"] > 2
lab.row("model check, with dedup", f"{safe['states']:,} states, the counter never exceeds 2")
lab.row("model check, without", f"{unsafe['states']:,} states; counter {unsafe['counter_at_violation']} after: "
+ ", ".join(unsafe["trace"]))
# 3. the varint: one byte per seven bits, and zigzag for small negatives
assert wire.varint(150) == bytes([0x96, 0x01]), "the encoding guide's example"
bits = np.arange(1, 65)
sizes = []
for b in bits:
v = (1 << int(b - 1)) + int(rng.integers(0, 1 << min(int(b - 1), 62))) # a random value with exactly b bits
enc = wire.varint(v)
assert wire.read_varint(enc) == (v, len(enc)) and len(enc) == -(-int(b) // 7)
sizes.append(len(enc))
for v in [int(x) for x in rng.integers(-10 ** 6, 10 ** 6, 200)] + [-1, 0, 1, -2 ** 63, 2 ** 63 - 1]:
z = wire.zigzag(v)
assert z >= 0 and wire.unzigzag(z) == v and z == (2 * v if v >= 0 else -2 * v - 1)
lab.row("varint", f"150 is 96 01; -2 takes {len(wire.varint(-2))} bytes as an int, "
f"{len(wire.varint(wire.zigzag(-2)))} after zigzag")
lab.note = ("Losing messages makes a counter too low, retrying makes it too high, and remembering which ids were "
"applied makes it exact with the same traffic: exactly-once processing is at-least-once delivery "
"plus deduplication.")
fig, ax = labs.figure(2, size=(11, 4.4))
grid = np.linspace(0, 0.3, 61)
x = [100 * v for v in losses]
ax[0].plot(100 * grid, [expected(v, dup)[1] for v in grid], color=labs.RED, lw=1, ls="--")
ax[0].plot(100 * grid, [expected(v, dup)[0] for v in grid], color=labs.BLUE, lw=1, ls="--", label="expected (dashed)")
ax[0].plot(x, np.array(got["at least once"]) / n, "o", color=labs.RED, label="at least once")
ax[0].plot(x, np.array(got["exactly once"]) / n, "o", color=labs.GREEN, label="exactly once (with dedup)")
ax[0].plot(x, np.array(got["at most once"]) / n, "o", color=labs.BLUE, label="at most once")
ax[0].set(title="Counter after 4,000 increments, as a share of the truth", xlabel="messages lost (%), 2% duplicated",
ylabel="count / increments sent")
ax[0].legend(loc="upper left")
ax[1].step(bits, sizes, where="mid", color=labs.GOLD, label="bytes of wire.varint")
ax[1].plot(bits, bits / 7, color=labs.MUTED, ls="--", label="bits / 7")
ax[1].set(title="A varint spends one byte per seven bits", xlabel="bits in the value", ylabel="bytes on the wire")
ax[1].legend(loc="upper left")
lab.fig = fig
return lab
Now change it
- Set dup to 0 and compare 'at least once' with 'exactly once' again. Where do the extra counts come from when the network never duplicates?
- Call dl.model_check(False, n_msgs=1, retries=1, max_dups=0) and read the trace: what is the shortest execution that counts one increment twice?
- Encode -1 with wire.varint and with wire.varint(wire.zigzag(-1)), then find the largest magnitude that zigzag still fits in two bytes.
Problems, with solutions
Try each problem before opening its solution.
-
Varints by hand. Encode the message
{a: 300, b: -3, c: [1, 2]}by hand (aan int32,ban sint32,cpacked), and decode it back.Solution
Number the fields 1, 2 and 3, as in the encoding guide. a: 300 = 1 0010 1100₂; the low seven bits are 010 1100 = 0x2C, sent first with the continuation bit set (0xAC), then the remaining bits, 10₂ = 0x02. The tag is 1 << 3 | 0 = 0x08, so a is
08 AC 02. b: zigzag maps −3 to (−3 << 1) ^ (−3 >> 31) = 5, a one-byte varint; the tag is 2 << 3 | 0 = 0x10, so b is10 05. c: a packed field is length-delimited, tag 3 << 3 | 2 = 0x1A, then the length of the payload, 2, then the varints 1 and 2:1A 02 01 02. The message is08 AC 02 10 05 1A 02 01 02, nine bytes (the compact JSON{"a":300,"b":-3,"c":[1,2]}is 26). Decoding:08is key 8, field 8 >> 3 = 1, wire type 8 & 7 = 0, a varint;AC 02gives 0x2C + (0x02 << 7) = 44 + 256 = 300.10is field 2, wire type 0;05unzigzags to (5 >> 1) ^ −(5 & 1) = 2 ^ −1 = −3.1Ais field 3, wire type 2; the length02covers01 02, the varints 1 and 2. Had b been an int32, −3 would have gone as its 64-bit two's complement, ten bytes (FD FF FF FF FF FF FF FF FF 01), and the message would be 18 bytes. Ourwire.encodeandwire.decodegive exactly these bytes and fields. -
Compatibility as subtyping. Show that adding an optional field is backward and forward compatible, and that changing a field's type is neither, by treating messages as records and compatibility as subtyping.
Solution
Treat a schema as a record type: a finite map from field numbers to a type and a flag, required or optional. A reader with schema R can read data written with schema W when W <: R in the following sense: for every field n of R, if n is in W then W's type for n is a subtype of R's (depth), and if n is required in R then n is in W and required there; fields of W that R lacks are skipped (width). Backward compatibility of a change v1 → v2 is v1 <: v2 (new code reads old data); forward compatibility is v2 <: v1 (old code reads new data). Let v1 = {1: word string required, 2: count int64 optional} and v2 = v1 + {3: novel string optional}. Forward: every field of v1 is in v2 with the same type and flag, and field 3 is extra, so v2 <: v1 by width subtyping; the old reader skips field 3 (protobuf keeps its bytes). Backward: v1 lacks field 3, but field 3 is optional in v2, so the condition holds and the new reader gives
novelits default; v1 <: v2. Now let v2 change field 2 to a string. The fields share a number, so depth subtyping needs int64 <: string or string <: int64, and neither holds: there is no value of one type that is a value of the other. Both directions fail, which is what our checker reports ("int64 written, read as string; and the reverse"). On the wire the tag itself changes, from10(wire type 0) to12(wire type 2), so a reader cannot interpret the bytes as its type at all: depending on the implementation the value is dropped or decoding fails. (Our checker treats int32, int64, uint32, uint64 and bool as one varint family, which is why widening int32 to int64 passes; the narrow reader then truncates values that no longer fit.) -
Exactly once. Prove that retrying until acknowledged, with a receiver that applies each id at most once, delivers every message exactly once if the network eventually delivers some copy.
Solution
The sender has messages with distinct ids 1, …, n and resends each id until it receives an acknowledgement for it. The receiver keeps a set A of applied ids and a counter c; on receiving a copy of i it applies i and adds i to A in one atomic step if i ∉ A, and in either case sends an acknowledgement of i. Fairness: a message sent infinitely often (in either direction) is eventually delivered. At most once. Initially c = 0 and A = ∅. Every step that increments c also adds a new element to A, and no step does one without the other, so c = |A| always; an id joins A only if it was absent, so each id is applied at most once, and A ⊆ {1, …, n} gives c ≤ n in every state, whatever the network does. At least once. Suppose some i is never applied. Then no copy of i ever arrives (an arriving copy either applies i or finds it in A). Acknowledgements of i are sent only when a copy arrives, so none is ever sent, the sender never hears one, and it sends i infinitely often; by fairness a copy is delivered, a contradiction. So every id is eventually in A and c = n. Termination. Once i is applied, every further copy of i that arrives is acknowledged; if the sender went on resending i for ever, infinitely many copies would arrive (fairness), infinitely many acknowledgements would be sent, and fairness again delivers one, after which the sender stops. Duplication and reordering change nothing in the argument, since it never counts copies. The atomicity matters: if a crash could fall between applying i and recording it, a later copy would be applied again. Chapter 5's model checker, whose resends are bounded and so cannot assume fairness, checked the conditional form (if both increments were acknowledged the counter is 2, and it never exceeds 2) in all 4,319 states; without deduplication it found a violation in six steps, with the counter at 3.
-
Offsets and cursors. Show that offset pagination over a list receiving k inserts per page repeats about k rows per page, and that cursor pagination repeats none.
Solution
The list is sorted newest first, pages hold p rows, and k ≤ p new rows arrive at the top after each page is read. Offset. Page j (from 0) asks for positions jp to jp + p − 1. By then jk rows have been inserted above the original ones, so an original row at position r now sits at r + jk, and page j shows the original rows jp − jk to jp − jk + p − 1 (no new row appears, since jp ≥ jk). Page j − 1 showed the original rows (j − 1)(p − k) to (j − 1)(p − k) + p − 1. The overlap runs from j(p − k) to (j − 1)(p − k) + p − 1, which is exactly k rows: each page after the first repeats the last k rows of the one before, and the reader advances only p − k original rows per page. To cover n rows it needs P = ⌈n/(p − k)⌉ pages and sees k(P − 1) repeats. For n = 1,000 and p = 50 this gives P = 21, 22, 25 and 20, 63, 240 repeats for k = 1, 3, 10, exactly the simulated figures. No row is missed under inserts; under deletions the shift goes the other way and rows are skipped. The cost is quadratic, since the database steps past every skipped row: with no inserts, Σ (50j + 50) over j = 0, …, 19 = 10,500 rows scanned, about n²/2p. Cursor. Page j asks for the p newest rows with id below the last id of page j − 1. Every new row has a larger id than every existing one, so it never satisfies the condition; the last id seen strictly decreases from page to page, so the pages are disjoint and together are the original list in order: no repeats, no misses, and with an index on id, p rows read per page (1,000 in all). A cursor needs a unique, totally ordered key; if the sort key can tie, the id breaks the tie.
-
Build. Add a saga to our simulator in which the courier step can time out, and show that an idempotent compensation keeps the invariant.
Solution
Solution sketch. A timeout is the third outcome of chapter 1's partial failure: the booking may or may not have happened, or may still happen when a delayed request arrives. Extend
services.saga_runwith atimeout_atstep and a hidden coin for whether the courier service actually booked; on a timeout the saga must treat the step as possibly done and compensate it too, in reverse order: cancel courier, refund card, release stock. Give the courier service a table keyed by the order's idempotency key:book(key)records a booking unless the key is already marked cancelled, andcancel(key)marks it cancelled whether or not a booking exists, so that cancel is idempotent, harmless when nothing was booked, and wins over a booking request that arrives after it (deliver the delayed request withdelivery.Netto test that case). Compensations are retried until they succeed, as insaga_experiment(comp_fail), so each must be idempotent: a refund keyed by the order, not one refund per attempt. Check the invariant on every order at the end of the run, against the services' own state rather than the saga's log: either stock reserved, card charged, courier booked and confirmation sent, or none of them in effect. A complete answer runs it twice over many orders with a timeout probability of a few percent: with the idempotent compensations no order is left inconsistent; with a non-idempotent refund every retried refund pays out twice, and with a cancel that does not record a tombstone a late booking leaves a courier booked for a refunded order, and the checker counts both. -
★ Research. A compatibility checker proving that every existing client completes every protocol run against a new version, under loss, duplication and reordering.
Discussion. Open. Chapter 3's checker compares message types, but compatibility that matters is behavioural: a new version can keep every type and still change the order of messages, add a state, or turn a call that was safe to retry into one that is not. Behavioural compatibility is a subtyping question about protocols, and even session-type subtyping over asynchronous (unboundedly buffered) channels is known to be undecidable in general (Bravetti, Carbone and Zavattaro; Lange and Yoshida, 2017); loss, duplication and reordering only enlarge the set of runs, and the "existing clients" are programs written by strangers, known only through their traffic or their contracts (Hyrum's law). A good partial answer would fix a model (finite-state clients, for instance extracted from consumer-driven contracts; services as session types), reduce lossy and duplicating channels to reliable reordering ones for protocols whose effects are deduplicated (chapter 5's theorem, made a lemma), and give a checker that is sound and decidable on a stated fragment, such as bounded buffers or protocols without loops, with a proof that it accepts the safe changes of chapters 3 and 6 and rejects the renumbering trap and a new enumeration value a client cannot handle. A cutoff result (a bound on buffer size or on the number of retries beyond which nothing new happens), or an evaluation on the history of a real public API, would also be new.
Notes and sources
Glossary
- fallacies of distributed computing — eight false assumptions about networks (reliable, zero latency, infinite bandwidth, secure, fixed topology, one administrator, free transport, homogeneous).
- remote procedure call (RPC), stub, marshalling, interface description language (IDL) — a call to a procedure on another machine made to look local; the generated local stand-ins; turning arguments into bytes; the language in which an interface is written once.
- partial failure, timeout — one part of a system failing while the rest runs; the only signal a caller gets.
- varint, zigzag encoding, tag, wire type, length-delimited, packed field — Protocol Buffers' integers, seven bits per byte; interleaving signs so small negatives stay short; a field number and wire type in one varint; a length followed by bytes; a repeated scalar sent as one length-delimited field.
- schema evolution, backward and forward compatibility, width subtyping, reserved field — changing a format while old and new code coexist; new code reading old data and old code reading new; a record with more fields standing for one with fewer; a retired field number that may never be reused.
- writer's and reader's schema, schema resolution, schema registry — Avro's pair of schemas matched by name.
- zero-copy format — bytes on the wire laid out as the program uses them, read in place through offsets.
- REST, resource, representation, uniform interface, statelessness — Fielding's architectural style for the web.
- safe and idempotent methods — HTTP methods that request no change; those whose repetition has the effect of one.
- offset and cursor (keyset) pagination — skipping k rows; asking for the rows after the last one seen.
- gRPC, unary and streaming calls, deadline, status — typed procedure calls over HTTP/2.
- GraphQL, resolver, N + 1 problem, batching (DataLoader), persisted query — a client-shaped query language; the per-field functions that fill a response; one query per parent; collecting keys into one query; a query registered in advance by its hash.
- at-most-once, at-least-once and exactly-once semantics, deduplication, idempotency key — how often a message takes effect; remembering ids already applied; a client-chosen id for one intended operation.
- model checking, fairness — exploring every reachable state of a model; the assumption that what is sent often enough is eventually delivered.
- Hyrum's law, additive change, deprecation, Sunset header, consumer-driven contract test — every observable behaviour has dependants; changes nobody could have observed; announcing retirement; a dated end of service; tests in which consumers state what they rely on.
- robustness principle — Postel's "be liberal in what you accept", and its critique in RFC 9413.
- message queue, visibility timeout, dead-letter queue, poison message — a buffer between services; how long a received message stays hidden; where messages that keep failing are set aside; a message that always fails.
- publish/subscribe, topic, subscription, partition, consumer group, offset — delivery to every subscriber; Kafka's ordered log per key and the position each consumer has read to.
- backpressure, load shedding, admission control, bounded queue — pushing overload back to the sender.
- retry storm, exponential backoff, jitter, retry budget, metastable failure — retries that amplify an outage; waits that double; randomised waits; a cap on retries; an overload that sustains itself.
- circuit breaker (closed, open, half-open) — failing fast on calls to a sick dependency.
- monolith, microservice, bounded context, distributed monolith — one deployable program; many; a part of the business with its own model; services that must still deploy together.
- fan-out, tail latency, latency budget, deadline propagation — one request becoming many; the slowest of them; dividing a deadline down a call chain.
- dual-write problem, transactional outbox, change data capture (CDC) — two writes with no transaction spanning them; an event row committed with the data; publishing a database's own log of changes.
- saga, compensation, orchestration, choreography, semantic lock — a long transaction as local steps with undos; a semantic undo; a coordinator or services reacting to events; marking data as pending.
- service discovery, health check, power of two choices — finding healthy instances; sending each request to the less loaded of two random servers.
- sidecar, service mesh, control plane, mutual TLS, workload identity (SPIFFE) — a proxy beside each service; the proxies together; their configuration; TLS with certificates on both sides; a name for a service in its certificate.
- OAuth 2.0, authorization code, PKCE, access token, refresh token — delegated access without sharing a password.
- JSON Web Token (JWT), claims,
alg: none, algorithm pinning — a signed token of claims; an unsecured token the standard allows; a verifier that chooses the algorithm itself. - capability, bearer token, macaroon, caveat — a token whose possession is the permission; one any holder can weaken by chaining HMACs over conditions.
- wall clock, monotonic clock, time zone, UTC offset, daylight saving gap, leap second, smear, Year 2038 problem — the date and time of day; a clock that only moves forwards; named rules for local time; a time that never occurs; an extra second in UTC and spreading it out; the overflow of a signed 32-bit Unix time.
- end-to-end argument — a function that needs the application's knowledge can only be completed at the endpoints.
- session type, choreography, projection — a protocol as a type; a global description of a conversation; each participant's local part of it.
Sources
- M. Kleppmann, Designing Data-Intensive Applications (2017), ch. 4, 11–12; S. Newman, Building Microservices (2nd edn, 2021); C. Richardson, Microservices Patterns (2018); E. Evans, Domain-Driven Design (2003); G. Hohpe and B. Woolf, Enterprise Integration Patterns (2003); M. Nygard, Release It! (2007); T. Winters, T. Manshreck and H. Wright, Software Engineering at Google (2020).
- A. Birrell and B. Nelson, "Implementing remote procedure calls", ACM Transactions on Computer Systems 1984; J. Waldo, G. Wyant, A. Wollrath and S. Kendall, "A note on distributed computing", Sun Microsystems Laboratories technical report SMLI TR-94-29, 1994; J. Saltzer, D. Reed and D. Clark, "End-to-end arguments in system design", ACM Transactions on Computer Systems 1984; J. Gray, "Notes on data base operating systems", in Operating Systems: An Advanced Course (1978).
- R. Fielding, Architectural Styles and the Design of Network-based Software Architectures, doctoral dissertation, University of California, Irvine, 2000; RFC 9110, HTTP Semantics (2022); RFC 5789, PATCH Method for HTTP (2010); RFC 8259, The JavaScript Object Notation (JSON) Data Interchange Format (2017); RFC 3339, Date and Time on the Internet: Timestamps (2002); RFC 8594, The Sunset HTTP Header Field (2019); RFC 793, Transmission Control Protocol (1981); RFC 9413, M. Thomson and D. Schinazi, Maintaining Robust Protocols (2023).
- Protocol Buffers, "Encoding" (protobuf.dev/programming-guides/encoding); the Apache Avro specification; Google, API Design Guide (cloud.google.com/apis/design).
- H. Garcia-Molina and K. Salem, "Sagas", SIGMOD 1987.
- J. Kreps, N. Narkhede and J. Rao, "Kafka: a distributed messaging system for log processing", NetDB 2011; N. Bronson, A. Aghayev, A. Charapko and T. Zhu, "Metastable failures in distributed systems", HotOS 2021.
- Y. Azar, A. Broder, A. Karlin and E. Upfal, "Balanced allocations", STOC 1994.
- RFC 6749, The OAuth 2.0 Authorization Framework (2012); RFC 7636, Proof Key for Code Exchange (2015); RFC 7519, JSON Web Token (2015); RFC 8725, JSON Web Token Best Current Practices (2020); A. Birgisson, J. Politz, Ú. Erlingsson, A. Taly, M. Vrable and M. Lentczner, "Macaroons: cookies with contextual caveats for decentralized authorization in the cloud", NDSS 2014.
- K. Honda, "Types for dyadic interaction", CONCUR 1993; K. Honda, N. Yoshida and M. Carbone, "Multiparty asynchronous session types", POPL 2008.
- C. Newcombe, T. Rath, F. Zhang, B. Munteanu, M. Brooker and M. Deardeuff, "How Amazon Web Services uses formal methods", Communications of the ACM 2015; C. Hawblitzel et al., "IronFleet: proving practical distributed systems correct", SOSP 2015; J. Wilcox et al., "Verdi: a framework for implementing and formally verifying distributed systems", PLDI 2015.
About this partfrom its README
Part 43 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fourth part of Act VIII, Building Software. Once a program is split across machines, every function call becomes a message that can be lost, duplicated, delayed or reordered, and a remote call can never be made to look exactly like a local one. Industry's answers have real mathematics underneath: schema evolution as subtyping, idempotency, exactly-once as at-least-once plus deduplication, sagas in place of distributed locks, and backpressure. We split the Job into three services and keep its counts exact while the network loses and duplicates messages.
The instruments are in explainer/cs/api/ (tested in tests/test_cs43_api.py):
wire.py: Protocol Buffers' wire format from first principles (varints, zigzag, tags and wire types, length-delimited and packed fields), an encoder and a schemaless decoder, checked byte for byte against the examples in the published encoding guide; JSON's integers read as IEEE doubles; one record as JSON and as protobuf; a schema-compatibility checker (fields matched by number, required and optional, the varint family) run on seven schema changes.delivery.py: a network that loses, duplicates and delays messages; at-most-once, at-least-once and exactly-once increments of a counter; a breadth-first model checker that explores every execution of retry-until-acknowledged, with and without deduplication; the Job as three services (tokenize, count, rank), with and without idempotency keys; offset against cursor pagination under concurrent inserts; a retry storm under immediate retries, exponential backoff with jitter, and a gRPC-style retry budget.services.py: the dual-write problem against a transactional outbox; an order saga with compensations under injected failures; fan-out latency over a call graph and a deadline propagated down a call chain; an M/M/1 queue, unbounded and bounded; GraphQL's N + 1 queries and batching; visibility timeouts and dead-letter queues; a JWT verifier that trusts the header and one that pins the algorithm; clock pitfalls computed withzoneinfo; client-side load balancing (random, round robin, two choices, least loaded).
Chapter notes
- Hook. The eight fallacies of distributed computing (Deutsch's seven of 1994, building on Joy and Lyon's, and Gosling's eighth), and three outages matched to them: GitHub's 43-second partition in October 2018 (the network is not reliable), Mirai against Dyn in October 2016 (not secure), Facebook's withdrawn backbone routes in October 2021 (topology changes). The Job in three services: 353 messages of counts over a network that loses 5% and duplicates 2%; with retries and no keys the is counted 2,924 times instead of 2,733 and 1,403 of 5,882 words are wrong (5,400 counts too many); with idempotency keys, none.
- 1. Calls across a network. Birrell and Nelson's stubs (Xerox PARC, 1984; generated by Lupine): marshal, send, unmarshal, dispatch. Waldo et al.'s four reasons remote is not local (1994): latency (a local call takes nanoseconds; in our model a remote one takes 10 ms at the median and 30 ms at the 99th percentile, 10⁶ to 10⁷ times longer); no shared memory (one object passed twice arrives as two copies); concurrency; and partial failure (request lost, server crashed after the work, reply lost: the same silence). The two generals again (Part 38): an RPC system runs a call at most once or at least once. Interface description languages and stub generators, from Sun RPC (1988) through CORBA and Thrift to gRPC (2015), whose calls take a deadline and return a status.
- 2. Bytes on the wire. JSON's numbers as doubles: every integer up to 2⁵³ is exact, beyond it only every second
one, so 2⁵³ + 1 arrives as 2⁵³ and the id 1234567890123456789 is read as 1234567890123456768 (doubles there are 256
apart); RFC 8259's warning. Varints derived on 150 (
96 01): one byte up to 127, one more for every seven bits, ten for 2⁶³. Tags asfield << 3 | wire type;{a: 150}is08 96 01, the string testing is12 07and seven bytes; our encoder reproduces all eight of the guide's examples. Zigzag: −2 takes ten bytes as an int32 and one (03) as an sint32; −1000 takes two rather than ten; the guide's table matched at the extremes. One record: 90 bytes of JSON against 34 of protobuf, and the bytes mean nothing without the schema. - 3. Schemas that evolve. Rolling deploys and old data: backward compatibility (new code reads old data) and
forward compatibility (old code reads new data). Compatibility as width subtyping (Part 14). Seven changes checked:
adding or removing an optional field is safe both ways; adding a required field breaks backward compatibility,
removing one breaks forward compatibility; changing a type breaks both; widening int32 to int64 passes (an old
reader truncates large values); renumbering passes both ways, and is a trap: a count of 1226 written as field 2
(
10 ca 09) and read as field 5 becomes 0, with nothing failing;reservednumbers and names; proto3 has no required fields. Avro (2009) resolves the writer's and reader's schemas by name, with defaults, so its dangerous change is a rename. Zero-copy formats (Cap'n Proto, FlatBuffers): an offset table, one jump, read in place. - 4. API styles. REST (Fielding 2000): resources, representations, a uniform interface, statelessness. RFC 9110's safe and idempotent methods (PATCH need not be idempotent); a PUT sent twice leaves the cart as intended, a POST sent twice places a second order. Offsets against cursors on 1,000 rows in pages of 50: with 0, 1, 3 and 10 new rows per page, offsets repeat 0, 20, 63 and 240 rows and scan 10,500, 11,520, 12,613 and 16,240; cursors repeat none and scan 1,000. gRPC (2015, from Stubby): unary, server-streaming, client-streaming and bidirectional calls over HTTP/2. GraphQL (2015): 50 authors and their books cost 51 queries naively (251 with each book's reviews) and 2 (3) with DataLoader-style batching; persisted queries and cost limits.
- 5. At most, at least, exactly once. Three promises. 10,000 increments over a network that loses 5% of messages, acknowledgements included, and duplicates 2%: at most once counts 9,694 (306 lost), at least once 10,754 (754 extra), exactly once 10,000; the last two send the same 21,841 messages in four rounds of retries, so deduplication costs no traffic. A model checker visits every state of two increments, each sent up to three times: 4,319 states with deduplication, in none of which the counter exceeds 2; 9,579 without, with a shortest violation six steps from the start (send three times, deliver three times: counter 3). One resend each, 1 to 4 increments: 47, 1,053, 21,963 and 442,169 states (×22, ×21, ×20). The theorem, proved under fairness. Idempotency keys in payment APIs: exactly-once delivery is impossible, exactly-once processing is not.
- 6. Designing and versioning APIs. Hyrum's law as a model: if each of N consumers relies on an incidental
behaviour with probability p, somebody does with probability 1 − (1 − p)^N, passing one half at N ≈ 0.69/p (69, 693
and 6,931 consumers for p = 0.01, 0.001, 0.0001). Changes that break and changes that don't (a new enumeration value
only looks additive). Versions, deprecation and the Sunset header (RFC 8594, 2019); versions in the path or in a
header, major numbers only. Google's resource-oriented design: five standard methods per collection and custom
methods after a colon. Consumer-driven contract tests (Pact): renaming
author.namefails the mobile app's contract. Postel's robustness principle (RFC 793, 1981) against RFC 9413 (2023). - 7. Queues and pub/sub. A queue decouples producer and consumer in time and in rate (SQS, RabbitMQ, Kafka, Cloud Pub/Sub; Hohpe and Woolf, 2003). Receive, hide, delete: a 30-second visibility timeout outlived by a slow worker, so the work is done twice. Poison messages go to a dead-letter queue after five receives; of 2,000 simulated messages, 98 were processed more than once (153 extra receives, 2,161 in all) and 2 were dead-lettered. Publish and subscribe; Kafka's partitioned log (2011): order per key, consumer groups and committed offsets.
- 8. Backpressure. An M/M/1 queue in front of a service: mean time in system 2.0, 5.3, 11.4, 23.7 and 107 service times at loads 0.5 to 0.99, against 1/(1 − ρ) = 2, 5, 10, 20, 100; above load 1 no steady state (1,451 and 4,401 after 50,000 arrivals at 1.05 and 1.2). Bounded at 20, the mean stays under 16 at every load, at the price of shedding 0.3% of requests at load 0.8 and 17.2% at 1.2. A retry storm (capacity 100/s, demand 90/s, down from 20 to 30 s): immediate retries peak at 990/s and recover at 119 s; backoff with jitter peaks at 381/s and recovers at 69 s; a retry budget (gRPC's throttling) retries only 49 failures, peaks at 139/s and recovers at 31 s, but gives up on 900 requests. Metastable failures (Bronson et al., 2021); circuit breakers (Nygard, 2007), load shedding, admission control and deadlines.
- 9. Monoliths and microservices. What a split gains (teams that deploy and scale on their own; Conway's law, Part 40) and costs. Bounded contexts (Evans, 2003) and the distributed monolith. Fan-out to k back ends, 20,000 simulated requests each: for k = 1, 5, 20, 100 the median is 21, 26, 31 and 85 ms, the 99th percentile 150, 198, 213 and 226 ms, and 1.7%, 4.4%, 12.1% and 46.4% of requests take over 100 ms, against 1 − 0.99^k = 1.0%, 4.9%, 18.2% and 63.4% (one back end alone: median 10 ms, 99th percentile 30 ms). A 150 ms deadline down a call chain: gateway 5 ms, auth 8 (with 145 left), orders 25 (137), inventory 30 (112), payments 60 (82), and 22 ms of slack.
- 10. Data across services. A database per service and the dual-write problem: 10,000 orders with a 1% crash between the writes; commit then publish loses 110 events, publish then commit commits 9,890 and announces 110 phantom orders; the transactional outbox loses none and invents none, at the price of 110 harmless duplicates; change data capture (Debezium, Part 46). Sagas (Garcia-Molina and Salem, 1987): reserve stock, charge card, book courier, send confirmation, with compensations run in reverse; one order fails at the courier and is refunded and released. 10,000 sagas: 9,359 completed, 641 compensated (106 at the stock step, 317 at the charge, 218 at the courier), 57 compensations retried, 0 orders left half done. No isolation (semantic locks, commutative updates); orchestration and choreography; why not two-phase commit (Part 39).
- 11. Finding, routing and trusting services. Registries, health checks and DNS. The power of two choices, with
50 servers at 90% load (time in system in service times, mean and 99th percentile): random 10.1 and 48.8, round
robin 4.8 and 21.0, two choices 2.6 and 9.1, least loaded 1.2 and 5.2; ln n/ln ln n against ln ln n/ln 2 (Azar,
Broder, Karlin and Upfal, 1994). Sidecars and the service mesh (Envoy, Istio, Linkerd), mutual TLS (Part 30) and
SPIFFE identities. OAuth 2.0's authorization-code flow with PKCE. JWTs: our naive verifier rejects an edited payload
but accepts an
alg: nonetoken claiming admin; the verifier that pins HS256 (RFC 8725) rejects both forgeries. Macaroons (Birgisson et al., 2014): caveats chained by HMAC, so a holder can only weaken a token (Part 55). - 12. Time in APIs. Wall clock against monotonic clock (an illustrative −0.7 s duration). New York on 8 March 2026: 01:30 EST plus one wall-clock hour is 02:30, which does not exist; normalised through UTC it is 03:30 EDT, one real hour later. Lord Howe Island is UTC+10:30, with a half-hour shift. 27 leap seconds since 1972, the 2012 leap second, Google's smear, and the 2022 decision to stop by 2035. 2³¹ − 1 = 2,147,483,647 seconds is 2038-01-19T03:14:07Z, and one second later a signed 32-bit clock reads 1901-12-13T20:45:52Z. Five rules for time in an API; an idempotency key expiring early on a clock two minutes fast (illustrative).
- 13. The Job as three services. The first 70,588 words of the novels in 353 chunks of 200 words: 772 messages, 39 lost, 22 duplicated, three rounds of retries. As loss and duplication rise from 0%/0% to 20%/10%, the counter without keys gets 0, 504, 1,403, 1,880 and 2,890 of the 5,882 words wrong (0, 1,200, 5,400, 9,600 and 23,200 counts too many: every error is an over-count); with keys, none, and only the traffic grows (706 to 992 messages). What the counter remembers: 353 keys, recorded atomically with the counts; time-to-live or sequence numbers; Kafka's idempotent producers. The end-to-end argument (Saltzer, Reed and Clark, 1984): TCP's guarantee ends at the socket.
- 14. Frontier: services you can prove. Protocols as types: a global choreography projected onto each service (session types, Honda 1993; multiparty, Honda, Yoshida and Carbone 2008; choreographic programming, Montesi). Checking every execution: 47 states for one message, 442,169 for four; TLA⁺ at Amazon (Newcombe et al., 2015); IronFleet (Dafny) and Verdi (Coq), 2015. Testing the whole system: FoundationDB's deterministic simulation, Jepsen, chaos engineering. Four open problems and the ★ research problem.
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
We split the Job into services and keep its counts exact while the network loses and duplicates messages.
- Hook: the eight fallacies of distributed computing, each matched to a real outage.
- RPC (Birrell & Nelson 1984): stubs and marshalling; why remote is not local (Waldo et al. 1994).
- Serialization:
- JSON's numbers (doubles, 2⁵³, callback to Part 4);
- Protocol Buffers' wire format: varints and zigzag, derived; field tags;
- schema evolution: forward and backward compatibility as a subtyping question (callback to Part 14);
- Avro; zero-copy formats.
- API styles:
- REST (Fielding 2000) and the safety and idempotency of HTTP methods;
- offset against cursor pagination (why offsets are O(n) and skip rows under inserts, computed);
- gRPC and streaming;
- GraphQL, the N + 1 problem and batching.
- Idempotency and delivery semantics: at-most, at-least and exactly once; exactly-once = at-least-once + dedup (proved in a model); idempotency keys; the two generals again.
- API design and versioning: Hyrum's law; deprecation; additive changes; consumer-driven contract tests.
- Queues and pub/sub: acknowledgements, visibility timeouts, dead-letter queues, per-key ordering.
- Backpressure: bounded queues and load shedding; queueing between services (callback to Part 31).
- Monolith against microservices: team autonomy against distributed complexity; bounded contexts (DDD); the distributed monolith; latency budgets across a call graph (callback to Part 39's tail).
- Data across services:
- the dual-write problem;
- the transactional outbox and change data capture (Part 46);
- sagas (Garcia-Molina & Salem 1987) with compensations, animated on an order–payment–shipping flow.
- Discovery and routing: client-side load balancing, sidecars and service meshes, mTLS (callback to Part 30).
- Authentication and authorization between services: OAuth 2.0 flows; JWTs and the
alg: nonepitfall; capability tokens and macaroons (Part 55). - Time in APIs: wall against monotonic clocks, time zones, leap seconds (callback to Part 38).
- The Job as three services (tokenize, count, rank) on our network with loss and duplication. Its counts stay exact with idempotency keys and drift without them (computed). Outro.
Computed: varint and zigzag encoders checked against the published encoding examples; a schema-compatibility checker; pagination anomalies under concurrent inserts; double-count rates with and without idempotency keys; sagas under injected failures; latency budgets composed over a call graph. Visuals: varint bytes with their continuation bits; a retry storm against idempotent dedup; a saga's forward steps and compensations; a call graph with latencies accumulating along the critical path. In practice: REST, gRPC and GraphQL APIs; Kafka, RabbitMQ and SQS; payment-grade idempotency; service meshes; OAuth; backend engineering at any company. Reading: Kleppmann, Designing Data-Intensive Applications ch. 4, 11–12; Newman, Building Microservices; Richardson, Microservices Patterns; Evans, Domain-Driven Design; Hohpe & Woolf, Enterprise Integration Patterns; Fielding 2000; Birrell & Nelson 1984; Waldo et al. 1994; Garcia-Molina & Salem 1987; the Protocol Buffers encoding documentation; RFC 6749 and RFC 7519; Google's API design guide.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
手算变长整数。 手工编码消息
{a: 300, b: -3, c: [1, 2]}(a为 int32,b为 sint32,c为打包字段),再把它解码回来。解答
按编码指南的惯例,三个字段编号为 1、2、3。a:300 = 1 0010 1100₂;低七位 010 1100 = 0x2C 先发送,并置上延续位 (0xAC),然后是余下的位 10₂ = 0x02。标签为 1 << 3 | 0 = 0x08,所以 a 是
08 AC 02。b:之字形编码(zigzag)把 −3 映射为 (−3 << 1) ^ (−3 >> 31) = 5,是一个字节的变长整数;标签为 2 << 3 | 0 = 0x10,所以 b 是10 05。c:打包字段带长度前缀,标签 3 << 3 | 2 = 0x1A,然后是载荷长度 2,再是变长整数 1 和 2:1A 02 01 02。整条消息是08 AC 02 10 05 1A 02 01 02,共九个字节(紧凑的 JSON{"a":300,"b":-3,"c":[1,2]}是 26 个字节)。解码:08是键 8,字段 8 >> 3 = 1,线路类型 8 & 7 = 0,即变长整数;AC 02得 0x2C + (0x02 << 7) = 44 + 256 = 300。10是字段 2、线路类型 0;05反向之字形解码为 (5 >> 1) ^ −(5 & 1) = 2 ^ −1 = −3。1A是字段 3、线路类型 2;长度02覆盖01 02,即变长整数 1 和 2。如果 b 是 int32,−3 就要按 64 位补码发送,占十个字节 (FD FF FF FF FF FF FF FF FF 01),整条消息变成 18 个字节。我们的wire.encode和wire.decode给出的正是这些字节和字段。 -
兼容性即子类型。 把消息看作记录、把兼容性看作子类型关系,证明增加一个可选字段既向后兼容又向前兼容,而改变一个字段的类型两者都不是。
解答
把模式(schema)看作一个记录类型:从字段编号到“类型和标志(必需或可选)”的有限映射。读取方模式为 R、写入方模式为 W 时, 读取方能读 W 写的数据,当且仅当在如下意义下 W <: R:对 R 的每个字段 n,若 n 在 W 中,则 W 中 n 的类型是 R 中类型的子类型(深度); 若 n 在 R 中是必需的,则 n 在 W 中存在且也是必需的;W 有而 R 没有的字段被跳过(宽度)。变更 v1 → v2 向后兼容即 v1 <: v2(新代码读旧数据), 向前兼容即 v2 <: v1(旧代码读新数据)。设 v1 = {1: word string 必需, 2: count int64 可选},v2 = v1 + {3: novel string 可选}。向前:v1 的每个 字段都以相同的类型和标志出现在 v2 中,字段 3 是多出来的,所以由宽度子类型 v2 <: v1;旧的读取方跳过字段 3(protobuf 保留它的字节)。 向后:v1 没有字段 3,但字段 3 在 v2 中是可选的,条件成立,新的读取方给
novel取默认值;v1 <: v2。现在让 v2 把字段 2 改成 string。 两个字段编号相同,深度子类型要求 int64 <: string 或 string <: int64,两者都不成立:一种类型的值都不是另一种类型的值。两个方向都失败, 这正是我们的检查器报告的(“int64 written, read as string; and the reverse”)。在线路上标签本身也变了,从10(线路类型 0)变成12(线路类型 2),所以读取方根本无法按自己的类型解释这些字节:视实现而定,这个值被丢弃,或者解码失败。(我们的检查器把 int32、int64、 uint32、uint64 和 bool 视为同一个变长整数家族,所以把 int32 放宽为 int64 能通过;窄的读取方随后会截断放不下的值。) -
恰好一次。 证明:在重试直到收到确认、且接收方对每个 id 至多应用一次的条件下,只要网络最终会投递某个副本,每条消息都恰好被投递一次。
解答
发送方有 id 互不相同的消息 1, …, n,对每个 id 不断重发,直到收到它的确认。接收方维护已应用 id 的集合 A 和计数器 c;收到 i 的 一个副本时,若 i ∉ A,就在一个原子步骤中应用 i 并把 i 加入 A;无论哪种情况都发送 i 的确认。公平性:(任一方向上)被发送无穷多次的消息 最终会被投递。至多一次。 初始时 c = 0、A = ∅。每个使 c 加一的步骤也向 A 加入一个新元素,没有哪个步骤只做其一,所以始终 c = |A|; 一个 id 只有在不在 A 中时才加入 A,所以每个 id 至多被应用一次,而 A ⊆ {1, …, n} 给出在每个状态下 c ≤ n,无论网络做什么。至少一次。 假设某个 i 从未被应用。那么 i 的副本从未到达(到达的副本要么应用 i,要么发现它已在 A 中)。i 的确认只在副本到达时才发送,所以从未发送过, 发送方从未收到确认,于是无穷多次发送 i;由公平性,某个副本被投递,矛盾。所以每个 id 最终都在 A 中,c = n。终止。 i 被应用后,此后到达 的每个 i 的副本都会被确认;如果发送方永远重发 i,就会有无穷多个副本到达(公平性),发出无穷多个确认,公平性再次保证其中一个被投递,之后 发送方停止。重复和乱序在论证中不起作用,因为论证从不数副本。原子性是关键:如果崩溃可能发生在应用 i 和记录 i 之间,之后到达的副本就会被 再次应用。第5章的模型检查器重发次数有界,不能假定公平性,所以它在全部 4,319 个状态中检查的是条件形式(如果两次递增都被确认,计数器就是 2,而且从不超过 2);不去重时,它在六步之内找到一个违例,计数器为 3。
-
偏移与游标。 证明:在每页之间插入 k 行的列表上,偏移分页每页大约重复 k 行,而游标分页一行也不重复。
解答
列表按从新到旧排序,每页 p 行,每读完一页就有 k ≤ p 个新行出现在顶部。偏移。 第 j 页(从 0 起)请求位置 jp 到 jp + p − 1。 此时原有各行之上已经插入了 jk 行,所以原来位于位置 r 的行现在位于 r + jk,第 j 页显示的是原来的第 jp − jk 到 jp − jk + p − 1 行(不会出现 新行,因为 jp ≥ jk)。第 j − 1 页显示的是原来的第 (j − 1)(p − k) 到 (j − 1)(p − k) + p − 1 行。重叠部分从 j(p − k) 到 (j − 1)(p − k) + p − 1,恰好 k 行:第一页之后的每一页都重复前一页的最后 k 行,读者每页只前进 p − k 个原有行。覆盖 n 行需要 P = ⌈n/(p − k)⌉ 页,看到 k(P − 1) 次重复。对 n = 1,000、p = 50,k = 1、3、10 时 P = 21、22、25,重复 20、63、240 行,与模拟结果完全 一致。插入时不会漏掉行;删除时位移方向相反,就会跳过行。代价是平方级的,因为数据库要逐行越过每个被跳过的行:没有插入时,对 j = 0, …, 19 求和 Σ (50j + 50) = 10,500 行,约为 n²/2p。游标。 第 j 页请求 id 小于第 j − 1 页最后一个 id 的最新 p 行。每个新行的 id 都比 所有已有行大,所以永远不满足条件;看到的最后一个 id 逐页严格递减,所以各页互不相交,合起来正是按顺序排列的原列表:没有重复,没有遗漏; 若 id 上有索引,每页只读 p 行(共 1,000 行)。游标需要一个唯一且全序的键;若排序键可能相等,就用 id 打破平局。
-
动手。 给我们的模拟器加一个 saga(长事务),其中订快递一步可能超时,并说明幂等的补偿能保持不变量。
解答
解答要点。 超时是第1章部分失败的第三种结果:预订可能发生了,也可能没有,还可能在一个延迟的请求到达时才发生。给
services.saga_run加一个timeout_at步骤,以及一枚隐藏的硬币决定快递服务是否真的订上了;超时时 saga 必须把这一步视为可能已完成,也要补偿它,按相反顺序: 取消快递、退款、释放库存。给快递服务一张以订单的幂等键为键的表:book(key)记录一次预订,除非该键已被标记为取消;cancel(key)无论预订 是否存在都把它标记为取消。这样取消是幂等的,在什么也没订时无害,并且能压过在它之后才到达的预订请求(用delivery.Net投递延迟的请求来 测试这种情形)。补偿会重试直到成功,就像saga_experiment(comp_fail)中那样,所以每个补偿都必须幂等:退款以订单为键,而不是每次尝试 退一笔。运行结束时对每个订单检查不变量,依据各服务自己的状态而不是 saga 的日志:要么库存已预留、卡已扣款、快递已预订、确认已发送,要么 这些都不生效。完整的答案在许多订单上、以几个百分点的超时概率运行两次:使用幂等补偿时,没有订单处于不一致状态;使用不幂等的退款时,每次 被重试的退款都付出两次,而不记录墓碑(tombstone)的取消会让迟到的预订给一个已退款的订单留下一辆快递,检查器把这两种情况都数出来。 -
★ 研究。 一个兼容性检查器,证明在丢失、重复和乱序之下,每个现有客户端在新版本上都能完成每一次协议运行。
讨论。 尚未解决。第3章的检查器比较的是消息类型,但真正要紧的是行为上的兼容:新版本可以保持每一个类型不变,却改变消息的顺序、增加一个 状态,或者把一个可以安全重试的调用变成不可以的。行为兼容是关于协议的子类型问题,而即使是异步(缓冲无界)信道上的会话类型子类型,一般而言 也已知是不可判定的(Bravetti、Carbone 与 Zavattaro;Lange 与 Yoshida,2017);丢失、重复和乱序只会扩大运行的集合,而“现有客户端”是 陌生人写的程序,只能通过它们的流量或契约来了解(海勒姆定律)。好的部分答案应当固定一个模型(有限状态的客户端,例如从消费者驱动的契约中 提取;服务表示为会话类型),对效果已去重的协议,把会丢失、会重复的信道归约为可靠但会乱序的信道(把第5章的定理变成一条引理),并给出一个 在明确规定的片段上(例如有界缓冲,或者没有循环的协议)可靠且可判定的检查器,证明它接受第3章和第6章中安全的变更,拒绝重新编号的陷阱, 以及客户端无法处理的新枚举值。一个截断结果(缓冲大小或重试次数的一个界,超过它就不会出现新情况),或者在一个真实公开 API 的历史上做的 评估,也都是新的。
Build the film
python -m videos.cs.cs43.compute # the part's numbers, into .cache/cs43
python tools/build.py cs43 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs43 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs43. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs43.compute
python -m unittest tests.test_cs43_api
python tools/build.py cs43