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

Axum 0.8 Tower Zero-Copy Body Stream Backpressure Invariant

Enforces strict end-to-end asynchronous backpressure across Axum 0.8 and Tower service pipelines to prevent unbounded memory growth during multi-gigabyte payload ingests. Prohibits eager body collection into heap buffers, mandating zero-copy streaming directly from the transport layer into rate-governed sinks to maintain HTTP/2 and TCP receive window constraints.

Prohibited Anti-Pattern: Buffering Inbound Request Bodies into Unbounded Memory Buffers Without Transport Backpressure

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Zero-Copy Body Stream Backpressure Invariant - Enforces strict end-to-end asynchronous backpressure across Axum 0.8 and Tower service pipelines to prevent unbounded memory growth during multi-gigabyte payload ingests. Prohibits eager body collection into heap buffers, mandating zero-copy streaming directly from the transport layer into rate-governed sinks to maintain HTTP/2 and TCP receive window constraints.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-tower-stream-backpressure-invariant"
---

# Axum 0.8 Tower Zero-Copy Body Stream Backpressure Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Buffering Inbound Request Bodies into Unbounded Memory Buffers Without Transport Backpressure

## System Constraints
You are a Principal Rust Architect enforcing zero-copy body stream backpressure in Axum 0.8 and Tower architectures. You must prevent Out-Of-Memory (OOM) vulnerabilities by guaranteeing that inbound multi-gigabyte streams are never collected eagerly into RAM, but are instead consumed via frame-level stream adapters that propagate pull-based backpressure directly to upstream TCP/HTTP2 flow control windows.

## Strict Guidelines
- Engineers MUST ALWAYS consume incoming payload bodies using `body.into_data_stream()` or `tokio_util::io::StreamReader` to preserve pull-based backpressure.
- Engineers MUST NOT invoke `axum::body::to_bytes` or aggregate request bodies into `Vec<u8>` or `BytesMut` on endpoints that accept arbitrary or multi-gigabyte payloads.
- Code SHOULD forward streaming `Bytes` chunks directly to non-blocking I/O sinks via `tokio::io::copy` or bounded Tokio channels without intermediate clones.
- Services MUST enforce strict transport-level size ceilings using `axum::extract::DefaultBodyLimit::disable()` paired with custom stream-level limit guards like `http_body_util::Limited`.
- Components NEVER buffer chunk allocations before sink readiness; the upstream socket read MUST stall when the downstream sink is blocked or saturated.

## Bad vs Good Implementations
### Zero-Copy Backpressured Stream Ingest vs. Eager Memory Buffering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `axum::body::to_bytes` with `usize::MAX` causes the entire request body to be buffered in heap memory. If clients upload multi-gigabyte files or many concurrent payloads arrive, the service will trigger an Out-Of-Memory (OOM) panic, completely defeating HTTP/2 window update backpressure.
```rust
use axum::{body::to_bytes, extract::Request, response::IntoResponse, http::StatusCode};

pub async fn ingest_payload_bad(request: Request) -> Result<impl IntoResponse, StatusCode> {
    // VIOLATION: Eagerly collects multi-gigabyte payloads into application memory.
    // Bypasses TCP flow control and exhausts system memory under concurrent requests.
    let body = request.into_body();
    let bytes = to_bytes(body, usize::MAX)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    tokio::fs::write("/tmp/upload.bin", &bytes)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(StatusCode::CREATED)
}
```

#### Production Standard (Correct)
> **Standard**: Converts the Axum body into a data stream and wraps it into a `tokio_util::io::StreamReader`. `tokio::io::copy` operates with a fixed internal buffer (typically 8KB), pulling from the network socket only as fast as the local disk can write, thereby propagating backpressure directly to upstream TCP/HTTP2 frames.
```rust
use axum::{body::Body, extract::Request, response::IntoResponse, http::StatusCode};
use futures_util::TryStreamExt;
use std::io;
use tokio::fs::File;
use tokio_util::io::StreamReader;

pub async fn ingest_payload_good(request: Request<Body>) -> Result<impl IntoResponse, StatusCode> {
    // INVARIANT: Body is converted into a zero-copy data stream.
    // Backpressure propagates through Tokio StreamReader to TCP/HTTP2 windows.
    let stream = request.into_body().into_data_stream();
    let io_stream = stream.map_err(|err| io::Error::new(io::ErrorKind::Other, err));
    let mut reader = StreamReader::new(io_stream);

    let mut file = File::create("/tmp/upload.bin")
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    tokio::io::copy(&mut reader, &mut file)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(StatusCode::CREATED)
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Tower Zero-Copy Body Stream Backpressure Invariant

Axum 0.8 Tower Zero-Copy Body Stream Backpressure Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict end-to-end asynchronous backpressure across Axum 0.8 and Tower service pipelines to prevent unbounded memory growth during multi-gigabyte payload ingests. Prohibits eager body collection into heap buffers, mandating zero-copy streaming directly from the transport layer into rate-governed sinks to maintain HTTP/2 and TCP receive window constraints. 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: Buffering Inbound Request Bodies into Unbounded Memory Buffers Without Transport Backpressure 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 DriftBuffering Inbound Request Bodies into Unbounded Memory Buffers Without Transport BackpressureCritical
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 consume incoming payload bodies using `body.into_data_stream()` or `tokio_util

Engineers MUST ALWAYS consume incoming payload bodies using `body.into_data_stream()` or `tokio_util::io::StreamReader` to preserve pull-based backpressure.

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` or aggregate request bodies into `Vec<u8>` or `BytesMut` on endpoints that accept arbitrary or multi-gigabyte payloads.

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

Code SHOULD forward streaming `Bytes` chunks directly to non-blocking I/O sinks via `tokio

Code SHOULD forward streaming `Bytes` chunks directly to non-blocking I/O sinks via `tokio::io::copy` or bounded Tokio channels without intermediate clones.

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

Services MUST enforce strict transport-level size ceilings using `axum

Services MUST enforce strict transport-level size ceilings using `axum::extract::DefaultBodyLimit::disable()` paired with custom stream-level limit guards like `http_body_util::Limited`.

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 chunk allocations before sink readiness

Components NEVER buffer chunk allocations before sink readiness; the upstream socket read MUST stall when the downstream sink is blocked or saturated.

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 Tower Zero-Copy Body Stream Backpressure Invariant critical for AI coding assistants?

Enforces strict end-to-end asynchronous backpressure across Axum 0.8 and Tower service pipelines to prevent unbounded memory growth during multi-gigabyte payload ingests. Prohibits eager body collection into heap buffers, mandating zero-copy streaming directly from the transport layer into rate-governed sinks to maintain HTTP/2 and TCP receive window constraints. 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 (Buffering Inbound Request Bodies into Unbounded Memory Buffers Without Transport Backpressure) 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