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

Axum 0.8 Tower Service Connection Shedding and Stream Cancellation Protocol

Enforces deterministic async task cancellation propagation across Axum 0.8 route handlers and Tower middleware layers during client disconnects or load shedding. Prevents kernel socket descriptor exhaustion, zombie Tokio workers, and half-open TLS states by anchoring streaming bodies to RAII drop semantics and cooperative cancellation tokens.

Prohibited Anti-Pattern: Detaching Streaming Tasks via tokio::spawn Without Drop Guard or CancellationToken Propagation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Service Connection Shedding and Stream Cancellation Protocol - Enforces deterministic async task cancellation propagation across Axum 0.8 route handlers and Tower middleware layers during client disconnects or load shedding. Prevents kernel socket descriptor exhaustion, zombie Tokio workers, and half-open TLS states by anchoring streaming bodies to RAII drop semantics and cooperative cancellation tokens.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-tower-stream-cancellation-protocol"
---

# Axum 0.8 Tower Service Connection Shedding and Stream Cancellation Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detaching Streaming Tasks via tokio::spawn Without Drop Guard or CancellationToken Propagation

## System Constraints
You are a Principal Systems Architect enforcing strict Axum 0.8 and Tower service cancellation invariants. You must prevent orphaned asynchronous runtimes, lingering file descriptors, and half-open TLS connections by mandating cooperative cancellation tokens, proper stream Drop mechanics, and graceful connection draining across all HTTP response streams.

## Strict Guidelines
- Engineers MUST ALWAYS couple long-lived streaming response bodies to a `tokio_util::sync::CancellationToken` or verify that the underlying generator implements RAII cleanup on `Drop`.
- Engineers MUST NOT spawn detached background producer tasks via `tokio::spawn` feeding an unmonitored `mpsc::channel` without tracking the downstream receiver's drop state.
- Code MUST handle premature client disconnects by allowing `axum::body::Body` consumption to collapse gracefully, avoiding unhandled `BrokenPipe` or `ConnectionReset` panics in streaming loops.
- Tower middleware layers implementing `tower::limit::ConcurrencyLimit` or `tower::load_shed::LoadShed` MUST ensure rejected incoming requests return immediate `503 Service Unavailable` responses with explicit `Connection: close` headers to prevent TLS session stalls.
- Services MUST NEVER allocate non-cancellable blocking database connections or compute-heavy work inside infinite SSE (Server-Sent Events) or chunked transfer loops without yield points via `tokio::select!` on cancellation signals.

## Bad vs Good Implementations
### Cancellable Async Stream via CancellationToken and Drop Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning a detached Tokio task without a structured cancellation mechanism causes the task to persist past connection termination. Resources (such as open DB transactions, TLS state buffers, and kernel socket queues) linger until the next `send` failure occurs, causing latency spikes and socket exhaustion under high load shedding.
```rust
use axum::{body::Body, response::Response};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

pub async fn stream_handler() -> Response {
    let (tx, rx) = mpsc::channel(16);
    
    // ANTI-PATTERN: Detached task has no awareness of client disconnect or tower shedding.
    // If the client aborts, tx keeps generating and buffering until channel fills, then leaks.
    tokio::spawn(async move {
        let mut counter = 0;
        loop {
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
            let data = format!("chunk {counter}\n");
            if tx.send(Ok::<_, std::io::Error>(data)).await.is_err() {
                // Detects break only after receiver is dropped and send fails,
                // but internal resources/descriptors held prior remain dangling.
                break;
            }
            counter += 1;
        }
    });

    Response::new(Body::from_stream(ReceiverStream::new(rx)))
}
```

#### Production Standard (Correct)
> **Standard**: Using `async_stream` paired with a `CancellationToken` ensures that when the client closes the connection or Tower drops the service future, the response body is dropped, immediately firing the cancellation token and unwinding Tokio tasks cleanly without lingering kernel resources.
```rust
use axum::{body::Body, response::Response};
use tokio_util::sync::CancellationToken;
use async_stream::try_stream;

pub async fn stream_handler() -> Response {
    let token = CancellationToken::new();
    let child_token = token.child_token();

    // INVARIANT: Wrap generator in an async stream tied directly to the response lifecycle.
    // Dropping the Response body immediately aborts stream evaluation.
    let stream = try_stream! {
        let _guard = child_token.drop_guard();
        let mut counter = 0;
        loop {
            tokio::select! {
                _ = child_token.cancelled() => {
                    break;
                }
                _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {
                    yield format!("chunk {counter}\n");
                    counter += 1;
                }
            }
        }
    };

    Response::builder()
        .header("cache-control", "no-cache")
        .header("x-accel-buffering", "no")
        .body(Body::from_stream(stream))
        .unwrap()
}
```

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 Service Connection Shedding and Stream Cancellation Protocol

Axum 0.8 Tower Service Connection Shedding and Stream Cancellation Protocol defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic async task cancellation propagation across Axum 0.8 route handlers and Tower middleware layers during client disconnects or load shedding. Prevents kernel socket descriptor exhaustion, zombie Tokio workers, and half-open TLS states by anchoring streaming bodies to RAII drop semantics and cooperative cancellation tokens. 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: Detaching Streaming Tasks via tokio::spawn Without Drop Guard or CancellationToken Propagation 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 DriftDetaching Streaming Tasks via tokio::spawn Without Drop Guard or CancellationToken PropagationCritical
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 couple long-lived streaming response bodies to a `tokio_util

Engineers MUST ALWAYS couple long-lived streaming response bodies to a `tokio_util::sync::CancellationToken` or verify that the underlying generator implements RAII cleanup on `Drop`.

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 background producer tasks via `tokio

Engineers MUST NOT spawn detached background producer tasks via `tokio::spawn` feeding an unmonitored `mpsc::channel` without tracking the downstream receiver's drop state.

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 MUST handle premature client disconnects by allowing `axum

Code MUST handle premature client disconnects by allowing `axum::body::Body` consumption to collapse gracefully, avoiding unhandled `BrokenPipe` or `ConnectionReset` panics in streaming loops.

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

Tower middleware layers implementing `tower

Tower middleware layers implementing `tower::limit::ConcurrencyLimit` or `tower::load_shed::LoadShed` MUST ensure rejected incoming requests return immediate `503 Service Unavailable` responses with explicit `Connection: close` headers to prevent TLS session 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.
5

Services MUST NEVER allocate non-cancellable blocking database connections or compute-heavy work inside infinite SSE (Server-Sent Events) or chunked transfer loops without yield points via `tokio

Services MUST NEVER allocate non-cancellable blocking database connections or compute-heavy work inside infinite SSE (Server-Sent Events) or chunked transfer loops without yield points via `tokio::select!` on cancellation signals.

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 Service Connection Shedding and Stream Cancellation Protocol critical for AI coding assistants?

Enforces deterministic async task cancellation propagation across Axum 0.8 route handlers and Tower middleware layers during client disconnects or load shedding. Prevents kernel socket descriptor exhaustion, zombie Tokio workers, and half-open TLS states by anchoring streaming bodies to RAII drop semantics and cooperative cancellation tokens. 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 (Detaching Streaming Tasks via tokio::spawn Without Drop Guard or CancellationToken Propagation) 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