Bound the total memory held by received messages
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 35/100
- Issue type
- Feature
- Clarity
- Mostly clear
- Activity status
- Active
- Tech stack
- rust
- Domain
- backend-api-design, performance
Research direction
The proposal names Server, ConnectRpcService, ClientConfig, ReceiveBudget, RpcBudget, and Acquire, but no source files or tests. Start by locating those entry points and the existing message, body-reading, and decompression paths. Done means implementing the proposed budget lifecycle, backpressure, release, cancellation, and wait-policy behavior with coverage for the stated RPC types.
Written by the indexing model from the issue text.
Description
Limits bounds the size and content of each received message, but no limit applies across all of the messages that a server is currently holding. Peak memory usage therefore depends on how many RPCs are in progress, and on what each handler retains. An integrator has no way to cap that total, or to apply backpressure to peers when a preferred limit is reached.
Background
Limits::max_message_size caps a single message. max_request_body_size caps the body of a unary or server-streaming request, which is read in full before the handler runs. Therefore, up to concurrent_requests × max_request_body_size can be retained for unary and server-streaming RPCs, plus the decompressed message for each compressed request.
The max_request_body_size limit does not apply to client-streaming or bidi requests, whose bodies have no fixed length. For those, the library holds up to two messages beyond what the RPC handler is processing: one in the receive channel, and another waiting to enter the channel after it. With the default 4 MiB max_message_size, up to 8 MiB per stream can be retained, so the server-wide total memory usage for buffered messages in client/bidi streaming RPCs is up to 2 × max_message_size × streams.
The number of concurrent RPCs is bounded only by the HTTP server's connection and concurrent-stream settings. If an integrator wants to limit the total memory held by received messages, their only options today are to limit the number of connections and streams, and potentially to lower max_message_size.
Proposed controls
We will introduce a ReceiveBudget trait, configured on Server/ConnectRpcService, and on ClientConfig. The library consults the trait once per RPC, and then before every allocation of storage for a received payload:
pub trait ReceiveBudget: Send + Sync + 'static {
/// Called once per RPC, before its body is read. Returning `None`
/// leaves the RPC unmetered.
fn for_rpc(&self, rpc: &BudgetContext<'_>) -> Option<Arc<dyn RpcBudget>>;
}
pub trait RpcBudget: Send + Sync + 'static {
/// Grant `bytes`, reject the request, or ask the caller to wait.
fn try_acquire(&self, bytes: usize) -> Acquire;
/// Called only after `try_acquire` returned `Acquire::Wait`.
fn acquire(&self, bytes: usize) -> BoxFuture<'static, Result<(), ConnectError>>;
/// Return `bytes` previously granted, once the storage they paid for is freed.
fn release(&self, bytes: usize);
}
pub enum Acquire {
Granted,
Wait,
Rejected(ConnectError),
}
BudgetContext is a #[non_exhaustive] struct with accessors for the RPC's Spec (procedure and StreamType), its deadline, its request headers, and its request extensions, which carry PeerAddr, PeerCerts, and anything a Tower layer inserted, such as a tenant or connection identifier. Selecting a budget once per RPC lets an implementation resolve a tenant or a connection once, return a shared per-tenant or per-connection budget, or leave some RPCs unmetered.
- The library chooses the size to acquire. The reader acquires the capacity it is about to allocate, which grows with the bytes received (#302), not the length the message header declares. An implementation therefore never grants more than the reader would allocate anyway. When a buffer grows, the library acquires the growth, and everything acquired for one buffer is released together when that buffer is freed.
- Acquired bytes are released exactly when the storage is freed. The library records each acquisition in a guard (an
Arc<dyn RpcBudget>and a byte count) that travels inside the message'sBytesthroughBytes::from_owner, and the guard callsreleasewhen the handler drops the message.from_ownerallocates once per message, andbyteshas no other public way to run code when aBytesis dropped; because the handler decides when that happens, the allocation cannot be reused. Nothing else allocates per message:try_acquirereturns without allocating, and only a wait boxes a future. Releasing when the handler drops the message, rather than when the library hands it over, counts every RPC type the same way: a unary payload is counted while its handler runs, and so is a streamed message that a handler keeps. - A compressed message acquires its decompressed size as it grows. The decompressed size is not known in advance and can reach
max_message_size, so the library reads from the provider'sdecompressorin steps, and acquires each growth of the output buffer before continuing, starting from the existing estimate of twice the compressed size. The bytes acquired for the compressed buffer are released when decompression finishes. - A body read in full is acquired frame by frame. For unary and server-streaming requests, the body collector acquires each received frame before reading the next one, and then acquires the contiguous buffer it assembles. hyper allocates each frame before the library sees it, so a request that is waiting in
acquireholds at most one frame beyond what it has been granted. - Waiting in
acquireapplies backpressure. A reader waiting inacquirestops pulling bytes from the request body, and hyper returns HTTP/2 flow-control credit only as body frames are read, so the peer stops sending once the stream's window is used up. - A wait ends when the RPC can no longer use the grant. The library waits until the grant arrives, the implementation fails the wait, the request deadline passes, or the RPC ends because the handler dropped its request stream or the client cancelled. The streaming reader task is detached so that it can finish draining the request body, so it outlives the handler's future and has to watch for its request stream closing while it waits. hyper drops the handler's future when an HTTP/2 client resets the stream, which closes the request stream.
- How long to wait is the implementation's policy.
try_acquirecan returnAcquire::Rejectedimmediately, and the future fromacquirecan fail after a timeout the implementation chooses, with whatever code and detail the implementation chooses.resource_exhaustedis the conventional code, since gRPC implementations generate it for out-of-memory and server overload conditions. The error ends the RPC: a unary request fails before its handler runs, and a streaming handler, or a client reading a response stream, receives the error as the next item of its stream. The error message reaches the peer, so it should carry only detail the integrator is willing to share. - Waiting can deadlock. A handler that holds every message until the stream ends keeps everything acquired for those messages, so under a shared budget two such streams can wait on each other until one of them reaches its deadline or the implementation fails the wait, and indefinitely if neither happens.
- The budget is selected before interceptors run. For client-streaming and bidi RPCs the library starts reading the body before it calls interceptors, so
for_rpcsees the request extensions that Tower layers inserted, but not anything an interceptor adds.
The library will provide a ReceiveBudget for a server-wide limit, using a tokio::sync::Semaphore sized in bytes, with RpcBudget::try_acquire handled by try_acquire_many and forget, RpcBudget::acquire by acquire_many_owned, and RpcBudget::release by add_permits. It rejects a request for more bytes than its whole capacity immediately, because the semaphore could never grant it, and it fails a wait with resource_exhausted once the wait exceeds a maximum set with with_max_wait, which defaults to 5 seconds. The maximum applies to every wait, whether or not the RPC has a deadline, because a wait for memory should end within seconds unless the server is overloaded or two RPCs are deadlocked; an earlier deadline still ends the wait first. with_max_wait(Duration::ZERO) rejects instead of waiting, and with_max_wait(None) waits until the deadline or the end of the RPC.
Out of scope: memory that decoding commits to repeated, map, string and bytes elements, which element_memory_limit bounds per decode, and HTTP/2 receive buffers inside hyper, which the flow-control window settings bound.
- Dominant language
- Rust
- Stars
- 544
- Forks
- 77
- PR merge metrics
- No merged PRs in 30d
Getting set up
- No Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from connectrpc/connect-rust
-
Difficulty 3/5 1-2 days Newbie friendliness 55/100
connectrpc/connect-rust#360 ·
-
Difficulty 5/5 Over a week Newbie friendliness 35/100
connectrpc/connect-rust#358 ·
-
Difficulty 3/5 1-2 days Newbie friendliness 53/100
connectrpc/connect-rust#355 ·
-
Streaming request body errors are always reported as `internal`Possibly taken @AhmedElBanna80 claimed this 18 days ago. Open
Difficulty 3/5 1-2 days Newbie friendliness 72/100
connectrpc/connect-rust#352 ·
-
Difficulty 3/5 Half a day Newbie friendliness 48/100
connectrpc/connect-rust#349 ·
All issues in connectrpc/connect-rust
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
Choochmeque/tauri-plugin-webdriver#134 ·
Maintainers usually reply within 17 days
-
bug rust SDK & CLI & REST API
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
boxlite-ai/boxlite#3292 ·
Maintainers usually reply within 1 day
-
Android bug
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
anefzaoui/misterdownloadmanager#2516 ·
Maintainers usually reply within 1 day
-
editor ui
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
state:triage tech-debt
Difficulty 2/5 1-3 hours Newbie friendliness 89/100
agent8-cash/ethpayserver#731 ·
Maintainers usually reply within 1 day