This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-cancel-safe-body-extraction-drain-standard

Axum 0.8 Cancel-Safe Body Extraction and Drain Standard

Enforces deterministic cancellation safety and complete HTTP body consumption when processing chunked or multipart streams in Axum 0.8 / Hyper 1.0. Prevents half-open TCP socket leaks, uncollected connection pools, and downstream backpressure deadlocks resulting from client aborts or unhandled error early-returns.

Prohibited Anti-Pattern: Partial body reads and naked select! loops triggering Hyper 1.0 socket exhaustion on early client termination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Cancel-Safe Body Extraction and Drain Standard - Enforces deterministic cancellation safety and complete HTTP body consumption when processing chunked or multipart streams in Axum 0.8 / Hyper 1.0. Prevents half-open TCP socket leaks, uncollected connection pools, and downstream backpressure deadlocks resulting from client aborts or unhandled error early-returns.
globs: src/**/*.rs, crates/**/*.rs, tests/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-cancel-safe-body-extraction-drain-standard"
---

# Axum 0.8 Cancel-Safe Body Extraction and Drain Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Partial body reads and naked select! loops triggering Hyper 1.0 socket exhaustion on early client termination

## System Constraints
You are a Principal Rust Systems Architect enforcing strict cancel-safe body extraction and stream drainage in Axum 0.8 services. You must forbid naked `tokio::select!` calls over stream extractors, unconstrained `axum::body::Body` drops, and missing error-path body drains. Mandate explicit graceful connection shutdown semantics, scoped token validation before body extraction, and deterministic consumption using `http_body_util::BodyExt`.

## Strict Guidelines
- Engineers MUST ALWAYS validate headers, authentication tokens, and payload quotas BEFORE invoking body extractors or polling stream data.
- Engineers MUST NOT drop an active `axum::body::Body` or `axum::extract::Multipart` stream on error without either fully consuming remaining bytes or explicitly dropping the underlying connection via `hyper::upgrade` or returning an explicit HTTP 4xx/5xx response with `Connection: close`.
- Engineers MUST ALWAYS ensure any asynchronous branch within `tokio::select!` operating on a body stream is strictly cancel-safe; partially consumed chunks MUST NOT cause corrupted state or hanging resource locks.
- Services MUST utilize `http_body_util::BodyExt` and bounded buffers via `Limited` to prevent unmetered memory consumption and unbounded chunked transfer DOS vectors.
- Components NEVER assume dropping an Axum 0.8 request body automatically releases the TCP connection cleanly under chunked transfer-encoding; incomplete frames cause Hyper 1.0 connection keep-alive protocol violations.

## Bad vs Good Implementations
### Cancel-Unsafe Multipart Stream Processing vs. Guarded Drain with Limit

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an error branch returns early, the remainder of the multipart stream is dropped without draining. Hyper 1.0 cannot reuse the underlying keep-alive connection, leading to socket leaks, backpressure lockup on the reverse proxy, and thread-pool exhaustion under high concurrency.
```rust
use axum::{extract::Multipart, http::StatusCode, response::IntoResponse};

pub async fn upload_handler(mut multipart: Multipart) -> Result<impl IntoResponse, StatusCode> {
    // ANTI-PATTERN: Partially iterates fields. If validation fails mid-stream,
    // returning early drops Multipart while client is still streaming chunks,
    // causing Hyper connection pool leaks and unread socket buffer buildup.
    while let Some(field) = multipart.next_field().await.map_err(|_| StatusCode::BAD_REQUEST)? {
        let name = field.name().unwrap_or_default().to_string();
        let data = field.bytes().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

        if name == "metadata" && data.is_empty() {
            return Err(StatusCode::UNPROCESSABLE_ENTITY); // Drops socket abruptly!
        }
    }
    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: Applies explicit body limits via `Limited`, evaluates auth upfront before touching stream buffers, handles length limit errors deterministically, and appends `Connection: close` headers whenever the body cannot be gracefully exhausted, signaling Hyper to close the TCP connection and avoid hung sockets.
```rust
use axum::{body::Body, extract::Request, http::{header, HeaderMap, StatusCode}, response::{IntoResponse, Response}};
use http_body_util::{BodyExt, Limited};
use tokio_util::sync::CancellationToken;

const MAX_UPLOAD_BYTES: usize = 10 * 1024 * 1024; // 10 MiB

pub async fn upload_handler(request: Request<Body>) -> Result<Response, StatusCode> {
    // 1. Validate request headers before touching the body
    if !request.headers().contains_key(header::AUTHORIZATION) {
        return Ok((StatusCode::UNAUTHORIZED, [("connection", "close")]).into_response());
    }

    let (parts, body) = request.into_parts();
    let mut limited_body = Limited::new(body, MAX_UPLOAD_BYTES);

    // 2. Wrap consumption with explicit cancel-safe draining
    let cancel_token = CancellationToken::new();
    let mut collected = Vec::new();

    while let Some(frame) = limited_body.frame().await {
        match frame {
            Ok(frame) if frame.is_data() => {
                let data = frame.into_data().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
                collected.extend_from_slice(&data);
            }
            Ok(_) => continue, // Trailers or extension frames
            Err(err) if err.is::<http_body_util::LengthLimitError>() => {
                return Ok((StatusCode::PAYLOAD_TOO_LARGE, [(header::CONNECTION, "close")]).into_response());
            }
            Err(_) => {
                return Ok((StatusCode::BAD_REQUEST, [(header::CONNECTION, "close")]).into_response());
            }
        }
    }

    Ok((StatusCode::OK, "Uploaded successfully").into_response())
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Cancel-Safe Body Extraction and Drain Standard

Axum 0.8 Cancel-Safe Body Extraction and Drain Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation safety and complete HTTP body consumption when processing chunked or multipart streams in Axum 0.8 / Hyper 1.0. Prevents half-open TCP socket leaks, uncollected connection pools, and downstream backpressure deadlocks resulting from client aborts or unhandled error early-returns. 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: Partial body reads and naked select! loops triggering Hyper 1.0 socket exhaustion on early client termination 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 DriftPartial body reads and naked select! loops triggering Hyper 1.0 socket exhaustion on early client terminationCritical
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 validate headers, authentication tokens, and payload quotas BEFORE invoking body extractors or polling stream data.

Engineers MUST ALWAYS validate headers, authentication tokens, and payload quotas BEFORE invoking body extractors or polling stream data.

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 drop an active `axum

Engineers MUST NOT drop an active `axum::body::Body` or `axum::extract::Multipart` stream on error without either fully consuming remaining bytes or explicitly dropping the underlying connection via `hyper::upgrade` or returning an explicit HTTP 4xx/5xx response with `Connection: close`.

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

Engineers MUST ALWAYS ensure any asynchronous branch within `tokio

Engineers MUST ALWAYS ensure any asynchronous branch within `tokio::select!` operating on a body stream is strictly cancel-safe; partially consumed chunks MUST NOT cause corrupted state or hanging resource locks.

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 utilize `http_body_util

Services MUST utilize `http_body_util::BodyExt` and bounded buffers via `Limited` to prevent unmetered memory consumption and unbounded chunked transfer DOS vectors.

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 assume dropping an Axum 0.8 request body automatically releases the TCP connection cleanly under chunked transfer-encoding

Components NEVER assume dropping an Axum 0.8 request body automatically releases the TCP connection cleanly under chunked transfer-encoding; incomplete frames cause Hyper 1.0 connection keep-alive protocol violations.

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 Cancel-Safe Body Extraction and Drain Standard critical for AI coding assistants?

Enforces deterministic cancellation safety and complete HTTP body consumption when processing chunked or multipart streams in Axum 0.8 / Hyper 1.0. Prevents half-open TCP socket leaks, uncollected connection pools, and downstream backpressure deadlocks resulting from client aborts or unhandled error early-returns. 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 (Partial body reads and naked select! loops triggering Hyper 1.0 socket exhaustion on early client termination) 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