Context and cancellation
Put a budget around work and propagate it.
The idea
A context carries cancellation, deadlines, and request-scoped values across API boundaries. Pass it as the first parameter and call the returned cancel function. Fiber has its own request context lifecycle; derive a standard context for database deadlines and do not retain the pooled Fiber context after the handler returns.
Follow the flow
Make it concrete
This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.
ctx, cancel := context.WithTimeout(c.UserContext(), 2*time.Second)
defer cancel()
booking, err := store.Find(ctx, tenantID, bookingID)
if err != nil { return err }
return c.JSON(booking)Decisions that matter
- Cancellation is cooperative; an operation must observe the context.
- A timeout does not prove a database write failed to commit.
- Do not use context values as a hidden dependency container.
Your turn
Why is saving *fiber.Ctx in a background goroutine unsafe?
Reveal a worked answer
Fiber reuses request contexts. Read the required values while handling the request, copy data that must outlive it, and use an independently managed standard context for background work. Define who owns shutdown and cancellation.