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

Axum 0.8 Tokio Cancellation-Safe Async Handler Standard

Enforces strict cancellation-safety invariants across Axum 0.8 HTTP handlers and Tokio async operations. Prevents orphan DB states, partial buffer flushes, and socket pool exhaustion when client connections terminate early or tokio::select! branches drop incomplete futures. Requires critical business mutations and database transactions to run within detached supervisor tasks or atomic linear sequences insulated from client transport lifecycle.

Prohibited Anti-Pattern: Running Non-Cancellation-Safe Database and External Mutations Directly in Client-Bound Tokio Futures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Cancellation-Safe Async Handler Standard - Enforces strict cancellation-safety invariants across Axum 0.8 HTTP handlers and Tokio async operations. Prevents orphan DB states, partial buffer flushes, and socket pool exhaustion when client connections terminate early or tokio::select! branches drop incomplete futures. Requires critical business mutations and database transactions to run within detached supervisor tasks or atomic linear sequences insulated from client transport lifecycle.
globs: src/**/*.rs, crates/**/*.rs, tests/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-tokio-cancellation-safe-handler-standard"
---

# Axum 0.8 Tokio Cancellation-Safe Async Handler Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Running Non-Cancellation-Safe Database and External Mutations Directly in Client-Bound Tokio Futures

## System Constraints
You are a Principal Rust Distributed Systems Engineer enforcing Axum 0.8 and Tokio cancellation-safety invariants. Client-bound futures in Axum are dropped instantly when TCP sockets terminate or when competing tokio::select! branches resolve. You must mandate that non-cancellation-safe operations—such as multi-step database mutations, file writes, and outbound payment requests—are never driven directly by the client request future. Guide agents to use atomic transactions, tokio::spawn for detached work units, or mpsc bounded channels to decouple transport drop events from business logic execution.

## Strict Guidelines
- Engineers MUST ALWAYS isolate state-mutating multi-step workflows from client connection termination using `tokio::spawn` or background queues.
- Engineers MUST NOT place non-cancellation-safe futures (e.g., `AsyncWriteExt::write_all`, non-atomic SQL operations, HTTP client POSTs) inside racing `tokio::select!` branches without guard mechanisms.
- Handlers MUST design database transactions such that if dropped, the `Drop` implementation on the transaction handle cleanly triggers a rollback without leaving half-committed side effects.
- Code SHOULD prefer spawning dedicated tasks (`tokio::task::JoinHandle`) and awaiting completion via cancellation-safe channels when results must be reported back to the HTTP response.
- Services MUST NEVER assume an in-flight Axum handler future runs to completion; any code past an `.await` point can be aborted at any yield point.

## Bad vs Good Implementations
### Vulnerable Direct In-Handler Mutation vs Decoupled Detached Task with Error Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the client closes the TCP connection or times out between the two database queries, Axum drops the handler future at the await point. The account balance remains decremented, but the order record is never inserted, causing silent data corruption and ledger discrepancies.
```rust
use axum::{extract::State, http::StatusCode, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct OrderPayload { pub user_id: i64, pub amount: i64 }

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderPayload>,
) -> Result<StatusCode, StatusCode> {
    // ANTI-PATTERN: If client disconnects here, execution aborts instantly.
    // Debit succeeds, but credit and order creation are dropped mid-flight.
    sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount, payload.user_id)
        .execute(&pool)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Client resets connection -> Handler dropped -> Money is lost forever!
    sqlx::query!("INSERT INTO orders (user_id, amount) VALUES ($1, $2)", payload.user_id, payload.amount)
        .execute(&pool)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(StatusCode::CREATED)
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping operations in a database transaction ensures ACID atomicity on drop, and wrapping the transaction inside `tokio::spawn` guarantees that execution continues to commit even if the client abruptly severs the HTTP connection.
```rust
use axum::{extract::State, http::StatusCode, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct OrderPayload { pub user_id: i64, pub amount: i64 }

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderPayload>,
) -> Result<StatusCode, StatusCode> {
    // PRODUCTION FIX: Critical multi-step mutation is executed inside an atomic transaction
    // and dispatched via a detached supervisor task insulated from client socket drops.
    let task = tokio::spawn(async move {
        let mut tx = pool.begin().await?;
        
        sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount, payload.user_id)
            .execute(&mut *tx)
            .await?;

        sqlx::query!("INSERT INTO orders (user_id, amount) VALUES ($1, $2)", payload.user_id, payload.amount)
            .execute(&mut *tx)
            .await?;

        tx.commit().await?;
        Ok::<(), sqlx::Error>(())
    });

    // Awaiting JoinHandle preserves client notification while guaranteeing 
    // background completion even if the client disconnects.
    match task.await {
        Ok(Ok(())) => Ok(StatusCode::CREATED),
        Ok(Err(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}
```

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 Cancellation-Safe Async Handler Standard

Axum 0.8 Tokio Cancellation-Safe Async Handler Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict cancellation-safety invariants across Axum 0.8 HTTP handlers and Tokio async operations. Prevents orphan DB states, partial buffer flushes, and socket pool exhaustion when client connections terminate early or tokio::select! branches drop incomplete futures. Requires critical business mutations and database transactions to run within detached supervisor tasks or atomic linear sequences insulated from client transport lifecycle. 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: Running Non-Cancellation-Safe Database and External Mutations Directly in Client-Bound Tokio Futures 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 DriftRunning Non-Cancellation-Safe Database and External Mutations Directly in Client-Bound Tokio FuturesCritical
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 isolate state-mutating multi-step workflows from client connection termination using `tokio

Engineers MUST ALWAYS isolate state-mutating multi-step workflows from client connection termination using `tokio::spawn` or background queues.

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 place non-cancellation-safe futures (e.g., `AsyncWriteExt

Engineers MUST NOT place non-cancellation-safe futures (e.g., `AsyncWriteExt::write_all`, non-atomic SQL operations, HTTP client POSTs) inside racing `tokio::select!` branches without guard mechanisms.

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

Handlers MUST design database transactions such that if dropped, the `Drop` implementation on the transaction handle cleanly triggers a rollback without leaving half-committed side effects.

Handlers MUST design database transactions such that if dropped, the `Drop` implementation on the transaction handle cleanly triggers a rollback without leaving half-committed side effects.

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

Code SHOULD prefer spawning dedicated tasks (`tokio

Code SHOULD prefer spawning dedicated tasks (`tokio::task::JoinHandle`) and awaiting completion via cancellation-safe channels when results must be reported back to the HTTP response.

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 assume an in-flight Axum handler future runs to completion

Services MUST NEVER assume an in-flight Axum handler future runs to completion; any code past an `.await` point can be aborted at any yield point.

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 Cancellation-Safe Async Handler Standard critical for AI coding assistants?

Enforces strict cancellation-safety invariants across Axum 0.8 HTTP handlers and Tokio async operations. Prevents orphan DB states, partial buffer flushes, and socket pool exhaustion when client connections terminate early or tokio::select! branches drop incomplete futures. Requires critical business mutations and database transactions to run within detached supervisor tasks or atomic linear sequences insulated from client transport lifecycle. 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 (Running Non-Cancellation-Safe Database and External Mutations Directly in Client-Bound Tokio Futures) 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