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

Axum 0.8 Hyper-Native Streaming Body Backpressure and Abort Teardown

Enforces strict end-to-end backpressure propagation and immediate cancellation propagation across Axum 0.8 / Hyper 1.x streaming pipelines. Forbids unbounded channel buffers (`mpsc::unbounded_channel`) and unmetered in-memory collection (`to_bytes` without limits), guaranteeing deterministic O(1) memory consumption and instant upstream connection teardown when downstream HTTP clients disconnect.

Prohibited Anti-Pattern: Unbounded Channel Buffering and Ignored Cancellation During Hyper Stream Consumption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Hyper-Native Streaming Body Backpressure and Abort Teardown - Enforces strict end-to-end backpressure propagation and immediate cancellation propagation across Axum 0.8 / Hyper 1.x streaming pipelines. Forbids unbounded channel buffers (`mpsc::unbounded_channel`) and unmetered in-memory collection (`to_bytes` without limits), guaranteeing deterministic O(1) memory consumption and instant upstream connection teardown when downstream HTTP clients disconnect.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-hyper-streaming-backpressure-invariant"
---

# Axum 0.8 Hyper-Native Streaming Body Backpressure and Abort Teardown

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Channel Buffering and Ignored Cancellation During Hyper Stream Consumption

## System Constraints
You are a Principal Rust Distributed Systems Architect specializing in Axum 0.8 and Hyper 1.x async I/O runtimes. Enforce strict backpressure and cooperative cancellation on all incoming and outgoing streaming bodies. Reject any pattern that buffers HTTP bodies without static byte caps, relies on unbounded tokio channels, or spawns detached background tasks that continue reading upstream payloads after client TCP disconnects. Require idiomatic use of `http_body_util::BodyStream`, bounded channels with proactive capacity control, and `tokio::select!` cancellation boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS bound downstream buffering by using bounded channels (`tokio::sync::mpsc::channel(N)`) or direct stream adapters (`ReaderStream`, `StreamBody`) rather than intermediate unbounded buffers.
- Engineers MUST NOT call `axum::body::to_bytes` or Hyper body collection without an explicit, deterministic byte limit (`axum::extract::DefaultBodyLimit` or `http_body_util::Limited`).
- Services MUST propagate client socket disconnects immediately to upstream I/O sources by binding the consuming stream lifetime to the request handler future or wiring `tokio::select!` with connection drop guards.
- Code SHOULD leverage `http_body_util::BodyStream` and `tokio_util::io::StreamReader` to transform hyper-native frames without copying memory across task boundaries.
- Components NEVER spawn unlinked `tokio::spawn` tasks that pull from request bodies without an explicit cancellation token or watch channel tied to client liveness.

## Bad vs Good Implementations
### Unbounded Chunk Forwarding vs. Zero-Copy Backpressured Stream Adapter

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning an unlinked background task feeding into `mpsc::unbounded_channel` buffers unlimited data if downstream consumption lags or stalls. Furthermore, if the client disconnects, the spawned task continues consuming upstream network bandwidth and memory, causing unmetered resource leaks.
```rust
use axum::{body::Body, extract::Request, response::Response, http::StatusCode};
use tokio::sync::mpsc;

pub async fn proxy_stream_bad(req: Request) -> Result<Response, StatusCode> {
    let mut body = req.into_body();
    // ANTI-PATTERN: Unbounded buffer destroys backpressure; slow receiver causes OOM
    let (tx, mut rx) = mpsc::unbounded_channel();

    // ANTI-PATTERN: Detached background task ignores client disconnect and leaks memory
    tokio::spawn(async move {
        use http_body_util::BodyExt;
        while let Some(frame_res) = body.frame().await {
            if let Ok(frame) = frame_res {
                if let Some(data) = frame.data_ref() {
                    let _ = tx.send(data.clone());
                }
            }
        }
    });

    let stream = async_stream::stream! {
        while let Some(chunk) = rx.recv().await {
            yield Ok::<_, std::io::Error>(chunk);
        }
    };

    Ok(Response::new(Body::from_stream(stream)))
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes `http_body_util::BodyStream` to maintain native frame backpressure. Memory is consumed in O(1) buffer sizes determined by the TCP socket window. If the client drops connection, Hyper tears down the response body stream, which drops the upstream extractor instantly.
```rust
use axum::{body::Body, extract::Request, response::Response, http::StatusCode};
use http_body_util::BodyStream;
use futures_util::TryStreamExt;

pub async fn proxy_stream_good(req: Request) -> Result<Response, StatusCode> {
    // INVARIANT: Wrap native Axum 0.8 Body in BodyStream directly without unbounded queues
    let body_stream = BodyStream::new(req.into_body());

    // Direct stream mapping preserves Hyper's pull-based backpressure frame-by-frame
    let byte_stream = body_stream.try_filter_map(|frame| async move {
        Ok(frame.into_data().ok())
    });

    // Returning Body::from_stream binds stream consumption directly to the client's socket drain rate.
    // If the client disconnects, the response future drops, instantly dropping `byte_stream` and aborting upstream I/O.
    Ok(Response::new(Body::from_stream(byte_stream)))
}
```

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 Hyper-Native Streaming Body Backpressure and Abort Teardown

Axum 0.8 Hyper-Native Streaming Body Backpressure and Abort Teardown defines an industrial-grade behavioral standard for backend engineering. Enforces strict end-to-end backpressure propagation and immediate cancellation propagation across Axum 0.8 / Hyper 1.x streaming pipelines. Forbids unbounded channel buffers (`mpsc::unbounded_channel`) and unmetered in-memory collection (`to_bytes` without limits), guaranteeing deterministic O(1) memory consumption and instant upstream connection teardown when downstream HTTP clients disconnect. 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 Channel Buffering and Ignored Cancellation During Hyper Stream Consumption 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 Channel Buffering and Ignored Cancellation During Hyper Stream ConsumptionCritical
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 bound downstream buffering by using bounded channels (`tokio

Engineers MUST ALWAYS bound downstream buffering by using bounded channels (`tokio::sync::mpsc::channel(N)`) or direct stream adapters (`ReaderStream`, `StreamBody`) rather than intermediate unbounded buffers.

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 call `axum

Engineers MUST NOT call `axum::body::to_bytes` or Hyper body collection without an explicit, deterministic byte limit (`axum::extract::DefaultBodyLimit` or `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.
3

Services MUST propagate client socket disconnects immediately to upstream I/O sources by binding the consuming stream lifetime to the request handler future or wiring `tokio

Services MUST propagate client socket disconnects immediately to upstream I/O sources by binding the consuming stream lifetime to the request handler future or wiring `tokio::select!` with connection drop guards.

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

Code SHOULD leverage `http_body_util

Code SHOULD leverage `http_body_util::BodyStream` and `tokio_util::io::StreamReader` to transform hyper-native frames without copying memory across task boundaries.

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 spawn unlinked `tokio

Components NEVER spawn unlinked `tokio::spawn` tasks that pull from request bodies without an explicit cancellation token or watch channel tied to client liveness.

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-Native Streaming Body Backpressure and Abort Teardown critical for AI coding assistants?

Enforces strict end-to-end backpressure propagation and immediate cancellation propagation across Axum 0.8 / Hyper 1.x streaming pipelines. Forbids unbounded channel buffers (`mpsc::unbounded_channel`) and unmetered in-memory collection (`to_bytes` without limits), guaranteeing deterministic O(1) memory consumption and instant upstream connection teardown when downstream HTTP clients disconnect. 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 Channel Buffering and Ignored Cancellation During Hyper Stream Consumption) 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