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

Axum 0.8 Streaming Multipart Byte-Budget Ceiling & Early-Abort Invariant

Enforces strict streaming chunk consumption with explicit byte-budget ceilings on Axum 0.8 multipart extractors to prevent unbounded memory allocation and heap exhaustion. Guarantees deterministic backpressure and explicit early-abort mechanics, eliminating socket buffer starvation and unconsumed TCP stream desynchronization during payload validation failures.

Prohibited Anti-Pattern: Unbounded Field Buffering via field.bytes() and Dangling Socket Starvation on Early Error Abort

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Streaming Multipart Byte-Budget Ceiling & Early-Abort Invariant - Enforces strict streaming chunk consumption with explicit byte-budget ceilings on Axum 0.8 multipart extractors to prevent unbounded memory allocation and heap exhaustion. Guarantees deterministic backpressure and explicit early-abort mechanics, eliminating socket buffer starvation and unconsumed TCP stream desynchronization during payload validation failures.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-multipart-streaming-backpressure"
---

# Axum 0.8 Streaming Multipart Byte-Budget Ceiling & Early-Abort Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Field Buffering via field.bytes() and Dangling Socket Starvation on Early Error Abort

## System Constraints
You are a Principal Rust Architect enforcing memory safety and backpressure invariants in Axum 0.8 services. You must reject any multipart handling that loads unvalidated field payloads into memory via `field.bytes()` or `field.text()` without a pre-allocated byte ceiling. Ensure all multipart fields stream chunks incrementally through bounded buffers, enforce read timeouts to prevent slowloris stalling, and explicitly consume or abort underlying TCP streams when returning early responses to prevent socket buffer desynchronization.

## Strict Guidelines
- Engineers MUST ALWAYS process multipart payloads chunk-by-chunk using `field.chunk().await` rather than eager accumulation methods like `field.bytes()`, unless protected by `axum::extract::DefaultBodyLimit`.
- Engineers MUST maintain an explicit atomic or local byte counter per field and globally per request, immediately terminating stream consumption with `StatusCode::PAYLOAD_TOO_LARGE` if ceilings are breached.
- Code MUST apply `tokio::time::timeout` to individual chunk yield operations to mitigate slowloris attacks and socket read stalls.
- Services MUST ensure early-abort branches either rapidly drain the remaining socket data under a strict throwaway cap or abruptly close the connection to prevent hyper transport buffer leaks.
- Components NEVER collect multipart streams directly into unbounded structures such as `Vec<u8>` or `String` prior to byte-length verification.

## Bad vs Good Implementations
### Unbounded Multipart Buffering vs. Streaming Byte-Budget Backpressure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `field.bytes().await` consumes the entire multipart field into resident memory before checking length. An attacker can exhaust host RAM with a single slow request. Additionally, returning an early `Err` leaves unread data on the wire without a clean transport abort, causing hyper connection state starvation.
```rust
use axum::{extract::Multipart, http::StatusCode, response::IntoResponse};

pub async fn upload_handler(mut multipart: Multipart) -> Result<impl IntoResponse, StatusCode> {
    while let Some(field) = multipart.next_field().await.map_err(|_| StatusCode::BAD_REQUEST)? {
        let name = field.name().unwrap_or_default().to_string();
        
        // CRITICAL FLAW: Reads entire payload into RAM without size budget.
        // An attacker streaming 10GB will cause an immediate Out-Of-Memory (OOM) panic.
        let data = field.bytes().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
        
        if data.len() > 10 * 1024 * 1024 {
            // Returns early, leaving subsequent socket parts unconsumed and hanging.
            return Err(StatusCode::PAYLOAD_TOO_LARGE);
        }
        
        tokio::fs::write(format!("/tmp/{name}"), &data).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    }
    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: Processes each multipart part chunk-by-chunk with bounded backpressure. A strict running byte ceiling triggers immediate termination prior to unbounded RAM allocation, combined with a read timeout to prevent socket starvation.
```rust
use axum::{extract::Multipart, http::StatusCode, response::IntoResponse};
use tokio::io::AsyncWriteExt;
use std::time::Duration;

const MAX_FIELD_BYTES: usize = 10 * 1024 * 1024; // 10 MiB limit
const CHUNK_TIMEOUT: Duration = Duration::from_secs(5);

pub async fn upload_handler(mut multipart: Multipart) -> Result<impl IntoResponse, StatusCode> {
    while let Some(mut field) = multipart.next_field().await.map_err(|_| StatusCode::BAD_REQUEST)? {
        let name = field.name().unwrap_or("unnamed").to_string();
        let mut file = tokio::fs::File::create(format!("/tmp/{name}"))
            .await
            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            
        let mut bytes_received: usize = 0;

        // INVARIANT: Incremental streaming backpressure with explicit budget ceiling
        loop {
            let chunk_res = tokio::time::timeout(CHUNK_TIMEOUT, field.chunk()).await;
            match chunk_res {
                Ok(Ok(Some(chunk))) => {
                    bytes_received += chunk.len();
                    if bytes_received > MAX_FIELD_BYTES {
                        // Proactively drop file handle to clean partial artifact
                        drop(file);
                        let _ = tokio::fs::remove_file(format!("/tmp/{name}")).await;
                        return Err(StatusCode::PAYLOAD_TOO_LARGE);
                    }
                    file.write_all(&chunk)
                        .await
                        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
                }
                Ok(Ok(None)) => break, // EOF reached cleanly for this field
                Ok(Err(_)) => return Err(StatusCode::BAD_REQUEST),
                Err(_) => return Err(StatusCode::REQUEST_TIMEOUT),
            }
        }
        file.flush().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    }
    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 Streaming Multipart Byte-Budget Ceiling & Early-Abort Invariant

Axum 0.8 Streaming Multipart Byte-Budget Ceiling & Early-Abort Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict streaming chunk consumption with explicit byte-budget ceilings on Axum 0.8 multipart extractors to prevent unbounded memory allocation and heap exhaustion. Guarantees deterministic backpressure and explicit early-abort mechanics, eliminating socket buffer starvation and unconsumed TCP stream desynchronization during payload validation failures. 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 Field Buffering via field.bytes() and Dangling Socket Starvation on Early Error Abort 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 Field Buffering via field.bytes() and Dangling Socket Starvation on Early Error AbortCritical
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 process multipart payloads chunk-by-chunk using `field.chunk().await` rather than eager accumulation methods like `field.bytes()`, unless protected by `axum

Engineers MUST ALWAYS process multipart payloads chunk-by-chunk using `field.chunk().await` rather than eager accumulation methods like `field.bytes()`, unless protected by `axum::extract::DefaultBodyLimit`.

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 maintain an explicit atomic or local byte counter per field and globally per request, immediately terminating stream consumption with `StatusCode

Engineers MUST maintain an explicit atomic or local byte counter per field and globally per request, immediately terminating stream consumption with `StatusCode::PAYLOAD_TOO_LARGE` if ceilings are breached.

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 apply `tokio

Code MUST apply `tokio::time::timeout` to individual chunk yield operations to mitigate slowloris attacks and socket read stalls.

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 early-abort branches either rapidly drain the remaining socket data under a strict throwaway cap or abruptly close the connection to prevent hyper transport buffer leaks.

Services MUST ensure early-abort branches either rapidly drain the remaining socket data under a strict throwaway cap or abruptly close the connection to prevent hyper transport buffer leaks.

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 collect multipart streams directly into unbounded structures such as `Vec<u8>` or `String` prior to byte-length verification.

Components NEVER collect multipart streams directly into unbounded structures such as `Vec<u8>` or `String` prior to byte-length verification.

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 Streaming Multipart Byte-Budget Ceiling & Early-Abort Invariant critical for AI coding assistants?

Enforces strict streaming chunk consumption with explicit byte-budget ceilings on Axum 0.8 multipart extractors to prevent unbounded memory allocation and heap exhaustion. Guarantees deterministic backpressure and explicit early-abort mechanics, eliminating socket buffer starvation and unconsumed TCP stream desynchronization during payload validation failures. 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 Field Buffering via field.bytes() and Dangling Socket Starvation on Early Error Abort) 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