This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-tower-frame-budgeted-streaming-invariant

Axum 0.8 / Tower Deterministic Frame-Budgeted Multipart Streaming Invariant

Enforces strict frame and memory budgeting on incoming multipart request streams within Axum 0.8 and Tower services. Prevents heap exhaustion and uncontrolled resource consumption triggered by unbuffered or malicious HTTP/3 DATA frame bursts by decoupling zero-copy network frames from unbounded heap allocators and asserting deterministic backpressure-aware quotas.

Prohibited Anti-Pattern: Unbounded Stream Ingestion and Naive Multipart Unwrapping Permitting HTTP/3 Frame Amplification OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 / Tower Deterministic Frame-Budgeted Multipart Streaming Invariant - Enforces strict frame and memory budgeting on incoming multipart request streams within Axum 0.8 and Tower services. Prevents heap exhaustion and uncontrolled resource consumption triggered by unbuffered or malicious HTTP/3 DATA frame bursts by decoupling zero-copy network frames from unbounded heap allocators and asserting deterministic backpressure-aware quotas.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-tower-frame-budgeted-streaming-invariant"
---

# Axum 0.8 / Tower Deterministic Frame-Budgeted Multipart Streaming Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Stream Ingestion and Naive Multipart Unwrapping Permitting HTTP/3 Frame Amplification OOM

## System Constraints
You are a Principal Systems and Security Architect enforcing Axum 0.8 and Tower invariants for mission-critical HTTP/3 streaming. Mandate strict frame budgets, bounded streaming extraction, and zero-allocation chunk consumption to eliminate memory exhaustion vectors.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit byte and frame budgets at the Tower layer using `http_body_util::Limited` or Axum's `DefaultBodyLimit::disable` combined with explicit per-field bounded streams.
- Engineers MUST NOT rely on default `Multipart::next_field` without an ambient or field-scoped size limit; raw frame extraction without byte counters allows an attacker to stream infinite single-field payloads.
- Services MUST apply cooperative backpressure by polling body frames with bounded capacity buffers rather than collecting chunks into intermediate `Vec<u8>` or `BytesMut` structures without hard ceilings.
- Engineers MUST configure Tower's `ServiceBuilder` with connection-level and stream-level concurrency barriers (e.g., `tower::limit::ConcurrencyLimit`) to prevent parallel HTTP/3 multi-stream amplification.
- Handlers MUST map quota and frame-budget violations deterministically to `StatusCode::PAYLOAD_TOO_LARGE` (413) without draining remaining trailing frames from the offending socket.

## Bad vs Good Implementations
### Multipart Ingestion: Unbounded Collection vs. Frame-Budgeted Stream Processing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler polls incoming chunks directly into an unbounded Vec<u8> across the multipart field. A client streaming high-throughput HTTP/3 DATA frames without a specified Content-Length can exploit connection-level flow control to cause rapid heap exhaustion and crash the process via the OOM killer.
```rust
use axum::extract::Multipart;
use axum::http::StatusCode;
use axum::response::IntoResponse;

// ANTI-PATTERN: Ingests chunks directly without frame budgets or field limits.
// Under HTTP/3, malicious peer sends infinite DATA frames, exhausting memory.
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 mut accumulated_bytes = Vec::new();
        
        // Unbounded accumulation directly into host heap
        while let Some(chunk) = field.chunk().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? {
            accumulated_bytes.extend_from_slice(&chunk);
        }
        
        tokio::fs::write("/tmp/upload.bin", &accumulated_bytes)
            .await
            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    }
    
    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: The compliant implementation enforces dual constraints: each received chunk is verified against a 64 KiB frame budget (`MAX_CHUNK_LIMIT`) and total field consumption is monotonically checked against a strict 10 MiB limit (`MAX_FIELD_BYTES`). Chunks are streamed directly to disk via `AsyncWriteExt` without unbounded heap buffering, maintaining zero-copy semantics and deterministic backpressure.
```rust
use axum::extract::Multipart;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use tokio::io::AsyncWriteExt;

const MAX_FIELD_BYTES: usize = 10 * 1024 * 1024; // 10 MiB frame budget
const MAX_CHUNK_LIMIT: usize = 64 * 1024;        // 64 KiB zero-copy frame budget

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 mut file = tokio::fs::File::create("/tmp/upload.bin")
            .await
            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            
        let mut total_field_bytes: usize = 0;

        // Enforce deterministic backpressure and frame quota checks
        while let Some(chunk) = field.chunk().await.map_err(|_| StatusCode::BAD_REQUEST)? {
            if chunk.len() > MAX_CHUNK_LIMIT {
                return Err(StatusCode::BAD_REQUEST); // Frame payload exceeds protocol budget
            }
            
            total_field_bytes = total_field_bytes
                .checked_add(chunk.len())
                .ok_or(StatusCode::PAYLOAD_TOO_LARGE)?;
                
            if total_field_bytes > MAX_FIELD_BYTES {
                return Err(StatusCode::PAYLOAD_TOO_LARGE);
            }

            file.write_all(&chunk)
                .await
                .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
        }
    }
    
    Ok(StatusCode::OK)
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 / Tower Deterministic Frame-Budgeted Multipart Streaming Invariant

Axum 0.8 / Tower Deterministic Frame-Budgeted Multipart Streaming Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict frame and memory budgeting on incoming multipart request streams within Axum 0.8 and Tower services. Prevents heap exhaustion and uncontrolled resource consumption triggered by unbuffered or malicious HTTP/3 DATA frame bursts by decoupling zero-copy network frames from unbounded heap allocators and asserting deterministic backpressure-aware quotas. 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 Ingestion and Naive Multipart Unwrapping Permitting HTTP/3 Frame Amplification OOM 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 Ingestion and Naive Multipart Unwrapping Permitting HTTP/3 Frame Amplification OOMCritical
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 enforce explicit byte and frame budgets at the Tower layer using `http_body_util

Engineers MUST ALWAYS enforce explicit byte and frame budgets at the Tower layer using `http_body_util::Limited` or Axum's `DefaultBodyLimit::disable` combined with explicit per-field bounded streams.

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 rely on default `Multipart

Engineers MUST NOT rely on default `Multipart::next_field` without an ambient or field-scoped size limit; raw frame extraction without byte counters allows an attacker to stream infinite single-field payloads.

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

Services MUST apply cooperative backpressure by polling body frames with bounded capacity buffers rather than collecting chunks into intermediate `Vec<u8>` or `BytesMut` structures without hard ceilings.

Services MUST apply cooperative backpressure by polling body frames with bounded capacity buffers rather than collecting chunks into intermediate `Vec<u8>` or `BytesMut` structures without hard ceilings.

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

Engineers MUST configure Tower's `ServiceBuilder` with connection-level and stream-level concurrency barriers (e.g., `tower

Engineers MUST configure Tower's `ServiceBuilder` with connection-level and stream-level concurrency barriers (e.g., `tower::limit::ConcurrencyLimit`) to prevent parallel HTTP/3 multi-stream amplification.

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

Handlers MUST map quota and frame-budget violations deterministically to `StatusCode

Handlers MUST map quota and frame-budget violations deterministically to `StatusCode::PAYLOAD_TOO_LARGE` (413) without draining remaining trailing frames from the offending socket.

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 / Tower Deterministic Frame-Budgeted Multipart Streaming Invariant critical for AI coding assistants?

Enforces strict frame and memory budgeting on incoming multipart request streams within Axum 0.8 and Tower services. Prevents heap exhaustion and uncontrolled resource consumption triggered by unbuffered or malicious HTTP/3 DATA frame bursts by decoupling zero-copy network frames from unbounded heap allocators and asserting deterministic backpressure-aware quotas. 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 Ingestion and Naive Multipart Unwrapping Permitting HTTP/3 Frame Amplification OOM) 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