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

Axum 0.8 & Hyper-v1 Flow-Control Window Backpressure Invariant

Mandates strict pull-based frame-level backpressure propagation across async stream transformers in Axum 0.8 and Hyper-v1 services. Precludes unbounded memory exhaustion and kernel page thrashing caused by decoupled producer-consumer rates when serving large payloads over flow-controlled HTTP/2 and HTTP/3 client downloads.

Prohibited Anti-Pattern: Decoupled Async Channel Buffering and Eager Task Spawning Leading to Process OOM on Flow-Controlled HTTP/2 Streams

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Hyper-v1 Flow-Control Window Backpressure Invariant - Mandates strict pull-based frame-level backpressure propagation across async stream transformers in Axum 0.8 and Hyper-v1 services. Precludes unbounded memory exhaustion and kernel page thrashing caused by decoupled producer-consumer rates when serving large payloads over flow-controlled HTTP/2 and HTTP/3 client downloads.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-hyper-v1-flow-control-backpressure"
---

# Axum 0.8 & Hyper-v1 Flow-Control Window Backpressure Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Decoupled Async Channel Buffering and Eager Task Spawning Leading to Process OOM on Flow-Controlled HTTP/2 Streams

## System Constraints
You are a Principal Systems Architect enforcing Hyper-v1 and Axum 0.8 flow-control invariants. You must prevent memory bloat, socket buffer exhaustion, and out-of-memory (OOM) panics caused by detached producer tasks, eager stream combinators, and unbounded mpsc channels during HTTP response streaming.

## Strict Guidelines
- Engineers MUST ALWAYS wire response stream transformers directly to the underlying `AsyncRead` source via pull-driven primitives like `tokio_util::io::ReaderStream` without intermediate detached tasks.
- Engineers MUST NOT spawn detached `tokio::spawn` producer tasks that push chunks into `tokio::sync::mpsc::unbounded_channel()` or oversized bounded queues to feed an HTTP response.
- Engineers MUST limit intermediate synchronization buffers to a capacity of at most 1 chunk if an explicit channel bridge is required, guaranteeing immediate backpressure propagation when Hyper's flow-control window stalls.
- Services MUST propagate client TCP zero-window and HTTP/2 `WINDOW_UPDATE` halts upstream to database cursors, S3 byte streams, or filesystem readers without eagerly buffering upcoming frames in memory.
- Components NEVER collect stream chunks into intermediate heap collections (`Vec<u8>`, `BytesMut`) before yielding frames to `axum::body::Body`.

## Bad vs Good Implementations
### HTTP/2 Streaming Response Backpressure Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning an unconstrained async task with an unbounded channel decouples chunk production from Hyper's frame dispatch. When a client pauses its HTTP/2 window or is on a slow connection, the producer task continues allocating frames into the channel buffer until the process runs out of memory.
```rust
use axum::{body::Body, response::IntoResponse, extract::Path};
use tokio_stream::wrappers::UnboundedReceiverStream;

pub async fn download_large_blob(Path(id): Path<String>) -> impl IntoResponse {
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

    // ANTI-PATTERN: Decoupled producer runs freely ahead of hyper's write loop.
    // If an HTTP/2 client pauses consumption via flow control, tx buffers
    // gigabytes into process memory, crashing the node with OOM.
    tokio::spawn(async move {
        let mut source = open_upstream_source(&id).await.unwrap();
        while let Some(chunk) = source.next_chunk().await {
            if tx.send(Ok::<_, std::io::Error>(chunk)).is_err() {
                break;
            }
        }
    });

    Body::from_stream(UnboundedReceiverStream::new(rx))
}
```

#### Production Standard (Correct)
> **Standard**: By utilizing `ReaderStream` inside a `StreamBody`, generation of chunks is driven strictly by Hyper's demand (`poll_frame`). Upstream reads are stalled at the system call or socket level whenever the client's HTTP/2 flow-control window closes, capping memory residency to 64KB per active connection.
```rust
use axum::{body::Body, response::IntoResponse, extract::Path};
use tokio_util::io::ReaderStream;
use http_body_util::StreamBody;

pub async fn download_large_blob(Path(id): Path<String>) -> Result<impl IntoResponse, AppError> {
    let file_reader = open_upstream_reader(&id).await?;
    
    // PRODUCTION FIX: ReaderStream uses poll-based pull semantics.
    // Upstream reads only execute when Hyper's poll_frame asks for the next chunk.
    // If the HTTP/2 client throttles the receive window, upstream polling freezes instantly.
    let chunk_stream = ReaderStream::with_capacity(file_reader, 64 * 1024);
    let frame_stream = chunk_stream.map(|res| res.map(hyper::body::Frame::data));
    
    Ok(Body::new(StreamBody::new(frame_stream)))
}
```

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 & Hyper-v1 Flow-Control Window Backpressure Invariant

Axum 0.8 & Hyper-v1 Flow-Control Window Backpressure Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates strict pull-based frame-level backpressure propagation across async stream transformers in Axum 0.8 and Hyper-v1 services. Precludes unbounded memory exhaustion and kernel page thrashing caused by decoupled producer-consumer rates when serving large payloads over flow-controlled HTTP/2 and HTTP/3 client downloads. 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: Decoupled Async Channel Buffering and Eager Task Spawning Leading to Process OOM on Flow-Controlled HTTP/2 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 DriftDecoupled Async Channel Buffering and Eager Task Spawning Leading to Process OOM on Flow-Controlled HTTP/2 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 wire response stream transformers directly to the underlying `AsyncRead` source via pull-driven primitives like `tokio_util

Engineers MUST ALWAYS wire response stream transformers directly to the underlying `AsyncRead` source via pull-driven primitives like `tokio_util::io::ReaderStream` without intermediate detached tasks.

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 spawn detached `tokio

Engineers MUST NOT spawn detached `tokio::spawn` producer tasks that push chunks into `tokio::sync::mpsc::unbounded_channel()` or oversized bounded queues to feed an HTTP response.

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 limit intermediate synchronization buffers to a capacity of at most 1 chunk if an explicit channel bridge is required, guaranteeing immediate backpressure propagation when Hyper's flow-control window stalls.

Engineers MUST limit intermediate synchronization buffers to a capacity of at most 1 chunk if an explicit channel bridge is required, guaranteeing immediate backpressure propagation when Hyper's flow-control window 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 propagate client TCP zero-window and HTTP/2 `WINDOW_UPDATE` halts upstream to database cursors, S3 byte streams, or filesystem readers without eagerly buffering upcoming frames in memory.

Services MUST propagate client TCP zero-window and HTTP/2 `WINDOW_UPDATE` halts upstream to database cursors, S3 byte streams, or filesystem readers without eagerly buffering upcoming frames in memory.

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 stream chunks into intermediate heap collections (`Vec<u8>`, `BytesMut`) before yielding frames to `axum

Components NEVER collect stream chunks into intermediate heap collections (`Vec<u8>`, `BytesMut`) before yielding frames to `axum::body::Body`.

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 & Hyper-v1 Flow-Control Window Backpressure Invariant critical for AI coding assistants?

Mandates strict pull-based frame-level backpressure propagation across async stream transformers in Axum 0.8 and Hyper-v1 services. Precludes unbounded memory exhaustion and kernel page thrashing caused by decoupled producer-consumer rates when serving large payloads over flow-controlled HTTP/2 and HTTP/3 client downloads. 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 (Decoupled Async Channel Buffering and Eager Task Spawning Leading to Process OOM on Flow-Controlled HTTP/2 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