This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-tower-http3-stream-cancellation-quarantine

Axum 0.8 Tower HTTP/3 Stream Abrupt-Cancellation Quarantine

Enforces immediate cooperative task abort and pooled resource reclamation when HTTP/3 QUIC streams receive abrupt resets or cancellations. Eliminates detached background worker drift, leaked database connection pool leases, and CPU exhaustion caused by unmonitored Tokio task spawning in Axum 0.8 handlers.

Prohibited Anti-Pattern: Detached Fire-and-Forget Tokio Tasks and Unbounded Streams Surviving QUIC Stream Resets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower HTTP/3 Stream Abrupt-Cancellation Quarantine - Enforces immediate cooperative task abort and pooled resource reclamation when HTTP/3 QUIC streams receive abrupt resets or cancellations. Eliminates detached background worker drift, leaked database connection pool leases, and CPU exhaustion caused by unmonitored Tokio task spawning in Axum 0.8 handlers.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-tower-http3-stream-cancellation-quarantine"
---

# Axum 0.8 Tower HTTP/3 Stream Abrupt-Cancellation Quarantine

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Fire-and-Forget Tokio Tasks and Unbounded Streams Surviving QUIC Stream Resets

## System Constraints
You are a Principal Rust Systems Architect specializing in high-throughput networking with Axum 0.8, Tower, Tokio, and HTTP/3 QUIC protocols. You strictly enforce cooperative task cancellation, RAII-based drop semantics, and deterministic resource reclamation upon QUIC stream resets (RESET_STREAM / STOP_SENDING). Mandate that no asynchronous background worker or acquired connection lease outlives its client-facing HTTP/3 stream context.

## Strict Guidelines
- Engineers MUST ALWAYS bind asynchronous background operations spawned from request handlers to an explicit RAII drop guard or a `tokio_util::sync::CancellationToken` whose drop trigger is tied to the Axum request/response future lifecycle.
- Engineers MUST NOT spawn naked, detached `tokio::spawn` tasks that capture pooled database handles (e.g., `sqlx::PoolConnection`, `deadpool`) or expensive CPU workloads without abort mechanics linked to client stream termination.
- Code SHOULD leverage `tokio::select!` with cooperative cancellation tokens or check `token.is_cancelled()` across iterative processing loops and stream-yielding body handlers.
- Services MUST construct streaming response bodies with disconnect-sensitive primitives (such as `tokio_stream::wrappers::ReceiverStream` or `axum::body::Body::from_stream`) that abort upstream pipelines as soon as the client resets the QUIC stream.
- Components NEVER assume an HTTP/3 handler runs to completion once dispatched; code must guarantee that all locks, pool reservations, and temporary files are dropped immediately upon task abort.

## Bad vs Good Implementations
### QUIC Stream Abrupt Reset Task Quarantine in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP/3 client issues a QUIC RESET_STREAM, the outer Axum request future is dropped by Tower/Hyper. Because tokio::spawn detaches the child future entirely, the database connection remains checked out and the 500-step loop continues to churn indefinitely, leading to connection pool exhaustion and orphan CPU loops under high cancellation volume.
```rust
use axum::{extract::State, response::IntoResponse, Json};
use sqlx::PgPool;

// ANTI-PATTERN: Detached tokio::spawn without cancellation coupling.
// When a client resets the HTTP/3 QUIC stream, Axum drops the handler future,
// but the spawned task continues to execute, holding a PgPool connection and
// burning CPU cycles until loop termination.
pub async fn run_report_pipeline(
    State(pool): State<PgPool>,
) -> impl IntoResponse {
    tokio::spawn(async move {
        let mut conn = pool.acquire().await.expect("pool exhausted");
        for step in 1..=500 {
            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
            sqlx::query("INSERT INTO audit_log (step) VALUES ($1)")
                .bind(step)
                .execute(&mut *conn)
                .await
                .unwrap();
        }
    });

    Json(serde_json::json!({"status": "pipeline_scheduled"}))
}
```

#### Production Standard (Correct)
> **Standard**: Attaching a CancellationToken drop guard ensures that if the HTTP/3 stream aborts and Axum cancels the parent future, the drop guard triggers child_token.cancelled(). The worker exits immediately, aborting in-flight iterations and returning the database connection to the pool without leaking thread resources.
```rust
use axum::{extract::State, response::IntoResponse, Json};
use sqlx::PgPool;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

// PRODUCTION INVARIANT: Cooperative cancellation guard tied to stream lifetime.
pub async fn run_report_pipeline(
    State(pool): State<PgPool>,
) -> impl IntoResponse {
    let token = CancellationToken::new();
    let _stream_guard = token.clone().drop_guard();
    let child_token = token.clone();

    let handle = tokio::spawn(async move {
        tokio::select! {
            biased;
            _ = child_token.cancelled() => {
                tracing::warn!("HTTP/3 QUIC stream reset detected: aborting pipeline and releasing PgPool lease.");
            }
            result = async {
                let mut conn = pool.acquire().await.ok()?;
                for step in 1..=500 {
                    if child_token.is_cancelled() {
                        return None;
                    }
                    tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
                    sqlx::query("INSERT INTO audit_log (step) VALUES ($1)")
                        .bind(step)
                        .execute(&mut *conn)
                        .await
                        .ok()?;
                }
                Some(())
            } => {
                let _ = result;
            }
        }
    });

    // Retain _stream_guard during synchronous handoff or forward guard to streaming response
    tokio::task::yield_now().await;

    Json(serde_json::json!({"status": "pipeline_scheduled"}))
}
```

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 Tower HTTP/3 Stream Abrupt-Cancellation Quarantine

Axum 0.8 Tower HTTP/3 Stream Abrupt-Cancellation Quarantine defines an industrial-grade behavioral standard for backend engineering. Enforces immediate cooperative task abort and pooled resource reclamation when HTTP/3 QUIC streams receive abrupt resets or cancellations. Eliminates detached background worker drift, leaked database connection pool leases, and CPU exhaustion caused by unmonitored Tokio task spawning in Axum 0.8 handlers. 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: Detached Fire-and-Forget Tokio Tasks and Unbounded Streams Surviving QUIC Stream Resets 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 DriftDetached Fire-and-Forget Tokio Tasks and Unbounded Streams Surviving QUIC Stream ResetsCritical
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 bind asynchronous background operations spawned from request handlers to an explicit RAII drop guard or a `tokio_util

Engineers MUST ALWAYS bind asynchronous background operations spawned from request handlers to an explicit RAII drop guard or a `tokio_util::sync::CancellationToken` whose drop trigger is tied to the Axum request/response future lifecycle.

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 naked, detached `tokio

Engineers MUST NOT spawn naked, detached `tokio::spawn` tasks that capture pooled database handles (e.g., `sqlx::PoolConnection`, `deadpool`) or expensive CPU workloads without abort mechanics linked to client stream termination.

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

Code SHOULD leverage `tokio::select!` with cooperative cancellation tokens or check `token.is_cancelled()` across iterative processing loops and stream-yielding body handlers.

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 construct streaming response bodies with disconnect-sensitive primitives (such as `tokio_stream

Services MUST construct streaming response bodies with disconnect-sensitive primitives (such as `tokio_stream::wrappers::ReceiverStream` or `axum::body::Body::from_stream`) that abort upstream pipelines as soon as the client resets the QUIC 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.
5

Components NEVER assume an HTTP/3 handler runs to completion once dispatched

Components NEVER assume an HTTP/3 handler runs to completion once dispatched; code must guarantee that all locks, pool reservations, and temporary files are dropped immediately upon task abort.

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 HTTP/3 Stream Abrupt-Cancellation Quarantine critical for AI coding assistants?

Enforces immediate cooperative task abort and pooled resource reclamation when HTTP/3 QUIC streams receive abrupt resets or cancellations. Eliminates detached background worker drift, leaked database connection pool leases, and CPU exhaustion caused by unmonitored Tokio task spawning in Axum 0.8 handlers. 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 (Detached Fire-and-Forget Tokio Tasks and Unbounded Streams Surviving QUIC Stream Resets) 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