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

Axum/Hyper-v1 Zero-Copy Request Body Cancellation & Memory Invariants

Enforces deterministic socket teardown, zero-copy buffer disposal, and cancellation safety when consuming streaming request bodies in Axum 0.7+ and Hyper 1.x. Prevents worker thread pinning and dangling TCP connections during aborted multipart uploads by enforcing structured drop mechanics and asynchronous backpressure.

Prohibited Anti-Pattern: Buffering multipart payloads or blocking worker threads during stream consumption, bypassing Hyper's cancellation-driven socket reclamation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum/Hyper-v1 Zero-Copy Request Body Cancellation & Memory Invariants - Enforces deterministic socket teardown, zero-copy buffer disposal, and cancellation safety when consuming streaming request bodies in Axum 0.7+ and Hyper 1.x. Prevents worker thread pinning and dangling TCP connections during aborted multipart uploads by enforcing structured drop mechanics and asynchronous backpressure.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-hyper-v1-body-cancellation-invariants"
---

# Axum/Hyper-v1 Zero-Copy Request Body Cancellation & Memory Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Buffering multipart payloads or blocking worker threads during stream consumption, bypassing Hyper's cancellation-driven socket reclamation.

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.7+ and Hyper v1.x zero-copy stream processing invariants. You must prevent thread starvation, unmanaged memory allocation, and socket leaks during premature HTTP stream cancellations.

## Strict Guidelines
- Engineers MUST ALWAYS consume incoming request bodies using async frame streaming (e.g., `http_body_util::BodyExt::frame`) or `tokio_util::io::StreamReader` to uphold zero-copy guarantees.
- Engineers MUST NOT introduce blocking I/O (such as `std::fs` operations or `std::sync` mutexes) inside stream-processing loops; all sinks MUST use non-blocking `tokio::io::AsyncWrite` implementations.
- Code SHOULD rely on Rust's RAII drop semantics for Hyper v1 `Incoming` streams to guarantee that client disconnects trigger immediate socket FIN/RST propagation.
- Services MUST bound chunk allocation and enforce upstream body limits via `axum::extract::DefaultBodyLimit` or tower layers before processing streaming frames.
- Components NEVER buffer entire multi-gigabyte multipart bodies in heap memory (`to_bytes`) prior to validating stream lifecycle or target persistence feasibility.

## Bad vs Good Implementations
### Hyper v1 Zero-Copy Streaming Upload with Async Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using synchronous blocking filesystem calls inside an async stream loop pins the Tokio worker thread. Furthermore, unwrapping frames without cancellation propagation delays socket teardown when the client abruptly disconnects.
```rust
use axum::{extract::Request, response::IntoResponse};
use http_body_util::BodyExt;
use std::fs::File;
use std::io::Write;

pub async fn bad_upload_handler(req: Request) -> impl IntoResponse {
    let mut body = req.into_body();
    // ANTI-PATTERN: std::fs::File blocks Tokio worker threads
    let mut file = File::create("/tmp/upload.bin").unwrap();

    while let Some(frame_res) = body.frame().await {
        let frame = frame_res.unwrap();
        if let Ok(data) = frame.into_data() {
            // Blocking write starves the async reactor; dropped client disconnects
            // are not recognized until the blocking write finishes.
            file.write_all(&data).unwrap();
        }
    }
    "Uploaded"
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to Hyper v1 cancellation invariants by utilizing fully non-blocking asynchronous I/O (`tokio::fs::File`) alongside zero-copy `Bytes` extraction. Aborted connections drop the stream future, cleanly closing the TCP session and reclaiming buffer memory without pinning executor threads.
```rust
use axum::{extract::Request, http::StatusCode, response::IntoResponse};
use http_body_util::BodyExt;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

pub async fn good_upload_handler(req: Request) -> Result<impl IntoResponse, StatusCode> {
    let mut body = req.into_body();
    let mut file = File::create("/tmp/upload.bin")
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Hyper v1 BodyExt::frame yields zero-copy Bytes frames.
    // Dropping this future on client disconnect drops the underlying Hyper body,
    // instantly releasing socket buffers and reclaiming memory without worker stalling.
    while let Some(frame_result) = body.frame().await {
        let frame = frame_result.map_err(|_| StatusCode::BAD_REQUEST)?;
        if let Ok(data) = frame.into_data() {
            file.write_all(&data)
                .await
                .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
        }
    }

    file.flush()
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok("Uploaded")
}
```

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/Hyper-v1 Zero-Copy Request Body Cancellation & Memory Invariants

Axum/Hyper-v1 Zero-Copy Request Body Cancellation & Memory Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic socket teardown, zero-copy buffer disposal, and cancellation safety when consuming streaming request bodies in Axum 0.7+ and Hyper 1.x. Prevents worker thread pinning and dangling TCP connections during aborted multipart uploads by enforcing structured drop mechanics and asynchronous backpressure. 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: Buffering multipart payloads or blocking worker threads during stream consumption, bypassing Hyper's cancellation-driven socket reclamation. 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 DriftBuffering multipart payloads or blocking worker threads during stream consumption, bypassing Hyper's cancellation-driven socket reclamation.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 consume incoming request bodies using async frame streaming (e.g., `http_body_util

Engineers MUST ALWAYS consume incoming request bodies using async frame streaming (e.g., `http_body_util::BodyExt::frame`) or `tokio_util::io::StreamReader` to uphold zero-copy guarantees.

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 introduce blocking I/O (such as `std

Engineers MUST NOT introduce blocking I/O (such as `std::fs` operations or `std::sync` mutexes) inside stream-processing loops; all sinks MUST use non-blocking `tokio::io::AsyncWrite` implementations.

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 SHOULD rely on Rust's RAII drop semantics for Hyper v1 `Incoming` streams to guarantee that client disconnects trigger immediate socket FIN/RST propagation.

Code SHOULD rely on Rust's RAII drop semantics for Hyper v1 `Incoming` streams to guarantee that client disconnects trigger immediate socket FIN/RST propagation.

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 bound chunk allocation and enforce upstream body limits via `axum

Services MUST bound chunk allocation and enforce upstream body limits via `axum::extract::DefaultBodyLimit` or tower layers before processing streaming frames.

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 buffer entire multi-gigabyte multipart bodies in heap memory (`to_bytes`) prior to validating stream lifecycle or target persistence feasibility.

Components NEVER buffer entire multi-gigabyte multipart bodies in heap memory (`to_bytes`) prior to validating stream lifecycle or target persistence feasibility.

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/Hyper-v1 Zero-Copy Request Body Cancellation & Memory Invariants critical for AI coding assistants?

Enforces deterministic socket teardown, zero-copy buffer disposal, and cancellation safety when consuming streaming request bodies in Axum 0.7+ and Hyper 1.x. Prevents worker thread pinning and dangling TCP connections during aborted multipart uploads by enforcing structured drop mechanics and asynchronous backpressure. 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 (Buffering multipart payloads or blocking worker threads during stream consumption, bypassing Hyper's cancellation-driven socket reclamation.) 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/Hyper-v1