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

Axum 0.8 Tokio Cancellation-Safe State Mutation Guardrail

Enforces asynchronous cancellation safety across Axum 0.8 request handlers running on Tokio runtimes. Guarantees that abruptly terminated HTTP/2 and HTTP/3 client streams (e.g., RST_STREAM frames) or client disconnects cannot interrupt intermediate async yield points inside critical state-machine updates, multi-step atomic operations, or non-atomic transaction sequences.

Prohibited Anti-Pattern: Interrupted In-Flight Awaits Causing Partial Multi-Phase State Mutations and Leaked Resources Upon Client Disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Cancellation-Safe State Mutation Guardrail - Enforces asynchronous cancellation safety across Axum 0.8 request handlers running on Tokio runtimes. Guarantees that abruptly terminated HTTP/2 and HTTP/3 client streams (e.g., RST_STREAM frames) or client disconnects cannot interrupt intermediate async yield points inside critical state-machine updates, multi-step atomic operations, or non-atomic transaction sequences.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-safe-state-guardrail"
---

# Axum 0.8 Tokio Cancellation-Safe State Mutation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Interrupted In-Flight Awaits Causing Partial Multi-Phase State Mutations and Leaked Resources Upon Client Disconnect

## System Constraints
You are a Principal Rust Concurrency Engineer enforcing Tokio cancellation safety within Axum 0.8 services. In Axum, every handler future is polled directly by the Hyper/Tokio connection task; when an HTTP/2 or HTTP/3 stream aborts, the handler future is instantly dropped at its current `.await` point. You must ensure all critical mutations, database transactional sequences, and multi-step shared state modifications either execute synchronously without interleaving awaits, run within an isolated background supervisor task via `tokio::spawn`, or utilize explicit rollback Drop guards.

## Strict Guidelines
- Engineers MUST NOT execute `.await` points between interdependent state transitions or between reserving and committing atomic resources in an Axum request handler.
- Engineers MUST decouple non-cancellable critical workflows (e.g., ledger updates, credit deductions, external webhook dispatches) from the ephemeral request lifecycle by offloading them to `tokio::spawn` or dedicated mpsc/broadcast worker channels.
- Engineers MUST ensure any transactional resource held across an await point implements RAII drop mechanics (e.g., `sqlx::Transaction` automatic rollback on drop) and does not rely on subsequent awaits for cleanup.
- Services MUST wrap long-running or segmented in-memory mutex writes using synchronous, non-yielding closures (e.g., standard `parking_lot::Mutex` or synchronous critical sections) rather than `tokio::sync::Mutex` across yields unless strictly necessary.
- Handlers MUST NEVER assume an async database commit succeeded if the stream dropped; state transitions spanning multiple external services must use an idempotency token with write-ahead intent logs.

## Bad vs Good Implementations
### Decoupling Critical State Updates from Axum Request Handler Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the client aborts the HTTP connection during the `sleep.await` yield point, Axum drops the handler future immediately. The balance deduction remains in memory, but the audit log entry is never executed, permanently corrupting invariant consistency.
```rust
use axum::{extract::State, http::StatusCode, Json};
use std::sync::Arc;
use tokio::sync::Mutex;

struct AppState {
    balance: Mutex<i64>,
    audit_log: Mutex<Vec<String>>,
}

// ANTI-PATTERN: If client closes HTTP/2 stream between step 1 and step 2, balance is mutated
// but the audit record is lost, leaving the system in a corrupted, unrecoverable state.
async fn transfer_funds(
    State(state): State<Arc<AppState>>,
    Json(amount): Json<i64>,
) -> Result<StatusCode, StatusCode> {
    let mut balance_guard = state.balance.lock().await;
    *balance_guard -= amount;
    
    // CRITICAL YIELD POINT: Abort here leaves state partially mutated
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    
    let mut log_guard = state.audit_log.lock().await;
    log_guard.push(format!("Deducted {amount}"));
    
    Ok(StatusCode.OK)
}
```

#### Production Standard (Correct)
> **Standard**: Critical mutations are consolidated into a synchronous critical section that cannot yield, preventing partial updates. Additionally, wrapping the flow inside `tokio::spawn` ensures that even if the client disconnects and cancels the HTTP handler future, the background execution continues to safe termination.
```rust
use axum::{extract::State, http::StatusCode, Json};
use std::sync::Arc;
use parking_lot::Mutex;

struct AppState {
    // Invariant: Guarded by synchronous Mutex; mutations are atomic and cannot yield
    inner: Mutex<AccountData>,
}

struct AccountData {
    balance: i64,
    audit_log: Vec<String>,
}

async fn transfer_funds(
    State(state): State<Arc<AppState>>,
    Json(amount): Json<i64>,
) -> Result<StatusCode, StatusCode> {
    // Spawning to a detached Tokio task guarantees completion even if HTTP stream cancels
    let background_state = Arc::clone(&state);
    tokio::spawn(async move {
        // Synchronous critical section without async yield points guarantees all-or-nothing mutation
        let mut data = background_state.inner.lock();
        data.balance -= amount;
        data.audit_log.push(format!("Deducted {amount}"));
    }).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(StatusCode::OK)
}
```

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 State Mutation Guardrail

Axum 0.8 Tokio Cancellation-Safe State Mutation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces asynchronous cancellation safety across Axum 0.8 request handlers running on Tokio runtimes. Guarantees that abruptly terminated HTTP/2 and HTTP/3 client streams (e.g., RST_STREAM frames) or client disconnects cannot interrupt intermediate async yield points inside critical state-machine updates, multi-step atomic operations, or non-atomic transaction sequences. 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: Interrupted In-Flight Awaits Causing Partial Multi-Phase State Mutations and Leaked Resources Upon 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 DriftInterrupted In-Flight Awaits Causing Partial Multi-Phase State Mutations and Leaked Resources Upon 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 NOT execute `.await` points between interdependent state transitions or between reserving and committing atomic resources in an Axum request handler.

Engineers MUST NOT execute `.await` points between interdependent state transitions or between reserving and committing atomic resources in an Axum request handler.

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 decouple non-cancellable critical workflows (e.g., ledger updates, credit deductions, external webhook dispatches) from the ephemeral request lifecycle by offloading them to `tokio

Engineers MUST decouple non-cancellable critical workflows (e.g., ledger updates, credit deductions, external webhook dispatches) from the ephemeral request lifecycle by offloading them to `tokio::spawn` or dedicated mpsc/broadcast worker channels.

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

Engineers MUST ensure any transactional resource held across an await point implements RAII drop mechanics (e.g., `sqlx

Engineers MUST ensure any transactional resource held across an await point implements RAII drop mechanics (e.g., `sqlx::Transaction` automatic rollback on drop) and does not rely on subsequent awaits for cleanup.

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 wrap long-running or segmented in-memory mutex writes using synchronous, non-yielding closures (e.g., standard `parking_lot

Services MUST wrap long-running or segmented in-memory mutex writes using synchronous, non-yielding closures (e.g., standard `parking_lot::Mutex` or synchronous critical sections) rather than `tokio::sync::Mutex` across yields unless strictly necessary.

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

Handlers MUST NEVER assume an async database commit succeeded if the stream dropped

Handlers MUST NEVER assume an async database commit succeeded if the stream dropped; state transitions spanning multiple external services must use an idempotency token with write-ahead intent logs.

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 State Mutation Guardrail critical for AI coding assistants?

Enforces asynchronous cancellation safety across Axum 0.8 request handlers running on Tokio runtimes. Guarantees that abruptly terminated HTTP/2 and HTTP/3 client streams (e.g., RST_STREAM frames) or client disconnects cannot interrupt intermediate async yield points inside critical state-machine updates, multi-step atomic operations, or non-atomic transaction sequences. 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 (Interrupted In-Flight Awaits Causing Partial Multi-Phase State Mutations and Leaked Resources Upon 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