This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-bounded-body-streaming-task-cancellation

Axum 0.8 Bounded Body Streaming and Task Cancellation Guardrail

Enforces deterministic bounded streaming and task cancellation semantics in Axum 0.8 HTTP services. Guarantees immediate reclamation of intermediate request body buffers and aborts background processing upon client disconnect, eliminating silent Tokio task leakage and memory amplification under high concurrency.

Prohibited Anti-Pattern: Unbounded Stream Buffering and Detached Tokio Tasks Leading to Memory Amplification and Silent Task Leakage on Client Disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Bounded Body Streaming and Task Cancellation Guardrail - Enforces deterministic bounded streaming and task cancellation semantics in Axum 0.8 HTTP services. Guarantees immediate reclamation of intermediate request body buffers and aborts background processing upon client disconnect, eliminating silent Tokio task leakage and memory amplification under high concurrency.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-bounded-body-streaming-task-cancellation"
---

# Axum 0.8 Bounded Body Streaming and Task Cancellation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Stream Buffering and Detached Tokio Tasks Leading to Memory Amplification and Silent Task Leakage on Client Disconnect

## System Constraints
You are a Principal Rust Systems Architect enforcing strict memory bounds and cancellation safety in Axum 0.8 services. You MUST mandate explicit stream chunk sizing, hard body limit extractors, deterministic Tokio CancellationToken or JoinHandle::abort wiring, and immediate deallocation of pooled buffers when downstream clients drop HTTP connections.

## Strict Guidelines
- Engineers MUST ALWAYS wrap request bodies in `axum::extract::DefaultBodyLimit::disable()` and explicit `tower_http::limit::RequestBodyLimitLayer` or per-route `axum::extract::Request::into_body()` stream length guards.
- Engineers MUST NEVER spawn detached asynchronous processing via `tokio::spawn` without linking execution to client connection lifecycle via `tokio_util::sync::CancellationToken` or explicit `JoinHandle::abort` RAII guards.
- Code MUST consume incoming bodies using bounded pinned byte streams (e.g., `http_body_util::BodyStream` or `http_body::Body::frame`) rather than accumulating full buffers with `axum::body::to_bytes` without an explicit size cap.
- Services MUST monitor connection termination and drop intermediate buffer allocations (`BytesMut`, pinned ring buffers) immediately when `Stream::poll_next` yields `Poll::Ready(None)` or a network error.
- Components NEVER retain references to large payload allocations across yield points where the parent HTTP request future may be cancelled by Hyper/Axum runtime drops.

## Bad vs Good Implementations
### Streaming Request Body Consumption with Disconnect Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning an unlinked Tokio task discards connection lifecycle tracking. If the client disconnects halfway through upload, the detached task continues reading until EOF or error while allocating memory, causing thread/task accumulation and disk exhaustion.
```rust
use axum::{body::Body, extract::Request, response::IntoResponse};
use futures_util::StreamExt;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

// ANTI-PATTERN: Detached task ignores client disconnect;
// consumes unbounded stream, leaking file handles and heap buffers.
pub async fn bad_upload_handler(req: Request<Body>) -> impl IntoResponse {
    let stream = req.into_body().into_data_stream();
    
    tokio::spawn(async move {
        let mut file = File::create("/tmp/upload.bin").await.unwrap();
        let mut stream = stream;
        while let Some(chunk) = stream.next().await {
            let data = chunk.unwrap();
            file.write_all(&data).await.unwrap();
        }
    });

    axum::http::StatusCode::ACCEPTED
}
```

#### Production Standard (Correct)
> **Standard**: The streaming consumption is directly awaited inside the request lifecycle future without detached spawning. If the client abruptly severs the connection, Axum drops the handler future instantly, deallocating the in-flight chunk buffer and terminating disk writes.
```rust
use axum::{body::Body, extract::Request, http::StatusCode, response::IntoResponse};
use futures_util::StreamExt;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use tokio_util::sync::CancellationToken;

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

// PRODUCTION FIX: Cancellation-aware inline processing with bounded stream and atomic abort
pub async fn good_upload_handler(req: Request<Body>) -> Result<impl IntoResponse, StatusCode> {
    let token = CancellationToken::new();
    let _drop_guard = token.clone().drop_guard();

    let mut stream = req.into_body().into_data_stream();
    let mut file = File::create("/tmp/upload.bin").await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    let mut total_bytes = 0usize;

    // Invariant: Handler runs within the Axum request future;
    // if the client disconnects, Axum drops this future immediately.
    while let Some(chunk_res) = stream.next().await {
        let chunk = chunk_res.map_err(|_| StatusCode::BAD_REQUEST)?;
        total_bytes += chunk.len();
        
        if total_bytes > MAX_FILE_SIZE {
            return Err(StatusCode::PAYLOAD_TOO_LARGE);
        }
        
        file.write_all(&chunk).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    }

    file.flush().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok((StatusCode::OK, "Upload complete"))
}
```

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 Bounded Body Streaming and Task Cancellation Guardrail

Axum 0.8 Bounded Body Streaming and Task Cancellation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic bounded streaming and task cancellation semantics in Axum 0.8 HTTP services. Guarantees immediate reclamation of intermediate request body buffers and aborts background processing upon client disconnect, eliminating silent Tokio task leakage and memory amplification under high concurrency. 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 and Detached Tokio Tasks Leading to Memory Amplification and Silent Task Leakage on Client Disconnect 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 and Detached Tokio Tasks Leading to Memory Amplification and Silent Task Leakage on Client DisconnectCritical
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 wrap request bodies in `axum

Engineers MUST ALWAYS wrap request bodies in `axum::extract::DefaultBodyLimit::disable()` and explicit `tower_http::limit::RequestBodyLimitLayer` or per-route `axum::extract::Request::into_body()` stream length 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.
2

Engineers MUST NEVER spawn detached asynchronous processing via `tokio

Engineers MUST NEVER spawn detached asynchronous processing via `tokio::spawn` without linking execution to client connection lifecycle via `tokio_util::sync::CancellationToken` or explicit `JoinHandle::abort` RAII 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.
3

Code MUST consume incoming bodies using bounded pinned byte streams (e.g., `http_body_util

Code MUST consume incoming bodies using bounded pinned byte streams (e.g., `http_body_util::BodyStream` or `http_body::Body::frame`) rather than accumulating full buffers with `axum::body::to_bytes` without an explicit size cap.

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 monitor connection termination and drop intermediate buffer allocations (`BytesMut`, pinned ring buffers) immediately when `Stream

Services MUST monitor connection termination and drop intermediate buffer allocations (`BytesMut`, pinned ring buffers) immediately when `Stream::poll_next` yields `Poll::Ready(None)` or a network error.

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 retain references to large payload allocations across yield points where the parent HTTP request future may be cancelled by Hyper/Axum runtime drops.

Components NEVER retain references to large payload allocations across yield points where the parent HTTP request future may be cancelled by Hyper/Axum runtime drops.

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 Bounded Body Streaming and Task Cancellation Guardrail critical for AI coding assistants?

Enforces deterministic bounded streaming and task cancellation semantics in Axum 0.8 HTTP services. Guarantees immediate reclamation of intermediate request body buffers and aborts background processing upon client disconnect, eliminating silent Tokio task leakage and memory amplification under high concurrency. 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 and Detached Tokio Tasks Leading to Memory Amplification and Silent Task Leakage on Client Disconnect) 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