Context timeout and deadline

A context timeout or deadline limits how long an operation may continue before cancellation is signalled. Using context.WithTimeout or context.WithDeadline helps prevent slow downstream operations from consuming resources indefinitely.

Minimal example

go
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()

select {
case <-ctx.Done():
    return ctx.Err()
case result := <-results:
    _ = result
}

Learn this concept

Lesson 1.17 · The chi router and context.Context

Used in exercises

Exercise 1.22 · Redis fixed-window limiter that fails open Exercise 1.29 · Optional: Token bucket in Redis with Lua and EVALSHA Exercise 6.6 · Request context and timeout layer Exercise 7.17 · gRPC resilience interceptors
Prerequisite conceptsGo contextGo time package