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

Axum 0.8 Streaming Body Atomic Deadline and Fused-Timeout Invariant

Enforces an absolute, atomic deadline across chunked asynchronous request payload streams in Axum 0.8. Mitigates Slowloris Denial of Service (DoS) attacks and heap exhaustion by wrapping the Body stream in a fused, monotonic timeout that decrements continuously rather than resetting per-chunk.

Prohibited Anti-Pattern: Per-Chunk Timeout Resets Enabling Infinite-Duration Slowloris Payload Streams

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Streaming Body Atomic Deadline and Fused-Timeout Invariant - Enforces an absolute, atomic deadline across chunked asynchronous request payload streams in Axum 0.8. Mitigates Slowloris Denial of Service (DoS) attacks and heap exhaustion by wrapping the Body stream in a fused, monotonic timeout that decrements continuously rather than resetting per-chunk.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-streaming-body-fused-timeout-guardrail"
---

# Axum 0.8 Streaming Body Atomic Deadline and Fused-Timeout Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Per-Chunk Timeout Resets Enabling Infinite-Duration Slowloris Payload Streams

## System Constraints
You are a Principal Rust Systems Architect specializing in Tokio and Axum 0.8 network resilience. You enforce strict streaming invariants against slowloris attacks and heap unboundedness by mandating monotonically decreasing fused deadlines across all Axum request body consumption paths.

## Strict Guidelines
- Engineers MUST ALWAYS bound Axum 0.8 streaming payload consumption with an overarching absolute `tokio::time::Instant` deadline rather than resetting idle timeouts on individual chunk yields.
- Engineers MUST wrap request stream consumption in `tokio::time::timeout_at` or maintain an explicit monotonic deadline budget across successive calls to `http_body_util::BodyStream` or `axum::body::Body::into_data_stream`.
- Engineers MUST enforce an explicit byte limit via `http_body_util::Limited` or Axum's `DefaultBodyLimit` concurrently with the stream timeout to avoid unbounded heap growth from high-bandwidth floods.
- Code SHOULD leverage pinned stream adapters or `tokio-util` fused stream constructs to guarantee stream cancellation occurs immediately upon deadline expiration without dangling open TCP sockets.
- Handlers MUST NOT loop over `body.frame().await` or `StreamExt::next(&mut stream).await` using per-iteration relative `tokio::time::timeout` durations, as this exposes the server to indefinite low-and-slow chunk ingestion.

## Bad vs Good Implementations
### Per-Chunk Relative Timeout Anti-Pattern vs Monotonic Deadline Guardrail in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Applying `tokio::time::timeout(Duration, stream.next())` resets the timer on every successfully received frame. An attacker sending a trickle of single bytes just under the duration threshold holds the connection, thread scheduler resources, and socket buffers open infinitely.
```rust
use axum::{body::Body, response::IntoResponse, http::StatusCode};
use futures_util::StreamExt;
use http_body_util::BodyStream;
use std::time::Duration;
use tokio::time::timeout;

// ANTI-PATTERN: Each chunk resets the 5-second timer.
// An attacker sending 1 byte every 4.9 seconds can stall the connection forever.
pub async fn stream_handler(body: Body) -> Result<impl IntoResponse, StatusCode> {
    let mut stream = BodyStream::new(body);
    let mut total_bytes = Vec::new();

    while let Some(frame_result) = timeout(Duration::from_secs(5), stream.next()).await
        .map_err(|_| StatusCode::REQUEST_TIMEOUT)? 
    {
        let frame = frame_result.map_err(|_| StatusCode::BAD_REQUEST)?;
        if let Some(chunk) = frame.data_ref() {
            total_bytes.extend_from_slice(chunk);
        }
    }

    Ok((StatusCode::OK, format!("Read {} bytes", total_bytes.len())))
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation secures the handler against both bandwidth and slowloris vulnerabilities. It applies `http_body_util::Limited` to cap allocation at 10 MiB, and wraps the entire ingestion loop within `tokio::time::timeout_at(deadline, ...)`, enforcing a strict 30-second atomic budget that never resets regardless of chunk cadence.
```rust
use axum::{body::Body, response::IntoResponse, http::StatusCode};
use futures_util::StreamExt;
use http_body_util::{BodyStream, Limited};
use std::time::Duration;
use tokio::time::{Instant, timeout_at};

const MAX_PAYLOAD_BYTES: usize = 10 * 1024 * 1024; // 10 MiB
const TOTAL_REQUEST_DEADLINE: Duration = Duration::from_secs(30);

pub async fn stream_handler(body: Body) -> Result<impl IntoResponse, StatusCode> {
    let deadline = Instant::now() + TOTAL_REQUEST_DEADLINE;
    
    // Bound memory consumption strictly using Limited
    let limited_body = Limited::new(body, MAX_PAYLOAD_BYTES);
    let mut stream = BodyStream::new(limited_body);
    let mut total_bytes = Vec::new();

    // Bound overall stream consumption duration with an atomic monotonic deadline
    timeout_at(deadline, async {
        while let Some(frame_result) = stream.next().await {
            let frame = frame_result.map_err(|_| StatusCode::BAD_REQUEST)?;
            if let Some(chunk) = frame.data_ref() {
                total_bytes.extend_from_slice(chunk);
            }
        }
        Ok::<(), StatusCode>(())
    })
    .await
    .map_err(|_| StatusCode::REQUEST_TIMEOUT)??;

    Ok((StatusCode::OK, format!("Safely processed {} bytes", total_bytes.len())))
}
```

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 Body Atomic Deadline and Fused-Timeout Invariant

Axum 0.8 Streaming Body Atomic Deadline and Fused-Timeout Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces an absolute, atomic deadline across chunked asynchronous request payload streams in Axum 0.8. Mitigates Slowloris Denial of Service (DoS) attacks and heap exhaustion by wrapping the Body stream in a fused, monotonic timeout that decrements continuously rather than resetting per-chunk. 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: Per-Chunk Timeout Resets Enabling Infinite-Duration Slowloris Payload Streams 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 DriftPer-Chunk Timeout Resets Enabling Infinite-Duration Slowloris Payload StreamsCritical
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 bound Axum 0.8 streaming payload consumption with an overarching absolute `tokio

Engineers MUST ALWAYS bound Axum 0.8 streaming payload consumption with an overarching absolute `tokio::time::Instant` deadline rather than resetting idle timeouts on individual chunk yields.

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 wrap request stream consumption in `tokio

Engineers MUST wrap request stream consumption in `tokio::time::timeout_at` or maintain an explicit monotonic deadline budget across successive calls to `http_body_util::BodyStream` or `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.
3

Engineers MUST enforce an explicit byte limit via `http_body_util

Engineers MUST enforce an explicit byte limit via `http_body_util::Limited` or Axum's `DefaultBodyLimit` concurrently with the stream timeout to avoid unbounded heap growth from high-bandwidth floods.

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

Code SHOULD leverage pinned stream adapters or `tokio-util` fused stream constructs to guarantee stream cancellation occurs immediately upon deadline expiration without dangling open TCP sockets.

Code SHOULD leverage pinned stream adapters or `tokio-util` fused stream constructs to guarantee stream cancellation occurs immediately upon deadline expiration without dangling open TCP sockets.

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 NOT loop over `body.frame().await` or `StreamExt

Handlers MUST NOT loop over `body.frame().await` or `StreamExt::next(&mut stream).await` using per-iteration relative `tokio::time::timeout` durations, as this exposes the server to indefinite low-and-slow chunk ingestion.

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 Body Atomic Deadline and Fused-Timeout Invariant critical for AI coding assistants?

Enforces an absolute, atomic deadline across chunked asynchronous request payload streams in Axum 0.8. Mitigates Slowloris Denial of Service (DoS) attacks and heap exhaustion by wrapping the Body stream in a fused, monotonic timeout that decrements continuously rather than resetting per-chunk. 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 (Per-Chunk Timeout Resets Enabling Infinite-Duration Slowloris Payload Streams) 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