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
Open
Conversation
…emory leaks on early exit paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
defercleanup 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 frombufPool, it encapsulates it into a standardbodyReadCloser. 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 wrappedbodyReadCloseris discarded, permanently leaking the underlying buffer from the coresync.Pool.Resolution Strategy
deferwrapper trackingres.Bodyclosure right after the upstream request completes and assigns the response payload.bodyReleased) that toggles to true once the stream safely passes into the final handoff pipeline, preventing premature closure during an un-interrupted lifecycle..Close(), safely returning the allocation directly to the buffer pool under high-concurrency client failures.