Skip to content

Commit 0a27ce5

Browse files
author
jose.castillo
committed
fix: limit HTTP buffer pool size to prevent memory growth in cluster mode
1 parent 9fc6d8c commit 0a27ce5

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

transport/http_transport.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ var bufferPool = sync.Pool{
4747
New: func() interface{} { return new(bytes.Buffer) },
4848
}
4949

50+
const maxBufferSize = 1024 * 1024 // 1MB
51+
5052
type GroupCacheInstance interface {
5153
GetGroup(string) Group
5254
}
@@ -281,7 +283,13 @@ func (t *HttpTransport) ServeHTTP(w http.ResponseWriter, r *http.Request) {
281283
defer r.Body.Close()
282284
b := bufferPool.Get().(*bytes.Buffer)
283285
b.Reset()
284-
defer bufferPool.Put(b)
286+
defer func() {
287+
if b.Cap() > maxBufferSize {
288+
b = nil
289+
} else {
290+
bufferPool.Put(b)
291+
}
292+
}()
285293
_, err := io.Copy(b, r.Body)
286294
if err != nil {
287295
http.Error(w, err.Error(), http.StatusInternalServerError)
@@ -382,6 +390,14 @@ func (h *HttpClient) Get(ctx context.Context, in *pb.GetRequest, out *pb.GetResp
382390
}
383391
b := bufferPool.Get().(*bytes.Buffer)
384392
b.Reset()
393+
defer func() {
394+
if b.Cap() > maxBufferSize {
395+
b = nil
396+
} else {
397+
bufferPool.Put(b)
398+
}
399+
}()
400+
b.Reset()
385401
defer bufferPool.Put(b)
386402
_, err := io.Copy(b, res.Body)
387403
if err != nil {

0 commit comments

Comments
 (0)