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

Axum 0.8 Tower Leaf-Node Request Cancellation and Socket Drain Invariant

Enforces deterministic downstream socket cleanup and prevents orphaned Tokio task leaks when HTTP/3 client streams abort mid-flight during backpressured operations. Mandates explicit cancellation propagation via tokens and guards across Tower leaf services and decoupled background tasks.

Prohibited Anti-Pattern: Spawning Unmonitored Tokio Tasks and Ignoring Stream Abort Drops in Axum Request Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Leaf-Node Request Cancellation and Socket Drain Invariant - Enforces deterministic downstream socket cleanup and prevents orphaned Tokio task leaks when HTTP/3 client streams abort mid-flight during backpressured operations. Mandates explicit cancellation propagation via tokens and guards across Tower leaf services and decoupled background tasks.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-request-cancellation-drain"
---

# Axum 0.8 Tower Leaf-Node Request Cancellation and Socket Drain Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Unmonitored Tokio Tasks and Ignoring Stream Abort Drops in Axum Request Pipelines

## System Constraints
You are a Principal Systems Engineer enforcing strict cancellation propagation and deterministic resource drainage in Axum 0.8 and Tower service architectures. Ensure zero orphaned background tasks when HTTP/3 or HTTP/2 client streams reset mid-execution.

## Strict Guidelines
- Engineers MUST ALWAYS link asynchronous background execution to the incoming request lifecycle using `tokio_util::sync::CancellationToken` or scoped task groups.
- Engineers MUST NOT invoke raw `tokio::spawn` for request-scoped work without wiring cancellation listeners to detect HTTP/3 `RST_STREAM` or socket drops.
- Code SHOULD wrap streaming response bodies and channel publishers with RAII drop guards to drain or close underlying resources immediately upon client disconnect.
- Services MUST monitor request future cancellation within backpressured processing loops using `tokio::select!` or cancellation-aware streams.
- Components NEVER assume intermediate database transactions or external RPCs abort automatically when an Axum handler future is dropped by Tower.

## Bad vs Good Implementations
### Streaming Response Processing with Cancellation Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP/3 client stream aborts mid-flight, Axum drops the outer response future, but the background worker task spawned via tokio::spawn continues to consume CPU and DB resources until the buffer fills and tx.send fails, leaking resources under heavy backpressure.
```rust
use axum::{extract::Request, response::IntoResponse};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

pub async fn handler(req: Request) -> impl IntoResponse {
    let (tx, rx) = mpsc::channel(16);
    
    // ANTI-PATTERN: Orphaned task running indefinitely if client resets stream
    tokio::spawn(async move {
        for i in 0..10_000 {
            // Heavy computation / DB pull continuing after HTTP/3 client disconnects
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            if tx.send(format!("chunk {}\n", i)).await.is_err() {
                break;
            }
        }
    });
    
    axum::response::Body::from_stream(ReceiverStream::new(rx))
}
```

#### Production Standard (Correct)
> **Standard**: Using a CancellationToken paired with an RAII drop_guard attached to the streaming body ensures that as soon as Axum/Tower drops the response future due to an HTTP/3 stream cancellation, the background Tokio task is notified instantly and terminates without orphan latency.
```rust
use axum::{extract::Request, response::IntoResponse};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;

pub async fn handler(req: Request) -> impl IntoResponse {
    let (tx, rx) = mpsc::channel(16);
    let token = CancellationToken::new();
    let child_token = token.clone();
    
    // Guard automatically triggers cancellation token when response stream is dropped
    let drop_guard = token.drop_guard();
    
    tokio::spawn(async move {
        for i in 0..10_000 {
            tokio::select! {
                biased;
                _ = child_token.cancelled() => {
                    // Explicit leaf-node pipeline drainage
                    tracing::info!("Client stream aborted: halting worker task cleanly");
                    break;
                }
                _ = tokio::time::sleep(std::time::Duration::from_millis(50)) => {
                    if tx.send(format!("chunk {}\n", i)).await.is_err() {
                        break;
                    }
                }
            }
        }
    });
    
    let stream = ReceiverStream::new(rx);
    // Attach drop guard to response lifecycle
    axum::response::Body::from_stream(async_stream::stream! {
        let _guard = drop_guard;
        for await item in stream {
            yield Ok::<_, std::io::Error>(item);
        }
    })
}
```

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 Leaf-Node Request Cancellation and Socket Drain Invariant

Axum 0.8 Tower Leaf-Node Request Cancellation and Socket Drain Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic downstream socket cleanup and prevents orphaned Tokio task leaks when HTTP/3 client streams abort mid-flight during backpressured operations. Mandates explicit cancellation propagation via tokens and guards across Tower leaf services and decoupled background tasks. 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: Spawning Unmonitored Tokio Tasks and Ignoring Stream Abort Drops in Axum Request Pipelines 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 DriftSpawning Unmonitored Tokio Tasks and Ignoring Stream Abort Drops in Axum Request PipelinesCritical
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 link asynchronous background execution to the incoming request lifecycle using `tokio_util

Engineers MUST ALWAYS link asynchronous background execution to the incoming request lifecycle using `tokio_util::sync::CancellationToken` or scoped task groups.

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 invoke raw `tokio

Engineers MUST NOT invoke raw `tokio::spawn` for request-scoped work without wiring cancellation listeners to detect HTTP/3 `RST_STREAM` or socket drops.

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 wrap streaming response bodies and channel publishers with RAII drop guards to drain or close underlying resources immediately upon client disconnect.

Code SHOULD wrap streaming response bodies and channel publishers with RAII drop guards to drain or close underlying resources immediately upon client disconnect.

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 monitor request future cancellation within backpressured processing loops using `tokio

Services MUST monitor request future cancellation within backpressured processing loops using `tokio::select!` or cancellation-aware 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.
5

Components NEVER assume intermediate database transactions or external RPCs abort automatically when an Axum handler future is dropped by Tower.

Components NEVER assume intermediate database transactions or external RPCs abort automatically when an Axum handler future is dropped by Tower.

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 Leaf-Node Request Cancellation and Socket Drain Invariant critical for AI coding assistants?

Enforces deterministic downstream socket cleanup and prevents orphaned Tokio task leaks when HTTP/3 client streams abort mid-flight during backpressured operations. Mandates explicit cancellation propagation via tokens and guards across Tower leaf services and decoupled background tasks. 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 (Spawning Unmonitored Tokio Tasks and Ignoring Stream Abort Drops in Axum Request Pipelines) 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