Skip to content

fix(reverseproxy): defer response body close to prevent buffer pool memory leaks on early exit paths#7841

Open
HarshalPatel1972 wants to merge 1 commit into
caddyserver:masterfrom
HarshalPatel1972:fix/proxy-buffer-leak
Open

fix(reverseproxy): defer response body close to prevent buffer pool memory leaks on early exit paths#7841
HarshalPatel1972 wants to merge 1 commit into
caddyserver:masterfrom
HarshalPatel1972:fix/proxy-buffer-leak

Conversation

@HarshalPatel1972

Copy link
Copy Markdown

Assistance Disclosure

I used an AI assistant to collaborate on the architectural discovery, trace early exit paths, and construct the defensive deferred cleanup pattern used in this patch. I verified the code compilation locally.


Description

This PR introduces a defensive defer cleanup envelope around the upstream response body tracking loop inside the reverse proxy module (reverseproxy.go). This guarantees the release of pooled internal buffers under unexpected upstream errors or early termination paths.

Technical Root Cause

When h.bufferedBody() pulls a dynamic byte buffer from bufPool, it encapsulates it into a standard bodyReadCloser. Safely recycling that memory requires explicitly calling .Close() on the response body down the execution line.

However, several critical error branches (such as status code parsing failures or downstream connection faults) execute an immediate return before reaching finalizeResponse(). Because these intermediate exit routes bypass the non-deferred closure tracking, the wrapped bodyReadCloser is discarded, permanently leaking the underlying buffer from the core sync.Pool.

Resolution Strategy

  • Defensive Defer Envelope: Implemented an explicit defer wrapper tracking res.Body closure right after the upstream request completes and assigns the response payload.
  • Ownership Transfer Flag: Added a state variable (bodyReleased) that toggles to true once the stream safely passes into the final handoff pipeline, preventing premature closure during an un-interrupted lifecycle.
  • Idempotent Leak Mitigation: Ensures any premature return routes cleanly invoke .Close(), safely returning the allocation directly to the buffer pool under high-concurrency client failures.

Copilot AI review requested due to automatic review settings June 24, 2026 10:56

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@CLAassistant

CLAassistant commented Jun 24, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants