Course contentsShow
← System Design
Lesson 1094 of 1,91928. Timeouts and DeadlinesFree lesson

Timeout Cancellation and Cleanup

Ensuring that when a timeout fires, resources are properly released and work is actually cancelled.

Timeout Cancellation and Cleanup

You'll learn why firing a timeout alone isn't enough—you must also cancel in-flight work and release resources to prevent leaks and waste.

The Problem with Passive Timeouts

Many developers treat timeouts as simple timers: "If the operation takes longer than X seconds, return an error to the caller." But here's the critical mistake: the underlying work often keeps running.

The database query continues executing. The HTTP connection stays open. The thread remains blocked. Memory buffers sit allocated. You've abandoned the result, but the resources are still tied up—potentially for minutes or until some other limit hits.

The Kitchen Analogy

Imagine ordering food at a restaurant with a 10-minute promise. At 10:01, the waiter says "Sorry, too slow!" and walks away—but the kitchen keeps cooking your meal, tying up the stove, ingredients, and a chef's attention. That wasted effort could've served another customer.

What Proper Cleanup Means

When a timeout fires, you must:

  1. Signal cancellation to the underlying operation (close connections, interrupt threads, send cancel RPCs)
  2. Release resources immediately (connection pool slots, memory buffers, file handles)
  3. Mark work as abandoned so retries don't double-process
  4. Log the cancellation for observability

Most modern frameworks provide cancellation tokens or context propagation (like Go's context.Context) that cascade cancellation down through layers. Without this, you're just changing when you notice the problem, not stopping the problem.

The Resource Leak Risk

Systems without timeout cleanup accumulate "zombie" operations. Connection pools drain. Thread pools saturate. Memory usage climbs. What looks like a timeout configuration problem is actually a resource leak in disguise.

Key Takeaway:
A timeout must actively cancel work and free resources, not just abandon the result—otherwise you've only shifted the failure mode from slow responses to resource exhaustion.