Unit 8 of 13 · about 4 hours · explain, implement

Structured errors, cancellation propagation and streaming flow control

A bare timeout string forces every caller to guess. Structured codes plus propagated cancellation turn a failure into an instruction the whole chain can follow.

You'll be able to

  • Classify errors into retryable, reject-and-fix and never-retry using status codes.
  • Propagate cancellation across hops and release handler resources on cancel.
  • Explain streaming flow control and the half-closed states that unary calls never show.

Covers

Structured errors and retry classificationCancellation propagation and cleanupStreaming flow control and half-closed connections
1

Read

In this order, only the parts listed

0 of 3 done

  1. gRPC status codesgRPC Guides - Deadlines, Cancellation, Status Codes, Retry and Flow Control

    Full list: DEADLINE_EXCEEDED may return even when the operation completed; UNAVAILABLE is the transient retryable code; only user code generates INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE and DATA_LOSS

  2. gRPC cancellation guidegRPC Guides - Deadlines, Cancellation, Status Codes, Retry and Flow Control

    Deadline expiry and I/O errors trigger cancel; server handlers must poll and stop; outgoing calls auto-cancel in Java, Go and C++ but not Python

  3. gRPC flow control guidegRPC Guides - Deadlines, Cancellation, Status Codes, Retry and Flow Control

    Streaming only with framework-managed window; writes wait when the receiver is full; synchronous two-sided bulk writes without reads can deadlock

2

Focus on

  • Codes are a contract: UNAVAILABLE invites a bounded retry, FAILED_PRECONDITION demands a state fix first, INVALID_ARGUMENT forbids retrying the same bytes.
  • DEADLINE_EXCEEDED after a mutation is ambiguous by definition. The code reports lateness, not non-execution, so pair it with an idempotency key.
  • Cancellation is cooperative. The library delivers the signal, but a handler that never checks keeps burning CPU and holding locks after the client left.
  • Flow control applies to streams, not unary calls. Writes block until the receiver frees window, which is why two sides doing bulk synchronous writes without reads deadlock.
Common mistakes · 3
  • Retrying INVALID_ARGUMENT on a timer. The request is bad regardless of system state, so retries only add load; fix the bytes first.
  • Assuming cancel kills the handler. The RPC library cannot interrupt application code, so a long loop without checks runs to completion anyway.
  • Applying streaming flow-control reasoning to unary calls. Unary calls have no window to manage; their failure modes are deadlines, caps and errors.
3

Try it yourself

Closed-book, before checking anything

Without notes, map five failures (overloaded dependency, bad argument, missing entity, expired deadline after a write, aborted transaction) to codes and retry decisions, then implement a handler that checks cancellation each work chunk and propagates cancel to its downstream call.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A call fails with UNAVAILABLE, then with FAILED_PRECONDITION. Which one retries?Answer

    Only UNAVAILABLE, with backoff and a budget. FAILED_PRECONDITION needs an explicit state fix such as emptying the directory before any retry.

  2. 2.A write returns DEADLINE_EXCEEDED. May the client assume it did not apply?Answer

    No. The guide states this error may return even when the operation completed, for example when the success reply arrived after the timer. Reconcile by key.

  3. 3.A Python server spawns a downstream RPC and the client cancels. What must the handler do?Answer

    Poll the serving context for cancellation, stop work, clean up, and cancel the downstream call explicitly, since Python does not auto-cancel outgoing calls.

  4. 4.Client and server both use synchronous reads, and each writes a large burst of stream messages before reading any. What happens?Answer

    Both block in flow control once windows fill, and neither drains, so they deadlock. At least one side must interleave reads, or use async handlers.

5

Practice

You're done when

Your error map routes each code to retry, fix-first or never-retry, and your streaming handler stops within one work chunk of cancellation while propagating it downstream.

Only when you can do this without notes.

Leads to

Notes

Resources · 1 for this unit, 15 more in the section
  • gRPC Guides - Deadlines, Cancellation, Status Codes, Retry and Flow ControlgRPC Authors · required

    Read the deadlines, cancellation, status codes, retry (enabled by default with no default policy; no retry once response headers arrive), keepalive and flow-control guides. Turn each into a rule your own RPC layer follows, and check a claim against grpcio before you rely on it.

Also in this section

  • DDIA 2e - Chapter 5 Encoding and EvolutionMartin Kleppmann and Chris Riccomini · primary

    Read formats, schema evolution, service RPC, durable workflows and event-driven dataflow. Write a four-version compatibility table and connect each compatibility claim to a wire fixture.

  • Protocol Buffers and Avro - Unknown Fields and Schema ResolutionGoogle and the Apache Software Foundation · required

    Read the proto3 guide on field numbers, defaults and unknown fields (kept through binary parsing and reserialization, lost through JSON) and the Avro 1.12.0 schema resolution rules (https://avro.apache.org/docs/1.12.0/specification/). Build round-trip fixtures that show each rule.

  • Building Distributed Systems - The MessengerBuild Distributed Systems · support

    Track 1 is free: do the RPC subtrack (sync RPC with timeout, timeout and retry loop, async callbacks, callback reaper, exponential backoff) and the deduplication task. Tasks are graded in the browser after login, so treat a pass as a drill and keep your local harness as the evidence.

  • MIT 6.5840 - RPC and Threads plus Lab 2 Key/Value ServerMIT PDOS · required

    Read the Lecture 2 notes (notes/l-rpc.txt and notes/kv.go) on RPC failure and at-most-once execution, then do Lab 2: a versioned Put key/value server whose client returns ErrMaybe when a retried Put may already have run, and a lock built on it. Keep the course tests, then add cancellation, size-limit and mixed-version faults in your own harness.

  • DSLabs - Lab 1 Exactly-Once RPCUniversity of Washington (Ellis Michael) · support

    Labs are Java 21 message-passing state machines tested on an emulated network and by model-checking search tests that print a minimal violating trace; run them with the run-tests.py script and its --lab and --part options. Lab 1 builds an "exactly-once" RPC abstraction for an unreplicated key/value server on a network that drops, duplicates and reorders messages. Use it to check your request identity and duplicate-suppression design against exhaustive orderings.

  • HLD Handbook - Networking, API Design and BackpressureHLD Handbook · required

    Read only Part 0 networking and API design, then the load balancer, service discovery, rate limiting and reliability chapters needed for the protocol design. Use the diagrams to review boundaries, not as a substitute for fault tests.

  • AWS Builders' Library - Timeouts, Retries and Backoff with JitterAmazon Web Services · required

    Read the whole article for timeout choice, retries at one layer, retry amplification across hops, capped exponential backoff and jitter. Derive the request multiplier for retries at every layer of a call chain before writing your retry policy.

  • AWS Builders' Library - Making Retries Safe with Idempotent APIsAmazon Web Services · support

    Read the caller-provided client request identifier pattern, the validation error for a repeated identifier with different parameters, the semantically equivalent response to a retry and why the identifier is retained only for a bounded interval. Compare that interval with your own duplicate-suppression state.

  • Building Distributed Systems - The NetworkerBuild Distributed Systems · optional

    Only the first three tasks are free (TCP echo, connection pool and backlog, graceful shutdown and drain). Tasks are graded in the browser after login, so treat a pass as a drill and keep your local harness as the evidence.

  • Beej's Guide to Network ProgrammingBrian Hall · support

    Use the client, server, send, receive, select or poll, and partial-transfer sections when socket behavior is unclear. This is a protocol mechanics reference, not the distributed-systems spine.

  • AlgoMaster System Design - Selected Networking and API ProblemsAlgoMaster · optional

    Use the problems on idempotency and retries (Deduplicate Idempotent Requests, Build an Idempotent Consumer, Classify Retry Outcomes), rate limiting (sliding-window log and token bucket), the Least Requests load balancer and the queue visibility timeout. For every solved component, add an external fault test and explain what its simplified judge does not establish.

  • Replicated Log and Stream Processor - Protocol SliceRoadmap-Final · support

    Create the repository, message schema, request and node identities, deadline and retry contract, deterministic network scheduler and raw event format. Keep this same artifact through DS-9.

  • RFC 9000 - QUIC Version 1IETF · reference

    Read Section 2 (streams), Section 4 (flow control) and Section 9 (connection migration) for QUIC transport behavior. No implementation; compare with TCP behavior from the Systems stage.

  • RFC 9114 - HTTP/3IETF · reference

    Read Sections 3 (connection setup), 6 (stream mapping) and 7 (framing) for how HTTP semantics map onto QUIC streams.

  • W3C Trace ContextW3C · reference

    Read Section 3.2 (traceparent fields), Section 3.3 (tracestate) and Section 4 (processing model) for trace correlation without synchronized clocks.