Xray-core icon indicating copy to clipboard operation
Xray-core copied to clipboard

Reduce memory usage by tightening buffer pool retention and adding size-aware allocations

Open benjamin920102 opened this issue 2 months ago • 1 comments

Problem

Xray still relies heavily on fixed-size 8 KiB buffers through buf.New() / buf.StackNew(), including several protocol paths that only need tens or hundreds of bytes.

At the same time, common/bytespool currently uses only four pool classes:

2 KiB
8 KiB
32 KiB
128 KiB

There is also a retention issue in bytespool.Free().

The current logic accepts any buffer whose capacity is greater than or equal to a pool class:

for i := numPools - 1; i >= 0; i-- {
    if size >= poolSize[i] {
        pool[i].Put(b)
        return
    }
}

This allows oversized allocations to contaminate smaller pools.

Example:

Alloc(1 MiB)
    -> make([]byte, 1 MiB)

Free(buffer)
    -> inserted into the 128 KiB pool

later Alloc(128 KiB)
    -> may receive a slice backed by a 1 MiB allocation

This does not help reuse future 1 MiB requests, because allocations above the largest pool class bypass the pool anyway.

It can instead cause unnecessarily large backing arrays to remain reachable through sync.Pool and increase heap/RSS after bursty workloads until GC/runtime reclamation occurs.

sing-box / sagernet/sing reference

sing-box relies heavily on the allocator from sagernet/sing.

Its buffer allocator uses much finer-grained size classes:

64 B
128 B
256 B
512 B
1 KiB
2 KiB
4 KiB
8 KiB
16 KiB
32 KiB
64 KiB
~72 KiB special class

More importantly, buffers are only returned to a pool when their capacity matches a supported allocator class.

Oversized or unsupported capacities are not inserted into smaller pools.

sing also exposes size-aware buffer allocation and uses it extensively for protocol/control data instead of always allocating the default streaming buffer size.

Proposed changes

1. Reject oversized buffers in bytespool.Free()

This should be the first and lowest-risk change.

Only buffers matching an actual pool capacity should be returned to that pool.

For example:

func Free(b []byte) {
    size := cap(b)

    for i, poolSize := range poolSize {
        if size == int(poolSize) {
            pool[i].Put(b[:size])
            return
        }
    }
}

The exact implementation can differ, but the important property is:

pool admission should be based on exact supported capacity,
not capacity >= pool size

Buffers larger than the largest supported class should simply be left for GC.

This preserves normal reuse while preventing oversized backing arrays from polluting the 128 KiB pool.


2. Preserve the existing bytespool.Alloc() API contract

bytespool.Alloc() is marked stable and currently documents:

Minimum size of returned slice is 2048.

Therefore the existing API should not simply be converted to 64/128/256-byte allocation classes.

Doing so could change observable behavior for callers relying on the current minimum capacity.

Instead, keep the existing bytespool.Alloc() semantics unchanged.


3. Add a separate size-aware allocation path for common/buf

Xray already has buf.NewWithSize(size).

Rather than changing the stable bytespool.Alloc() contract, common/buf could use a separate small-buffer allocator for size-aware allocations.

Possible classes:

64 B
128 B
256 B
512 B
1 KiB
2 KiB
4 KiB
8 KiB
16 KiB
32 KiB
64 KiB

The exact class layout should be benchmarked.

buf.New() should remain the normal 8 KiB streaming fast path.

The optimization should target only buffers whose maximum or expected size is already known.

An equivalent size-aware stack API could also be considered, e.g.:

StackNewWithSize(size)

if it reduces heap allocation without complicating ownership.


4. Migrate obvious bounded protocol/control allocations

There are multiple paths where Xray currently allocates an 8 KiB buffer for very small bounded reads.

Examples include protocol handshake/control paths such as:

proxy/socks/
proxy/vless/
proxy/vmess/
proxy/shadowsocks/

For example, some current code allocates a normal buffer and then reads only a small fixed amount:

buffer := buf.New()

if _, err := buffer.ReadFullFrom(reader, 50); err != nil {
    ...
}

Similar cases exist for SOCKS fields and other bounded protocol headers.

These are good candidates for size-aware allocation.

However, this should be done per call site.

Do not blindly replace all buf.New() calls, because many buffers later grow to contain payload data or are used in stream-copy paths where the existing 8 KiB allocation is appropriate.


Follow-up: UDP queue memory

The UDP receive path is another potential memory contributor.

The default UDP hub capacity is:

256

With 8 KiB packet buffers, a completely full queue can hold approximately:

256 * 8192 ~= 2 MiB

of raw packet backing storage, excluding object/channel overhead.

The KCP listener uses a hub capacity of:

1024

which can reach approximately:

1024 * 8192 ~= 8 MiB

when fully occupied.

Possible follow-up experiments:

- reusable packet buffers
- size-aware UDP packet storage
- direct packet dispatch where ownership permits
- batched packet reads
- queue-capacity tuning

Queue depth should not be changed without benchmarking, especially for KCP, because smaller queues may reduce burst tolerance and increase packet drops.

This should remain separate from the initial allocator fix.

Suggested implementation order

Phase 1
- make bytespool.Free() accept exact pool capacities only

Phase 2
- add an internal size-aware allocator for common/buf
- preserve existing bytespool.Alloc() behavior
- migrate clearly bounded handshake/control buffers

Phase 3
- benchmark UDP/KCP queue and packet-buffer behavior

Benchmarking

Compare before/after using:

runtime.MemStats:
- HeapAlloc
- HeapInuse
- HeapIdle
- HeapReleased
- Sys

process:
- RSS

pprof:
- alloc_space
- inuse_space
- alloc_objects
- inuse_objects

Suggested workloads:

1. High concurrent idle TCP connections
2. High connection/handshake churn
3. SOCKS/VLESS/VMess/Shadowsocks small-request workloads
4. Sustained UDP forwarding
5. KCP traffic
6. Large temporary allocations followed by an idle period

Also compare:

- GC frequency
- GC CPU cost
- retained heap after traffic stops
- RSS recovery after burst workloads
- throughput / latency regressions

Expected result

The first two phases should reduce unnecessary retained capacity and reduce memory consumed by small protocol/control buffers without changing protocol behavior or the existing 8 KiB streaming fast path.

The most important low-risk fix is preventing oversized buffers from entering smaller bytespool classes.

benjamin920102 avatar Sep 17 '26 08:09 benjamin920102

实际上 Alloc 函数根本没有多少人用 singbox的pool切的很细 但是一个默认buffer高达32kb xray默认8kb已经相当小了 对于小流量同时根本不会存在多少buffer在缓冲区 大流量则主要取决于各协议层间的总缓冲区大小 而且每块buffer在大流量下总是会被填满浪费空间很小

Fangliding avatar Sep 17 '26 09:09 Fangliding