Skip to content

🐛 bug: timeout middleware leaks fiber.Ctx on timeout (unbounded memory leak) #4359

@pageton

Description

@pageton

Problem

The timeout middleware (middleware/timeout/timeout.go:44-82, 136-152) permanently leaks fiber.Ctx objects when a request times out. When the timeout fires:

  1. The handler goroutine continues using the fiber.Ctx.
  2. The middleware calls c.Abandon() which prevents ReleaseCtx from returning the context to the pool.
  3. The cleanup goroutine (line ~136) blocks indefinitely waiting for the handler to finish.

The code comment at line ~145 explicitly acknowledges: "timed-out requests leak their contexts until a safe reclamation strategy exists."

Impact

  • Each timed-out request permanently leaks one DefaultCtx + all embedded fasthttp allocations (byte buffers, etc.).
  • Under sustained upstream degradation (the exact scenario that triggers timeouts), this becomes an unbounded memory leak.
  • At 1K timed-out requests/sec, ~1K DefaultCtx objects accumulate every second, leading to OOM kills.

Note: The related redesign issue #3394 was closed but this specific memory leak was not addressed.

Proposed fix

  1. Implement a finalizer goroutine pool or sync.WaitGroup-based cleanup that eventually calls ForceRelease after the handler goroutine completes.
  2. Add a secondary timeout for the cleanup goroutine itself (e.g., 2x the original timeout).
  3. Consider a bounded pool of "reclaimer" goroutines rather than spawning one per timeout.

Reproduction

app.Use(timeout.New(func(c fiber.Ctx) error {
    time.Sleep(10 * time.Second) // simulate slow upstream
    return nil
}, 100*time.Millisecond))

// Fire 10K requests → 10K leaked DefaultCtx objects

Priority

P0 — Unbounded memory leak under the exact failure mode the middleware is designed to handle.


Identified during a full performance architecture review of the Fiber codebase.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions