Go · Chapter 19 of 26

Context

By the end of this chapter you can give work a deadline or cancel it with context.Context, tell a timeout from a cancel with ctx.Err(), pass a context down so cancelling a request stops everything done for it, check a context in your own loops, and say why a context is always a function's first parameter. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Concurrency
  • 4 tasks
  • Go
  • In the all labs plan

The first 2 chapters of Go are free. This one comes with the all labs plan.

Why you need this

In chapter 17 your lookup gave up after 100 ms. But look at what kept going: the goroutine you left behind was still waiting on the central system, and the central system was still working on a question nobody wanted answered any more. At the evening peak, Tenzin's graphs showed exactly that: the drivers' apps had given up, and the central system was busy with thousands of lookups for them. Every abandoned call took a slot that a live one needed.

Giving up is only half the job. The other half is telling the work below you to stop, and that work may be several calls deep: the status handler calls a lookup function, which starts goroutines, which call the central system, which waits on its database. A done channel from chapter 17 could do it, if every function in the chain took one, and a separate timer for every deadline. Go's standard library has one value that carries both, which every function in the chain accepts: a context.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    batch.go: a batch of lookups under a 200 ms deadline

    Write Statuses(ctx context.Context, c *bijli.Central, ids []string) ([]bijli.Status, error) in batch.go. It asks c for the status of every charger in ids, all at the same time, and gives the whole batch at most 200 ms from when it is called. Make the 200 ms deadline from the ctx it is given, so a caller's earlier deadline or cancel still counts, and pass it to every lookup.

    When every lookup answers, return the statuses in the order of ids and nil. Otherwise return nil and an error: after 200 ms one for which errors.Is(err, context.DeadlineExceeded) is true; with a ctx that was already cancelled, one for which errors.Is(err, context.Canceled) is true; for an unknown id such as C9999, the central system's error, which wraps bijli.ErrUnknownCharger.

    The Check uses a fake clock: C1001 to C1050 at 40 ms a lookup must take exactly 40 ms; a central system that takes 1 s must give the deadline error after exactly 200 ms; a ctx that ends after 30 ms must stop it after 30 ms. When Statuses returns, none of its goroutines may still be running. Call the cancel function that comes with the deadline when Statuses returns.

  2. Task 2

    down.go: cancel the rest when one charger is down

    Write AllUp(ctx context.Context, src StatusSource, ids []string) error in down.go. StatusSource (declared in the starter) is anything with a method ChargerStatus(ctx context.Context, id string) (bijli.Status, error), like *bijli.Central. AllUp asks src for the status of every charger in ids, all at the same time. If they all answer without an error, it returns nil. As soon as one fails, it cancels all the others at once and returns the error of the one that failed, after every lookup has finished.

    The Check gives a fake StatusSource: C1099 fails after 10 ms with an error that wraps bijli.ErrChargerDown, and every other charger answers after 1 s unless its ctx ends first, when it returns ctx.Err(). With C1099 first, in the middle or last in ids, AllUp must return C1099's error (errors.Is with bijli.ErrChargerDown) after exactly 10 ms (fake clock), every other lookup must have seen its ctx cancelled, and none may still be running. With three chargers that all answer, AllUp returns nil after 1 s.

    Once you cancel, the other lookups fail too, with context.Canceled: return the first failure, not one of theirs.

  3. Task 3

    replay.go: a replay that stops when ctx ends

    Write Replay(ctx context.Context, readings []bijli.Reading, every time.Duration, out chan<- bijli.Reading) (int, error) in replay.go. It sends the readings on out, in order, one every interval, the first one interval after Replay starts, until all are sent or ctx ends. When all are sent it returns len(readings) and nil; when ctx ends it returns at once how many it sent and ctx.Err().

    The Check uses a fake clock. With 100 readings, every = 10 ms and a ctx that ends after 255 ms, Replay must send exactly the first 25 readings, in order, and return 25 and an error for which errors.Is(err, context.DeadlineExceeded) is true, after exactly 255 ms. With 5 readings and context.Background(), it returns 5 and nil after 50 ms. When nobody receives from out and ctx ends after 50 ms, Replay must still return, with 0 and the deadline error, after exactly 50 ms.

  4. Task 4 · interview question

    Interview: checker.go, the checker that stopped working

    Tenzin's Checker has NewChecker(c bijli.Central) Checker and (ch *Checker) Status(ctx context.Context, id string) (bijli.Status, error), which should give each status lookup 100 ms. NewChecker makes one context with a 100 ms timeout and keeps it in the struct, and Status uses it. In the service, every lookup failed with context deadline exceeded from 100 ms after the Checker was made, and a request whose caller had gone kept asking anyway.

    Fix it, keeping the names and parameters, so that every call of Status gets its own 100 ms, counted from the call, made from the caller's ctx. The Check (with a fake clock): 150 ms after NewChecker, Status(ctx, "C1042") with a quick central system returns C1042's status; with a central system that takes 1 s, Status returns context.DeadlineExceeded after exactly 100 ms; with a caller's ctx already cancelled, it returns context.Canceled; with a caller's ctx that ends after 30 ms, it stops after 30 ms.

    Joseph will ask: why is a context a parameter, and never a field of a struct?

What you will learn

  • context.Context: carries a deadline and a cancel signal down a chain of calls.
  • context.Background(): the empty context everything starts from.
  • WithCancel, WithTimeout, WithDeadline: a child context that ends when you say, or at a time.
  • ctx.Done() and ctx.Err(): a channel closed when it ends, and why: context.Canceled or context.DeadlineExceeded.
  • Always call cancel, and pass ctx down, first parameter, every time.
  • Checking ctx in your own loops, and context values in one paragraph.

More in Concurrency

Build "Context" yourself

BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Go are free. This one comes with the all labs plan.