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

Axum 0.8 Tokio Cancellation-Safe State Invariants & Mutex Hygiene

Enforces strict cancellation safety in Axum 0.8 handlers backed by Tokio runtimes. Prevents partial state mutation, deadlocks, and invariant corruption when HTTP/2 RST_STREAM or client TCP drops abort handlers mid-execution across .await points.

Prohibited Anti-Pattern: Mutating shared zero-copy state across async yield points without cancellation-safe transactional rollback.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Cancellation-Safe State Invariants & Mutex Hygiene - Enforces strict cancellation safety in Axum 0.8 handlers backed by Tokio runtimes. Prevents partial state mutation, deadlocks, and invariant corruption when HTTP/2 RST_STREAM or client TCP drops abort handlers mid-execution across .await points.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-safe-mutex-invariants"
---

# Axum 0.8 Tokio Cancellation-Safe State Invariants & Mutex Hygiene

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Mutating shared zero-copy state across async yield points without cancellation-safe transactional rollback.

## System Constraints
You are a Principal Rust Architect enforcing Tokio task cancellation safety and zero-copy state invariant rules in Axum 0.8 services. Axum handlers run directly within Tokio tasks that are abruptly dropped when HTTP clients disconnect, timeouts fire, or streams reset. You must ensure no critical section holds locks across await points where a cancellation drop would leave shared memory, zero-copy buffers, or state machines in a corrupted or half-committed state.

## Strict Guidelines
- Engineers MUST NEVER hold a `tokio::sync::Mutex` guard across an `.await` boundary when the subsequent operations depend on multi-step state consistency.
- Engineers MUST separate state mutation into synchronous, atomic, non-yielding critical sections using synchronous primitives (`parking_lot::Mutex` or `std::sync::Mutex`) held strictly within a non-async scope.
- Operations that MUST run to completion regardless of client disconnection (e.g., zero-copy ledger commits, debiting, resource releases) MUST be detached via `tokio::spawn` or dispatched through an mpsc channel to a dedicated worker task.
- Code modifying zero-copy shared buffers MUST implement the RAII rollback pattern (or a transactional staging buffer) so that if a drop occurs prior to final commit, the buffer invariants remain valid.
- Handlers MUST NOT use `tokio::select!` branches over cancel-unsafe futures that mutate shared references before completion.
- Engineers SHOULD prefer immutable snapshot state combined with atomic compare-and-swap (`arc_swap::ArcSwap`) over long-lived shared mutable state.

## Bad vs Good Implementations
### Cancellation Vulnerability vs. Non-Cancellable Commit Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts the request during `external_upstream_io().await`, Tokio immediately drops the handler future. The lock is released, but `guard.buffer` contains dirty uncommitted bytes while `committed_offset` was never updated, corrupting shared memory invariants for all concurrent tasks.
```rust
use axum::{extract::State, Json, response::IntoResponse};
use std::sync::Arc;
use tokio::sync::Mutex;

pub struct ZeroCopyLedger {
    pub buffer: Vec<u8>,
    pub committed_offset: usize,
}

// VULNERABLE: If client drops connection during `send_upstream.await`,
// `committed_offset` is never updated, but `buffer` already has dirty data.
// The Tokio mutex lock is dropped, leaving corrupted invariant for future requests.
pub async fn handle_transaction(
    State(ledger): State<Arc<Mutex<ZeroCopyLedger>>>,
    Json(payload): Json<Vec<u8>>,
) -> impl IntoResponse {
    let mut guard = ledger.lock().await;
    let start = guard.committed_offset;
    guard.buffer.extend_from_slice(&payload);

    // Client disconnection drops the future right here!
    external_upstream_io().await.expect("I/O failed");

    guard.committed_offset = start + payload.len();
    "OK"
}

async fn external_upstream_io() -> Result<(), ()> { Ok(()) }
```

#### Production Standard (Correct)
> **Standard**: All async operations that can be interrupted by client drops complete before the lock is acquired. The state update is executed synchronously without `.await` points using `parking_lot::Mutex`, guaranteeing atomic updates and zero invariant corruption.
```rust
use axum::{extract::State, Json, response::IntoResponse};
use parking_lot::Mutex;
use std::sync::Arc;

pub struct ZeroCopyLedger {
    buffer: Vec<u8>,
    committed_offset: usize,
}

impl ZeroCopyLedger {
    pub fn append_atomic(&mut self, payload: &[u8]) {
        self.buffer.extend_from_slice(payload);
        self.committed_offset += payload.len();
    }
}

// RESILIENT: Perform async I/O prior to critical section or isolate commit
// within an uninterruptible task or atomic synchronous critical section.
pub async fn handle_transaction(
    State(ledger): State<Arc<Mutex<ZeroCopyLedger>>>,
    Json(payload): Json<Vec<u8>>,
) -> impl IntoResponse {
    // 1. Perform fallible/cancellable async operations first
    external_upstream_io().await.expect("I/O failed");

    // 2. Commit state inside a synchronous scope without yield points
    {
        let mut guard = ledger.lock();
        guard.append_atomic(&payload);
    } // Lock released immediately

    "OK"
}

async fn external_upstream_io() -> Result<(), ()> { 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 Invariants & Mutex Hygiene

Axum 0.8 Tokio Cancellation-Safe State Invariants & Mutex Hygiene defines an industrial-grade behavioral standard for backend engineering. Enforces strict cancellation safety in Axum 0.8 handlers backed by Tokio runtimes. Prevents partial state mutation, deadlocks, and invariant corruption when HTTP/2 RST_STREAM or client TCP drops abort handlers mid-execution across .await points. 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: Mutating shared zero-copy state across async yield points without cancellation-safe transactional rollback. 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 DriftMutating shared zero-copy state across async yield points without cancellation-safe transactional rollback.Critical
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 hold a `tokio

Engineers MUST NEVER hold a `tokio::sync::Mutex` guard across an `.await` boundary when the subsequent operations depend on multi-step state consistency.

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 separate state mutation into synchronous, atomic, non-yielding critical sections using synchronous primitives (`parking_lot

Engineers MUST separate state mutation into synchronous, atomic, non-yielding critical sections using synchronous primitives (`parking_lot::Mutex` or `std::sync::Mutex`) held strictly within a non-async scope.

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

Operations that MUST run to completion regardless of client disconnection (e.g., zero-copy ledger commits, debiting, resource releases) MUST be detached via `tokio

Operations that MUST run to completion regardless of client disconnection (e.g., zero-copy ledger commits, debiting, resource releases) MUST be detached via `tokio::spawn` or dispatched through an mpsc channel to a dedicated worker task.

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 modifying zero-copy shared buffers MUST implement the RAII rollback pattern (or a transactional staging buffer) so that if a drop occurs prior to final commit, the buffer invariants remain valid.

Code modifying zero-copy shared buffers MUST implement the RAII rollback pattern (or a transactional staging buffer) so that if a drop occurs prior to final commit, the buffer invariants remain valid.

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 NOT use `tokio

Handlers MUST NOT use `tokio::select!` branches over cancel-unsafe futures that mutate shared references before completion.

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.
6

Engineers SHOULD prefer immutable snapshot state combined with atomic compare-and-swap (`arc_swap

Engineers SHOULD prefer immutable snapshot state combined with atomic compare-and-swap (`arc_swap::ArcSwap`) over long-lived shared mutable 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.
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 Invariants & Mutex Hygiene critical for AI coding assistants?

Enforces strict cancellation safety in Axum 0.8 handlers backed by Tokio runtimes. Prevents partial state mutation, deadlocks, and invariant corruption when HTTP/2 RST_STREAM or client TCP drops abort handlers mid-execution across .await points. 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 (Mutating shared zero-copy state across async yield points without cancellation-safe transactional rollback.) 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