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

Axum 0.8 Tower Task Cancellation and Resource Reclamation Standard

Enforces strict cancellation propagation and RAII resource reclamation across Axum 0.8 handlers and Tower middleware stacks. Prevents connection leaks, orphaned database transactions, and CPU waste by ensuring Tokio futures abort safely upon client TCP termination or HTTP/2 stream reset. Mandates explicit cancellation token boundaries for intentional detached background tasks.

Prohibited Anti-Pattern: Detached Tokio Spawns and Non-RAII Async State Causing Zombie Queries and Leaked Connection Leases on Client Disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Task Cancellation and Resource Reclamation Standard - Enforces strict cancellation propagation and RAII resource reclamation across Axum 0.8 handlers and Tower middleware stacks. Prevents connection leaks, orphaned database transactions, and CPU waste by ensuring Tokio futures abort safely upon client TCP termination or HTTP/2 stream reset. Mandates explicit cancellation token boundaries for intentional detached background tasks.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-task-cancellation-reclamation-standard"
---

# Axum 0.8 Tower Task Cancellation and Resource Reclamation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Tokio Spawns and Non-RAII Async State Causing Zombie Queries and Leaked Connection Leases on Client Disconnect

## System Constraints
You are a Principal Systems Architect enforcing the Axum 0.8 and Tower Task Cancellation and Resource Reclamation Standard. Your goal is to guarantee that client disconnects, timeouts, and downstream pipeline cancellations immediately halt pending execution, release connection pool slots, and safely abort or commit transactional boundaries without leaking memory, sockets, or locks.

## Strict Guidelines
- Engineers MUST NEVER invoke raw `tokio::spawn` inside Axum handlers for operations that should terminate when the client disconnects; handler futures MUST remain tied to the inbound request lifecycle.
- Engineers MUST wrap stateful database transactions in RAII guards (e.g., `sqlx::Transaction`) where drop semantics automatically issue an async rollback or release the underlying pool lease when a future is aborted.
- Code executing intentional out-of-band asynchronous work MUST use a structured supervisor like `tokio_util::task::TaskTracker` combined with `tokio_util::sync::CancellationToken` rather than untracked detached threads.
- Middleware pipelines MUST be cancellation-safe across `.await` suspension points; mutexes, semaphore permits, and leased network buffers MUST NOT be held across `.await` points where cancellation would cause deadlocks or permanent starvation.
- Streaming responses (Server-Sent Events, chunked bodies, and WebSockets) MUST listen for client disconnect notifications or yield to stream termination checks on every iteration to immediately release upstream database and message broker cursors.

## Bad vs Good Implementations
### Handling Client Disconnection in Long-Running Database Mutations

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning a detached task drops the connection between the client's HTTP request lifecycle and the execution. If the client terminates the connection, the background query continues running, consuming pool connections and compute resources uncontrollably.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use sqlx::PgPool;

#[derive(Deserialize)]
pub struct JobRequest { pub payload: String }

pub async fn run_job_bad(
    State(pool): State<PgPool>,
    Json(req): Json<JobRequest>,
) -> impl IntoResponse {
    // ANTI-PATTERN: Spawning an unmonitored detached task disconnects execution
    // from the Axum client socket. If the client drops connection (e.g., client timeout),
    // this query runs to completion, occupying pool connections and database IO.
    tokio::spawn(async move {
        let mut conn = pool.acquire().await.unwrap();
        sqlx::query!("INSERT INTO job_history (data) VALUES ($1)", req.payload)
            .execute(&mut *conn)
            .await
            .unwrap();
    });

    StatusCode::ACCEPTED
}
```

#### Production Standard (Correct)
> **Standard**: The transaction execution stays within the handler's async future frame. If the HTTP stream drops, the future is dropped immediately at its pending await point, triggering the `Drop` implementation on `sqlx::Transaction`, which cleans up resources and prevents orphaned transactions.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use sqlx::{PgPool, Transaction, Postgres};

#[derive(Deserialize)]
pub struct JobRequest { pub payload: String }

pub async fn run_job_good(
    State(pool): State<PgPool>,
    Json(req): Json<JobRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    // INVARIANT: Execute directly within the handler future.
    // If the client disconnects, Axum drops the handler future at the nearest .await.
    // sqlx::Transaction implements Drop: dropping the transaction uncommitted
    // triggers an internal rollback and immediately returns the connection to the pool.
    let mut tx: Transaction<'_, Postgres> = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    sqlx::query!("INSERT INTO job_history (data) VALUES ($1)", req.payload)
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    tx.commit().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(StatusCode::CREATED)
}
```

### Cancellation-Safe Server-Sent Events (SSE) Stream Reclamation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Without structured guardrails, streams that encapsulate external resources (such as message queues or DB listeners) can hang indefinitely or fail to signal upstream dependencies when the client closes the connection.
```rust
use axum::response::sse::{Event, KeepAlive, Sse};
use futures::stream::Stream;
use std::convert::Infallible;
use tokio::time::{sleep, Duration};

pub async fn bad_sse_stream() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    // ANTI-PATTERN: The stream does not track drop or acquire resource limits safely;
    // holding a raw lease across un-cancellable intervals risks lock contention.
    let stream = async_stream::try_stream! {
        let mut counter = 0;
        loop {
            sleep(Duration::from_secs(1)).await;
            counter += 1;
            yield Event::default().data(format!("event count: {}", counter));
        }
    };

    Sse::new(stream).keep_alive(KeepAlive::default())
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes `CancellationToken::drop_guard()` attached to the stream's lifecycle. When the client closes the connection, the stream drops, firing the guard, cancelling concurrent branches, and ensuring deterministic cleanup.
```rust
use axum::response::sse::{Event, KeepAlive, Sse};
use futures::stream::Stream;
use std::convert::Infallible;
use tokio::time::{sleep, Duration};
use tokio_util::sync::CancellationToken;

pub async fn good_sse_stream() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    // INVARIANT: RAII cleanup via CancellationToken.
    // When the downstream Sse body drops, the stream is dropped, executing RAII Drop guards
    // and notifying any cooperative worker subroutines via CancellationToken.
    let token = CancellationToken::new();
    let drop_guard = token.clone().drop_guard();

    let stream = async_stream::try_stream! {
        let _guard = drop_guard; // Bound to the life of the generator
        let mut counter = 0;
        loop {
            tokio::select! {
                _ = token.cancelled() => {
                    break;
                }
                _ = sleep(Duration::from_secs(1)) => {
                    counter += 1;
                    yield Event::default().data(format!("event count: {}", counter));
                }
            }
        }
    };

    Sse::new(stream).keep_alive(KeepAlive::default())
}
```

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 Task Cancellation and Resource Reclamation Standard

Axum 0.8 Tower Task Cancellation and Resource Reclamation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict cancellation propagation and RAII resource reclamation across Axum 0.8 handlers and Tower middleware stacks. Prevents connection leaks, orphaned database transactions, and CPU waste by ensuring Tokio futures abort safely upon client TCP termination or HTTP/2 stream reset. Mandates explicit cancellation token boundaries for intentional detached 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: Detached Tokio Spawns and Non-RAII Async State Causing Zombie Queries and Leaked Connection Leases on Client Disconnect 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 Tokio Spawns and Non-RAII Async State Causing Zombie Queries and Leaked Connection Leases on Client DisconnectCritical
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 NEVER invoke raw `tokio

Engineers MUST NEVER invoke raw `tokio::spawn` inside Axum handlers for operations that should terminate when the client disconnects; handler futures MUST remain tied to the inbound request 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 wrap stateful database transactions in RAII guards (e.g., `sqlx

Engineers MUST wrap stateful database transactions in RAII guards (e.g., `sqlx::Transaction`) where drop semantics automatically issue an async rollback or release the underlying pool lease when a future is aborted.

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 executing intentional out-of-band asynchronous work MUST use a structured supervisor like `tokio_util

Code executing intentional out-of-band asynchronous work MUST use a structured supervisor like `tokio_util::task::TaskTracker` combined with `tokio_util::sync::CancellationToken` rather than untracked detached threads.

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

Middleware pipelines MUST be cancellation-safe across `.await` suspension points

Middleware pipelines MUST be cancellation-safe across `.await` suspension points; mutexes, semaphore permits, and leased network buffers MUST NOT be held across `.await` points where cancellation would cause deadlocks or permanent starvation.

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

Streaming responses (Server-Sent Events, chunked bodies, and WebSockets) MUST listen for client disconnect notifications or yield to stream termination checks on every iteration to immediately release upstream database and message broker cursors.

Streaming responses (Server-Sent Events, chunked bodies, and WebSockets) MUST listen for client disconnect notifications or yield to stream termination checks on every iteration to immediately release upstream database and message broker cursors.

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 Task Cancellation and Resource Reclamation Standard critical for AI coding assistants?

Enforces strict cancellation propagation and RAII resource reclamation across Axum 0.8 handlers and Tower middleware stacks. Prevents connection leaks, orphaned database transactions, and CPU waste by ensuring Tokio futures abort safely upon client TCP termination or HTTP/2 stream reset. Mandates explicit cancellation token boundaries for intentional detached 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 (Detached Tokio Spawns and Non-RAII Async State Causing Zombie Queries and Leaked Connection Leases on Client Disconnect) 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