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

Axum 0.8 Cancel-Safe Body Stream Flow Control Standard

Enforces strict cancellation safety and backpressure guarantees when consuming Axum 0.8 request body streams on Tokio runtimes. Prevents unconsumed payload buffer accumulation, lingering socket descriptors, and corrupted or poisoned shared synchronization states when client connections abruptly terminate mid-stream. Mandates explicit RAII cleanup and isolation of asynchronous lock guards from stream ingestion poll loops.

Prohibited Anti-Pattern: Holding async synchronization guards across unbuffered body chunk awaits and neglecting drop-safety during premature client termination.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Cancel-Safe Body Stream Flow Control Standard - Enforces strict cancellation safety and backpressure guarantees when consuming Axum 0.8 request body streams on Tokio runtimes. Prevents unconsumed payload buffer accumulation, lingering socket descriptors, and corrupted or poisoned shared synchronization states when client connections abruptly terminate mid-stream. Mandates explicit RAII cleanup and isolation of asynchronous lock guards from stream ingestion poll loops.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-cancel-safe-stream-guardrail"
---

# Axum 0.8 Cancel-Safe Body Stream Flow Control Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Holding async synchronization guards across unbuffered body chunk awaits and neglecting drop-safety during premature client termination.

## System Constraints
You are a Principal Rust Systems Architect enforcing the Axum 0.8 Cancel-Safe Body Stream Flow Control Standard. You must rigorously reject any patterns where synchronization guards (such as tokio::sync::Mutex or transaction handles) are held across body stream read points, or where body frames are consumed in `tokio::select!` branches without explicit cancellation rollback mechanics. Require all body consumption to adhere to strict backpressure, cancellation-safe state machines, and proper resource deallocation upon unexpected future drop.

## Strict Guidelines
- Engineers MUST ALWAYS isolate asynchronous lock acquisitions (`tokio::sync::MutexGuard`, database transactions) from body streaming loops (`http_body_util::BodyStream`, `axum::body::Body::into_data_stream`).
- Engineers MUST NOT hold shared state locks or transaction write locks across `.frame().await` or `.next().await` invocations where client disconnects can drop the future.
- Code MUST employ bounded buffers (`tokio::sync::mpsc::channel` with explicit capacity) when decoupling stream readers from downstream storage or processing workers.
- Services MUST ensure that temporary files or chunk buffers registered during streaming implement the RAII pattern (e.g., `tempfile::NamedTempFile`) so unlinked artifacts are immediately purged if dropped midway.
- Components NEVER assume a streaming request will reach EOF; all state updates driven by streamed data MUST be staged and atomically committed only after stream completion.

## Bad vs Good Implementations
### Decoupling Stream Ingestion from Synchronized State

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Acquiring a `tokio::sync::MutexGuard` before iterating over `stream.next().await` causes the lock to be held across variable network latency and client idle time. If the client abruptly drops the connection, the future is dropped inside the while loop, potentially leaving partially ingested, inconsistent state in the shared vector and blocking other tasks for excessive durations.
```rust
use axum::extract::BodyStream;
use futures_util::StreamExt;
use std::sync::Arc;
use tokio::sync::Mutex;

pub async fn ingest_payload(
    state: Arc<Mutex<Vec<u8>>>,
    mut stream: BodyStream,
) -> Result<(), axum::http::StatusCode> {
    // VIOLATION: Holding async mutex across network stream yields.
    // If client disconnects or times out, the lock is held until drop,
    // and any interleaved select! or error handling leaves partial state.
    let mut lock = state.lock().await;
    while let Some(chunk) = stream.next().await {
        let data = chunk.map_err(|_| axum::http::StatusCode::BAD_REQUEST)?;
        lock.extend_from_slice(&data);
    }
    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: The good example decouples network I/O from synchronization by buffering into an isolated, capacity-capped local buffer. If the client disconnects, the future is dropped cleanly without contaminating the shared state or holding locks across idle TCP frames. The lock is held only for an atomic, in-memory mutation that cannot be interrupted by network cancellation.
```rust
use axum::body::Body;
use http_body_util::BodyExt;
use std::sync::Arc;
use tokio::sync::Mutex;

pub async fn ingest_payload(
    state: Arc<Mutex<Vec<u8>>>,
    body: Body,
) -> Result<(), axum::http::StatusCode> {
    // INVARIANT: Consume stream into an isolated local buffer with a strict size limit
    // before acquiring the synchronization lock.
    const MAX_ALLOWED_BYTES: usize = 10 * 1024 * 1024; // 10 MiB limit
    let mut stream = body.into_data_stream();
    let mut staged_buffer = Vec::new();

    while let Some(chunk_res) = stream.next().await {
        let chunk = chunk_res.map_err(|_| axum::http::StatusCode::BAD_REQUEST)?;
        if staged_buffer.len() + chunk.len() > MAX_ALLOWED_BYTES {
            return Err(axum::http::StatusCode::PAYLOAD_TOO_LARGE);
        }
        staged_buffer.extend_from_slice(&chunk);
    }

    // Lock is acquired ONLY for the deterministic, non-yielding in-memory update
    let mut lock = state.lock().await;
    lock.extend_from_slice(&staged_buffer);
    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 Cancel-Safe Body Stream Flow Control Standard

Axum 0.8 Cancel-Safe Body Stream Flow Control Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict cancellation safety and backpressure guarantees when consuming Axum 0.8 request body streams on Tokio runtimes. Prevents unconsumed payload buffer accumulation, lingering socket descriptors, and corrupted or poisoned shared synchronization states when client connections abruptly terminate mid-stream. Mandates explicit RAII cleanup and isolation of asynchronous lock guards from stream ingestion poll loops. 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: Holding async synchronization guards across unbuffered body chunk awaits and neglecting drop-safety during premature 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 DriftHolding async synchronization guards across unbuffered body chunk awaits and neglecting drop-safety during premature client termination.Critical
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 isolate asynchronous lock acquisitions (`tokio

Engineers MUST ALWAYS isolate asynchronous lock acquisitions (`tokio::sync::MutexGuard`, database transactions) from body streaming loops (`http_body_util::BodyStream`, `axum::body::Body::into_data_stream`).

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 hold shared state locks or transaction write locks across `.frame().await` or `.next().await` invocations where client disconnects can drop the future.

Engineers MUST NOT hold shared state locks or transaction write locks across `.frame().await` or `.next().await` invocations where client disconnects can drop the future.

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 employ bounded buffers (`tokio

Code MUST employ bounded buffers (`tokio::sync::mpsc::channel` with explicit capacity) when decoupling stream readers from downstream storage or processing workers.

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 ensure that temporary files or chunk buffers registered during streaming implement the RAII pattern (e.g., `tempfile

Services MUST ensure that temporary files or chunk buffers registered during streaming implement the RAII pattern (e.g., `tempfile::NamedTempFile`) so unlinked artifacts are immediately purged if dropped midway.

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 a streaming request will reach EOF

Components NEVER assume a streaming request will reach EOF; all state updates driven by streamed data MUST be staged and atomically committed only after stream completion.

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 Stream Flow Control Standard critical for AI coding assistants?

Enforces strict cancellation safety and backpressure guarantees when consuming Axum 0.8 request body streams on Tokio runtimes. Prevents unconsumed payload buffer accumulation, lingering socket descriptors, and corrupted or poisoned shared synchronization states when client connections abruptly terminate mid-stream. Mandates explicit RAII cleanup and isolation of asynchronous lock guards from stream ingestion poll loops. 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 (Holding async synchronization guards across unbuffered body chunk awaits and neglecting drop-safety during premature 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