This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-hyper-stream-quota-backpressure-fence

Axum 0.8 & Hyper 1.0 Chunked Body Stream Quota and Backpressure Fence

Enforces strict allocator byte ceilings and non-blocking backpressure on uncontrolled HTTP/2 and HTTP/3 streaming request bodies. Eliminates remote heap exhaustion (OOM DoS) attacks by replacing unconstrained buffer aggregation with frame-level byte accounting and bounded channel handoffs.

Prohibited Anti-Pattern: Unbounded Stream Buffering via to_bytes or Unmetered Channel Ingest Leading to Heap Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Hyper 1.0 Chunked Body Stream Quota and Backpressure Fence - Enforces strict allocator byte ceilings and non-blocking backpressure on uncontrolled HTTP/2 and HTTP/3 streaming request bodies. Eliminates remote heap exhaustion (OOM DoS) attacks by replacing unconstrained buffer aggregation with frame-level byte accounting and bounded channel handoffs.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-hyper-stream-quota-backpressure-fence"
---

# Axum 0.8 & Hyper 1.0 Chunked Body Stream Quota and Backpressure Fence

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Stream Buffering via to_bytes or Unmetered Channel Ingest Leading to Heap Exhaustion

## System Constraints
You are a Principal Systems Architect enforcing memory boundaries in Axum 0.8 and Hyper 1.0 services. Mandate absolute byte quotas, stream-level backpressure fences, and explicit frame consumption limits for all chunked HTTP/2 and HTTP/3 endpoints.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit byte limits at the router layer using `axum::extract::DefaultBodyLimit::disable()` paired with explicit `axum::extract::DefaultBodyLimit::max(BYTES)` or `http_body_util::Limited` on individual streaming handlers.
- Engineers MUST NOT invoke `axum::body::to_bytes(body, usize::MAX)` or aggregate frames into unbounded `Vec<u8>` buffers on streaming request handlers.
- Services MUST process incoming data frames iteratively via `http_body_util::BodyStream` or `http_body::Body::poll_frame` with a deterministic, low-capacity backpressure conduit (e.g., `tokio::sync::mpsc::channel` with fixed capacity <= 16).
- Handlers MUST immediately terminate streaming and drop the frame source upon receiving `http_body_util::LengthLimitError`, returning an HTTP 413 Payload Too Large response before allocating further down-stream structures.
- Components NEVER buffer chunked payloads in memory when destination sinks (e.g., S3 multi-part, disk, database BLOBs) support incremental streaming or framed pipeline transfers.

## Bad vs Good Implementations
### Unbounded Body Ingestion vs. Hard-Quoted Backpressured Stream Ingestion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `collect().await.to_bytes()` on an arbitrary stream in Hyper 1.0 / Axum 0.8 aggregates incoming data frames indefinitely. HTTP/2 and HTTP/3 multiplexing enables an attacker to slowly or rapidly stream gigabytes of chunks, exhausting server memory and causing unrecoverable panic or process termination.
```rust
use axum::{body::Body, extract::Request, response::IntoResponse, http::StatusCode};
use http_body_util::BodyExt;

pub async fn bad_upload_handler(req: Request) -> Result<impl IntoResponse, StatusCode> {
    // VULNERABILITY: Ingests unconstrained chunked body into process heap.
    // An attacker sending an endless HTTP/2 data stream will trigger an OOM kill.
    let whole_body = match req.into_body().collect().await {
        Ok(collected) => collected.to_bytes(),
        Err(_) => return Err(StatusCode::BAD_REQUEST),
    };

    println!("Read {} bytes into memory", whole_body.len());
    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the incoming body in `http_body_util::Limited` to guarantee that total frame byte consumption cannot exceed 10 MiB. Uses a bounded `mpsc::channel(4)` that propagates TCP/HTTP/2 flow-control backpressure upstream: if the consumer slows down, the producer pauses reading frames, preventing heap explosion.
```rust
use axum::{extract::Request, response::IntoResponse, http::StatusCode};
use http_body_util::{BodyExt, Limited};
use bytes::Bytes;
use tokio::sync::mpsc;

const MAX_ALLOWED_BYTES: usize = 10 * 1024 * 1024; // 10 MiB limit
const BACKPRESSURE_BUFFER_SLOTS: usize = 4;        // Strict backpressure fence

pub async fn good_upload_handler(req: Request) -> Result<impl IntoResponse, StatusCode> {
    // 1. Wrap the inbound body in a hard allocator fence
    let limited_body = Limited::new(req.into_body(), MAX_ALLOWED_BYTES);
    let mut body_stream = http_body_util::BodyDataStream::new(limited_body);

    // 2. Establish a bounded backpressure channel to downstream worker
    let (tx, mut rx) = mpsc::channel::<Bytes>(BACKPRESSURE_BUFFER_SLOTS);

    // 3. Spawn consumer task to enforce non-blocking processing
    let consumer_handle = tokio::spawn(async move {
        let mut total_written: usize = 0;
        while let Some(chunk) = rx.recv().await {
            total_written += chunk.len();
            // Downstream sink writes (e.g., file or object store) occur here
        }
        total_written
    });

    // 4. Stream chunks with backpressure propagation and strict limit checks
    use futures_util::StreamExt;
    while let Some(chunk_result) = body_stream.next().await {
        match chunk_result {
            Ok(chunk) => {
                if tx.send(chunk).await.is_err() {
                    return Err(StatusCode::INTERNAL_SERVER_ERROR);
                }
            }
            Err(err) if err.is::<http_body_util::LengthLimitError>() => {
                return Err(StatusCode::PAYLOAD_TOO_LARGE);
            }
            Err(_) => {
                return Err(StatusCode::BAD_REQUEST);
            }
        }
    }

    drop(tx); // Close channel so consumer finishes
    let _ = consumer_handle.await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(StatusCode::ACCEPTED)
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 & Hyper 1.0 Chunked Body Stream Quota and Backpressure Fence

Axum 0.8 & Hyper 1.0 Chunked Body Stream Quota and Backpressure Fence defines an industrial-grade behavioral standard for backend engineering. Enforces strict allocator byte ceilings and non-blocking backpressure on uncontrolled HTTP/2 and HTTP/3 streaming request bodies. Eliminates remote heap exhaustion (OOM DoS) attacks by replacing unconstrained buffer aggregation with frame-level byte accounting and bounded channel handoffs. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Stream Buffering via to_bytes or Unmetered Channel Ingest Leading to Heap Exhaustion Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Stream Buffering via to_bytes or Unmetered Channel Ingest Leading to Heap ExhaustionCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enforce explicit byte limits at the router layer using `axum

Engineers MUST ALWAYS enforce explicit byte limits at the router layer using `axum::extract::DefaultBodyLimit::disable()` paired with explicit `axum::extract::DefaultBodyLimit::max(BYTES)` or `http_body_util::Limited` on individual streaming handlers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT invoke `axum

Engineers MUST NOT invoke `axum::body::to_bytes(body, usize::MAX)` or aggregate frames into unbounded `Vec<u8>` buffers on streaming request handlers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST process incoming data frames iteratively via `http_body_util

Services MUST process incoming data frames iteratively via `http_body_util::BodyStream` or `http_body::Body::poll_frame` with a deterministic, low-capacity backpressure conduit (e.g., `tokio::sync::mpsc::channel` with fixed capacity <= 16).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Handlers MUST immediately terminate streaming and drop the frame source upon receiving `http_body_util

Handlers MUST immediately terminate streaming and drop the frame source upon receiving `http_body_util::LengthLimitError`, returning an HTTP 413 Payload Too Large response before allocating further down-stream structures.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER buffer chunked payloads in memory when destination sinks (e.g., S3 multi-part, disk, database BLOBs) support incremental streaming or framed pipeline transfers.

Components NEVER buffer chunked payloads in memory when destination sinks (e.g., S3 multi-part, disk, database BLOBs) support incremental streaming or framed pipeline transfers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Axum 0.8 & Hyper 1.0 Chunked Body Stream Quota and Backpressure Fence critical for AI coding assistants?

Enforces strict allocator byte ceilings and non-blocking backpressure on uncontrolled HTTP/2 and HTTP/3 streaming request bodies. Eliminates remote heap exhaustion (OOM DoS) attacks by replacing unconstrained buffer aggregation with frame-level byte accounting and bounded channel handoffs. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Stream Buffering via to_bytes or Unmetered Channel Ingest Leading to Heap Exhaustion) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Axum