Skip to content

Commit 769d4a7

Browse files
committed
http-connect: reduce memory allocations
Introduce a `sync.Pool` to reuse read buffers in the `ServeHTTP` handler for the http-connect mode. Previously, a new 32KB buffer was allocated for every hijacked connection, causing high GC pressure in high-throughput scenarios. By pooling and reusing these buffers, we significantly reduce the number of memory allocations, which improves CPU usage and lowers request latency by decreasing the impact of garbage collection. Signed-off-by: Imran Pochi <[email protected]>
1 parent 7c8afba commit 769d4a7

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

pkg/server/tunnel.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,22 @@ import (
2929
"sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics"
3030
)
3131

32+
const (
33+
// bufferSize is the size of the buffer used for reading from the hijacked connection.
34+
// It matches the gRPC window size for optimal performance.
35+
bufferSize = 1 << 15 // 32KB
36+
)
37+
38+
// bufferPool is a pool of byte slices used for reading data from hijacked connections.
39+
// This reduces memory allocations and GC pressure by reusing buffers across connections.
40+
var bufferPool = sync.Pool{
41+
New: func() interface{} {
42+
// Allocate a new buffer when the pool is empty
43+
buf := make([]byte, bufferSize)
44+
return &buf
45+
},
46+
}
47+
3248
// Tunnel implements Proxy based on HTTP Connect, which tunnels the traffic to
3349
// the agent registered in ProxyServer.
3450
type Tunnel struct {
@@ -176,7 +192,14 @@ func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
176192
agentID := connection.agentID
177193
klog.V(3).InfoS("Starting proxy to host", "host", r.Host, "agentID", agentID, "connectionID", connID)
178194

179-
pkt := make([]byte, 1<<15) // Match GRPC Window size
195+
// Get a buffer from the pool
196+
bufPtr := bufferPool.Get().(*[]byte)
197+
pkt := *bufPtr
198+
defer func() {
199+
// Return the buffer to the pool when done
200+
bufferPool.Put(bufPtr)
201+
}()
202+
180203
var acc int
181204

182205
for {

0 commit comments

Comments
 (0)