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

Axum 0.8 & Tokio Epoll Cooperative Task Cancellation Token Guardrail

Mandates deterministic cooperative cancellation propagation across Axum 0.8 HTTP request lifecycles, Tokio task trees, and active database transaction streams. Eliminates phantom resource starvation, unreleased database connection pool slots, and orphaned background tasks caused by implicit future drops and socket disconnects.

Prohibited Anti-Pattern: Silent Future Dropping in Tokio Select! Leading to Orphaned Database Transactions and Connection Pool Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Tokio Epoll Cooperative Task Cancellation Token Guardrail - Mandates deterministic cooperative cancellation propagation across Axum 0.8 HTTP request lifecycles, Tokio task trees, and active database transaction streams. Eliminates phantom resource starvation, unreleased database connection pool slots, and orphaned background tasks caused by implicit future drops and socket disconnects.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-token-guardrail"
---

# Axum 0.8 & Tokio Epoll Cooperative Task Cancellation Token Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Silent Future Dropping in Tokio Select! Leading to Orphaned Database Transactions and Connection Pool Starvation

## System Constraints
You are a Principal Rust Concurrency Architect enforcing Axum 0.8 and Tokio asynchronous runtime safety standards. Your objective is to ensure that all HTTP request handlers, SSE/WebSocket streams, and spawned Tokio tasks implement deterministic cooperative cancellation via `tokio_util::sync::CancellationToken` and explicit `axum::extract::Request` body abort detection. You must detect cancellation-unsafe operations in `tokio::select!` branches, guarantee deterministic rollback of database transactions (e.g., SQLx/SeaORM), and prevent phantom thread execution on client socket drops.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate a `tokio_util::sync::CancellationToken` child per incoming request and propagate child tokens down through all spawned subtasks and long-running services.
- Engineers MUST NOT spawn detached tasks (`tokio::spawn`) from Axum handlers without binding their lifetime to a propagated `CancellationToken` or holding an explicit abort guard (`tokio::task::JoinHandle::abort`).
- Code MUST ensure all branches inside `tokio::select!` are strictly cancellation-safe; any branch holding uncommitted transactional state must yield to an explicit clean-up or use `CancellationToken::cancelled()` to drive graceful rollbacks.
- Services MUST monitor client socket termination via Axum 0.8 disconnect hooks or body streaming drop detection to trigger the token before database query streams stall on epoll event loops.
- Database access inside streaming responses or long loops MUST check `token.is_cancelled()` at every iteration to proactively return connection pool slots back to the pool manager instead of relying on slow TCP RST/FIN timeouts.

## Bad vs Good Implementations
### Cooperative Database Stream Handling with CancellationToken under Client Drop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client abruptly drops the connection, Axum drops the outer response future. However, unmonitored `tokio::spawn` calls remain executing in the background, and pending database fetches lack cooperative preemption signals, causing database connection locks, phantom I/O execution, and thread pool exhaustion under heavy traffic spikes.
```rust
use axum::{extract::State, response::sse::{Event, Sse}, Json};
use futures::stream::Stream;
use sqlx::PgPool;
use std::convert::Infallible;

// ANTI-PATTERN: If client disconnects or tokio::select fires,
// the query continues running on the DB server, holding pool connections,
// and spawned worker runs detached without cancellation awareness.
pub async fn stream_records_handler(
    State(pool): State<PgPool>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    // Spawning unmonitored background processor on client request
    tokio::spawn(async move {
        // Phantom execution: runs even after client disconnects!
        for i in 0..1000 {
            tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            println!("Processing item {i}");
        }
    });

    let stream = async_stream::stream! {
        let mut rows = sqlx::query!("SELECT id, payload FROM events ORDER BY id ASC")
            .fetch(&pool);
        while let Some(Ok(row)) = rows.next().await {
            yield Ok(Event::default().data(row.payload));
        }
    };
    Sse::new(stream)
}
```

#### Production Standard (Correct)
> **Standard**: Leverages `tokio_util::sync::CancellationToken` and RAII `drop_guard()` to capture client socket drops. The cooperative token terminates downstream workers and breaks the database stream loop gracefully, guaranteeing database connections return immediately to the pool without orphaned background tasks.
```rust
use axum::{extract::State, response::sse::{Event, Sse}, response::IntoResponse};
use futures::{stream::Stream, StreamExt};
use sqlx::PgPool;
use std::convert::Infallible;
use tokio_util::sync::CancellationToken;
use tracing::{warn, info};

pub async fn stream_records_handler(
    State(pool): State<PgPool>,
) -> impl IntoResponse {
    let token = CancellationToken::new();
    let child_token = token.child_token();

    // Guarded background worker bounded to token lifetime
    let worker_token = token.child_token();
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
        for i in 0..1000 {
            tokio::select! {
                _ = worker_token.cancelled() => {
                    warn!("Worker received cancellation signal; tearing down task");
                    break;
                }
                _ = interval.tick() => {
                    info!("Processing item {i}");
                }
            }
        }
    });

    // Wrap stream with RAII token trigger on drop to detect disconnects
    let drop_guard_token = token.clone();
    let stream = async_stream::stream! {
        let _guard = drop_guard_token.drop_guard();
        let mut rows = sqlx::query!("SELECT id, payload FROM events ORDER BY id ASC")
            .fetch(&pool);

        loop {
            tokio::select! {
                biased;
                _ = child_token.cancelled() => {
                    warn!("Streaming cancelled by client or peer drop; aborting stream");
                    break;
                }
                item = rows.next() => {
                    match item {
                        Some(Ok(row)) => yield Ok(Event::default().data(row.payload)),
                        Some(Err(e)) => {
                            warn!("Database error during stream: {e:?}");
                            break;
                        }
                        None => break,
                    }
                }
            }
        }
    };

    Sse::new(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 & Tokio Epoll Cooperative Task Cancellation Token Guardrail

Axum 0.8 & Tokio Epoll Cooperative Task Cancellation Token Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic cooperative cancellation propagation across Axum 0.8 HTTP request lifecycles, Tokio task trees, and active database transaction streams. Eliminates phantom resource starvation, unreleased database connection pool slots, and orphaned background tasks caused by implicit future drops and socket disconnects. 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: Silent Future Dropping in Tokio Select! Leading to Orphaned Database Transactions and Connection Pool Starvation 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 DriftSilent Future Dropping in Tokio Select! Leading to Orphaned Database Transactions and Connection Pool StarvationCritical
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 instantiate a `tokio_util

Engineers MUST ALWAYS instantiate a `tokio_util::sync::CancellationToken` child per incoming request and propagate child tokens down through all spawned subtasks and long-running services.

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 tasks (`tokio

Engineers MUST NOT spawn detached tasks (`tokio::spawn`) from Axum handlers without binding their lifetime to a propagated `CancellationToken` or holding an explicit abort guard (`tokio::task::JoinHandle::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.
3

Code MUST ensure all branches inside `tokio

Code MUST ensure all branches inside `tokio::select!` are strictly cancellation-safe; any branch holding uncommitted transactional state must yield to an explicit clean-up or use `CancellationToken::cancelled()` to drive graceful rollbacks.

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 client socket termination via Axum 0.8 disconnect hooks or body streaming drop detection to trigger the token before database query streams stall on epoll event loops.

Services MUST monitor client socket termination via Axum 0.8 disconnect hooks or body streaming drop detection to trigger the token before database query streams stall on epoll event 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.
5

Database access inside streaming responses or long loops MUST check `token.is_cancelled()` at every iteration to proactively return connection pool slots back to the pool manager instead of relying on slow TCP RST/FIN timeouts.

Database access inside streaming responses or long loops MUST check `token.is_cancelled()` at every iteration to proactively return connection pool slots back to the pool manager instead of relying on slow TCP RST/FIN timeouts.

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 & Tokio Epoll Cooperative Task Cancellation Token Guardrail critical for AI coding assistants?

Mandates deterministic cooperative cancellation propagation across Axum 0.8 HTTP request lifecycles, Tokio task trees, and active database transaction streams. Eliminates phantom resource starvation, unreleased database connection pool slots, and orphaned background tasks caused by implicit future drops and socket disconnects. 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 (Silent Future Dropping in Tokio Select! Leading to Orphaned Database Transactions and Connection Pool Starvation) 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