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

Axum 0.8 Backpressure-Bounded Zero-Allocation Streaming Standard

Mandates strict byte-limit boundaries and end-to-end backpressure propagation across all Axum 0.8 streaming extractors and response pipelines. Prevents catastrophic heap exhaustion, buffer bloat, and slowloris memory DoS vulnerabilities by eliminating unbounded chunk aggregation in Tokio runtimes.

Prohibited Anti-Pattern: Unbounded Request Ingestion and Decoupled Async Stream Buffering

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Backpressure-Bounded Zero-Allocation Streaming Standard - Mandates strict byte-limit boundaries and end-to-end backpressure propagation across all Axum 0.8 streaming extractors and response pipelines. Prevents catastrophic heap exhaustion, buffer bloat, and slowloris memory DoS vulnerabilities by eliminating unbounded chunk aggregation in Tokio runtimes.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-backpressure-streaming-guardrail"
---

# Axum 0.8 Backpressure-Bounded Zero-Allocation Streaming Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Request Ingestion and Decoupled Async Stream Buffering

## System Constraints
You are a Principal Software Architect enforcing the Axum 0.8 Backpressure-Bounded Zero-Allocation Streaming Standard. You must strictly forbid unbounded payload accumulation, naive Vec<u8> chunk appending, and decoupled memory buffering in Tokio runtimes. You must enforce explicit byte capping via axum::body::to_bytes or tower-http limits, and mandate direct backpressure-propagating streaming using StreamReader and bounded sinks.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit byte limits when consuming incoming request bodies using axum::body::to_bytes(body, MAX_LIMIT) or tower_http::limit::RequestBodyLimitLayer.
- Engineers MUST NEVER aggregate incoming stream frames into an unbounded Vec<u8> or BytesMut collection inside an asynchronous handler loop.
- Pipelines streaming request payloads to external sinks (such as S3 or local files) MUST propagate backpressure directly using tokio_util::io::StreamReader and tokio::io::copy without intermediate heap staging.
- Handlers MUST immediately terminate streaming and return StatusCode::PAYLOAD_TOO_LARGE (HTTP 413) the moment an incoming payload exceeds configured hard bounds.
- Background worker handoffs MUST NEVER use unbounded mpsc channels; channels MUST be bounded and handlers MUST await permit acquisition or channel capacity to prevent memory bloat under downstream lag.

## Bad vs Good Implementations
### Payload Ingestion: Unbounded Collection vs. Memory-Bounded Stream Sink

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler consumes the entire request body into a growing in-memory Vec<u8> without enforcing any maximum size or byte limit. An attacker can stream gigabytes of data slowly or rapidly, exhausting system memory, starving the Tokio allocator, and crashing the service.
```rust
use axum::{body::Body, extract::Request, http::StatusCode, response::IntoResponse};
use futures_util::StreamExt;

pub async fn upload_handler(req: Request<Body>) -> Result<impl IntoResponse, StatusCode> {
    let mut stream = req.into_body().into_data_stream();
    let mut aggregated_data = Vec::new();

    // VULNERABILITY: Unbounded in-memory allocation accumulates arbitrary payload sizes.
    // Bypasses backpressure, inviting Heap Exhaustion DoS and OOM panics.
    while let Some(chunk_result) = stream.next().await {
        let chunk = chunk_result.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
        aggregated_data.extend_from_slice(&chunk);
    }

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

    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: Directly links incoming chunks to the file sink via StreamReader without heap accumulation. The AsyncReadExt::take adapter strictly bounds reading to the byte ceiling and terminates with HTTP 413 if the client violates bounds, preserving Tokio runtime memory stability.
```rust
use axum::{body::Body, extract::Request, http::StatusCode, response::IntoResponse};
use futures_util::TryStreamExt;
use tokio::fs::File;
use tokio_util::io::StreamReader;

const MAX_UPLOAD_LIMIT_BYTES: u64 = 10 * 1024 * 1024; // 10 MiB limit

pub async fn upload_handler(req: Request<Body>) -> Result<impl IntoResponse, StatusCode> {
    // Enforce backpressure and bounded stream transformation
    let body = req.into_body();
    let byte_stream = body.into_data_stream().map_err(|err| {
        std::io::Error::new(std::io::ErrorKind::Other, err)
    });

    let mut stream_reader = StreamReader::new(byte_stream);
    let mut destination = File::create("/tmp/upload.bin")
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Pipe data directly with backpressure; cap memory and total bytes written
    let mut bounded_reader = tokio::io::AsyncReadExt::take(&mut stream_reader, MAX_UPLOAD_LIMIT_BYTES + 1);
    let bytes_copied = tokio::io::copy(&mut bounded_reader, &mut destination)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    if bytes_copied > MAX_UPLOAD_LIMIT_BYTES {
        let _ = tokio::fs::remove_file("/tmp/upload.bin").await;
        return Err(StatusCode::PAYLOAD_TOO_LARGE);
    }

    Ok(StatusCode::OK)
}
```

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 Backpressure-Bounded Zero-Allocation Streaming Standard

Axum 0.8 Backpressure-Bounded Zero-Allocation Streaming Standard defines an industrial-grade behavioral standard for backend engineering. Mandates strict byte-limit boundaries and end-to-end backpressure propagation across all Axum 0.8 streaming extractors and response pipelines. Prevents catastrophic heap exhaustion, buffer bloat, and slowloris memory DoS vulnerabilities by eliminating unbounded chunk aggregation in Tokio runtimes. 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 Request Ingestion and Decoupled Async Stream Buffering 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 Request Ingestion and Decoupled Async Stream BufferingCritical
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 when consuming incoming request bodies using axum

Engineers MUST ALWAYS enforce explicit byte limits when consuming incoming request bodies using axum::body::to_bytes(body, MAX_LIMIT) or tower_http::limit::RequestBodyLimitLayer.

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 NEVER aggregate incoming stream frames into an unbounded Vec<u8> or BytesMut collection inside an asynchronous handler loop.

Engineers MUST NEVER aggregate incoming stream frames into an unbounded Vec<u8> or BytesMut collection inside an asynchronous handler loop.

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

Pipelines streaming request payloads to external sinks (such as S3 or local files) MUST propagate backpressure directly using tokio_util

Pipelines streaming request payloads to external sinks (such as S3 or local files) MUST propagate backpressure directly using tokio_util::io::StreamReader and tokio::io::copy without intermediate heap staging.

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 return StatusCode

Handlers MUST immediately terminate streaming and return StatusCode::PAYLOAD_TOO_LARGE (HTTP 413) the moment an incoming payload exceeds configured hard bounds.

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

Background worker handoffs MUST NEVER use unbounded mpsc channels

Background worker handoffs MUST NEVER use unbounded mpsc channels; channels MUST be bounded and handlers MUST await permit acquisition or channel capacity to prevent memory bloat under downstream lag.

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 Backpressure-Bounded Zero-Allocation Streaming Standard critical for AI coding assistants?

Mandates strict byte-limit boundaries and end-to-end backpressure propagation across all Axum 0.8 streaming extractors and response pipelines. Prevents catastrophic heap exhaustion, buffer bloat, and slowloris memory DoS vulnerabilities by eliminating unbounded chunk aggregation in Tokio runtimes. 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 Request Ingestion and Decoupled Async Stream Buffering) 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