This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-zero-copy-streaming-backpressure-invariant

Axum 0.8 Zero-Copy Streaming Body Backpressure and Teardown Invariant

Enforces bounded memory allocations and deterministic connection lifecycle management for asynchronous HTTP request/response bodies in Axum 0.8. Prohibits unbounded payload buffering into memory and mandates explicit downstream stream backpressure propagation with deterministic cancellation semantics during early aborts.

Prohibited Anti-Pattern: Unbounded In-Memory Body Ingestion and Unhandled Stream Aborts Leading to Socket and Memory Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Zero-Copy Streaming Body Backpressure and Teardown Invariant - Enforces bounded memory allocations and deterministic connection lifecycle management for asynchronous HTTP request/response bodies in Axum 0.8. Prohibits unbounded payload buffering into memory and mandates explicit downstream stream backpressure propagation with deterministic cancellation semantics during early aborts.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-zero-copy-streaming-backpressure-invariant"
---

# Axum 0.8 Zero-Copy Streaming Body Backpressure and Teardown Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded In-Memory Body Ingestion and Unhandled Stream Aborts Leading to Socket and Memory Leaks

## System Constraints
You are a Principal Rust Systems Architect specializing in high-throughput network services and Axum 0.8 internals. Enforce strict zero-copy streaming, explicit backpressure propagation via Tokio and `http-body 1.0`, bounded allocation constraints, and deterministic teardown for partially consumed streams in reverse proxy and high-throughput pipelines. Never allow `axum::body::to_bytes` without tight bounds, and never drop unconsumed incoming streams without explicit channel draining or immediate connection reset.

## Strict Guidelines
- Engineers MUST ALWAYS stream `axum::body::Body` using `BodyDataStream` or `http_body_util::BodyStream` chunk-by-chunk to enforce TCP receive window backpressure upstream.
- Engineers MUST NOT buffer entire unbounded payloads into RAM using `axum::body::to_bytes(body, usize::MAX)` or aggregate streams into dynamic vectors in proxy pipelines.
- Services MUST enforce strict, deterministic payload byte limits using `axum::extract::DefaultBodyLimit` or `http_body_util::Limited` on all mutating HTTP routes.
- Components NEVER drop an unconsumed or aborted request stream silently; they MUST propagate stream cancellation to the upstream transport to trigger immediate TCP reset (RST) or consume up to a fixed safety threshold.
- Code SHOULD forward raw frame chunks (`Bytes`) directly through upstream/downstream channels without intermediate cloning or re-allocation.

## Bad vs Good Implementations
### Unbounded Body Buffering vs. Zero-Copy Backpressured Stream Forwarding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reading the entire body into memory via unbounded `to_bytes(..., usize::MAX)` collapses TCP backpressure, exhaustively consumes host memory under load, and prevents zero-copy pipeline execution.
```rust
use axum::{body::Body, extract::Request, response::Response, http::StatusCode};

pub async fn proxy_handler(req: Request<Body>) -> Result<Response<Body>, StatusCode> {
    // ANTI-PATTERN: Buffers entire stream into heap without backpressure or size limits.
    // High throughput or large payloads induce massive RSS spikes and OOM panics.
    let full_bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Allocates and copies data redundantly
    let client = reqwest::Client::new();
    let upstream_res = client
        .post("http://internal-upstream:8080/upload")
        .body(full_bytes)
        .send()
        .await
        .map_err(|_| StatusCode::BAD_GATEWAY)?;

    let resp_bytes = upstream_res.bytes().await.map_err(|_| StatusCode::BAD_GATEWAY)?;
    Ok(Response::new(Body::from(resp_bytes)))
}
```

#### Production Standard (Correct)
> **Standard**: Converts incoming `Body` into a chunk stream governed by `http_body_util::Limited`, forwarding `Bytes` zero-copy chunks to downstream HTTP clients while preserving end-to-end TCP backpressure and enforcing bounded memory.
```rust
use axum::{
    body::Body,
    extract::Request,
    http::StatusCode,
    response::Response,
};
use futures_util::TryStreamExt;
use http_body_util::StreamBody;
use tokio_util::io::ReaderStream;

const MAX_PROXY_BODY_BYTES: usize = 10 * 1024 * 1024; // 10 MiB limit

pub async fn proxy_handler(req: Request<Body>) -> Result<Response<Body>, StatusCode> {
    let (parts, body) = req.into_parts();
    
    // Enforce bounded memory allocations with explicit stream limiting
    let limited_body = http_body_util::Limited::new(body, MAX_PROXY_BODY_BYTES);
    let chunk_stream = http_body_util::BodyStream::new(limited_body)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e));

    // Stream zero-copy chunks directly to upstream with Tokio backpressure
    let client = reqwest::Client::new();
    let upstream_res = client
        .post("http://internal-upstream:8080/upload")
        .headers(parts.headers)
        .body(reqwest::Body::wrap_stream(chunk_stream))
        .send()
        .await
        .map_err(|_| StatusCode::BAD_GATEWAY)?;

    // Pipe upstream response stream directly into Axum response
    let stream = upstream_res.bytes_stream().map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e));
    let axum_body = Body::from_stream(stream);

    Ok(Response::builder()
        .status(upstream_res.status())
        .body(axum_body)
        .unwrap_or_else(|_| Response::new(Body::empty())))
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Zero-Copy Streaming Body Backpressure and Teardown Invariant

Axum 0.8 Zero-Copy Streaming Body Backpressure and Teardown Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces bounded memory allocations and deterministic connection lifecycle management for asynchronous HTTP request/response bodies in Axum 0.8. Prohibits unbounded payload buffering into memory and mandates explicit downstream stream backpressure propagation with deterministic cancellation semantics during early aborts. 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 In-Memory Body Ingestion and Unhandled Stream Aborts Leading to Socket and Memory Leaks 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 In-Memory Body Ingestion and Unhandled Stream Aborts Leading to Socket and Memory LeaksCritical
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 stream `axum

Engineers MUST ALWAYS stream `axum::body::Body` using `BodyDataStream` or `http_body_util::BodyStream` chunk-by-chunk to enforce TCP receive window backpressure upstream.

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 buffer entire unbounded payloads into RAM using `axum

Engineers MUST NOT buffer entire unbounded payloads into RAM using `axum::body::to_bytes(body, usize::MAX)` or aggregate streams into dynamic vectors in proxy pipelines.

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 enforce strict, deterministic payload byte limits using `axum

Services MUST enforce strict, deterministic payload byte limits using `axum::extract::DefaultBodyLimit` or `http_body_util::Limited` on all mutating HTTP routes.

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

Components NEVER drop an unconsumed or aborted request stream silently

Components NEVER drop an unconsumed or aborted request stream silently; they MUST propagate stream cancellation to the upstream transport to trigger immediate TCP reset (RST) or consume up to a fixed safety threshold.

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

Code SHOULD forward raw frame chunks (`Bytes`) directly through upstream/downstream channels without intermediate cloning or re-allocation.

Code SHOULD forward raw frame chunks (`Bytes`) directly through upstream/downstream channels without intermediate cloning or re-allocation.

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 Zero-Copy Streaming Body Backpressure and Teardown Invariant critical for AI coding assistants?

Enforces bounded memory allocations and deterministic connection lifecycle management for asynchronous HTTP request/response bodies in Axum 0.8. Prohibits unbounded payload buffering into memory and mandates explicit downstream stream backpressure propagation with deterministic cancellation semantics during early aborts. 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 In-Memory Body Ingestion and Unhandled Stream Aborts Leading to Socket and Memory Leaks) 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