This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-tower-middleware-panic-isolation-invariant

Axum Tower Middleware Panic Isolation and Cancellation Invariant

Enforces strict panic isolation, cancellation safety, and RAII cleanup invariants across Axum and Tower middleware layers. Prevents Tokio task cancellation drops and thread unwinds from poisoning shared state Mutexes, leaking telemetry contexts, or leaving distributed transactional handles dangling.

Prohibited Anti-Pattern: Unprotected Tower Middleware State Mutation and Unhandled Panics Poisoning Shared State on Task Drop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum Tower Middleware Panic Isolation and Cancellation Invariant - Enforces strict panic isolation, cancellation safety, and RAII cleanup invariants across Axum and Tower middleware layers. Prevents Tokio task cancellation drops and thread unwinds from poisoning shared state Mutexes, leaking telemetry contexts, or leaving distributed transactional handles dangling.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-middleware-panic-isolation-invariant"
---

# Axum Tower Middleware Panic Isolation and Cancellation Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unprotected Tower Middleware State Mutation and Unhandled Panics Poisoning Shared State on Task Drop

## System Constraints
You are a Principal Rust Architect enforcing resilience invariants in Axum and Tower middleware stacks. Ensure all asynchronous request pipelines are strictly cancellation-safe, isolate panics to the request boundary via CatchPanicLayer, and avoid holding standard blocking locks or incomplete state mutations across Tokio await points.

## Strict Guidelines
- Engineers MUST ALWAYS register `tower_http::catch_panic::CatchPanicLayer` at the boundary of public Axum routers to intercept unwinding panics before worker thread termination.
- Engineers MUST NOT hold `std::sync::MutexGuard` or `std::sync::RwLockReadGuard`/`RwLockWriteGuard` across `.await` points or within async middleware layers where task cancellation can trigger lock poisoning.
- Code MUST ensure Tokio cancellation safety: state updates across async yield points must either be atomic or guarded by an RAII transaction roll-back token that cleans up transient state on Drop.
- Services MUST pass transient request contexts via typed Axum extensions (`req.extensions_mut().insert(...)`) and rely on automatic Drop semantics rather than manual teardown hooks vulnerable to cancellation.
- Components NEVER expose shared application state (`axum::extract::State`) to partial mutation prior to asynchronous I/O without rollback or commit boundaries.

## Bad vs Good Implementations
### Unsafe Shared Mutex Mutation and Missing Panic Boundary vs. Cancellation-Safe RAII Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using std::sync::Mutex without RAII drop guards causes state leakage on Tokio cancellation drops and permanent lock poisoning across threads if the middleware or downstream handler panics.
```rust
use axum::{extract::State, http::Request, middleware::Next, response::Response};
use std::sync::{Arc, Mutex};

#[derive(Clone, Default)]
pub struct AppState {
    pub active_requests: Arc<Mutex<usize>>,
}

// Anti-pattern: std::sync::Mutex held across async execution and unwinding panics.
// If the client disconnects during `next.run()`, task is dropped, but active_requests
// is not decremented, leaking context and corrupting metrics. A panic poisons the lock.
pub async fn track_requests<B>(
    State(state): State<AppState>,
    req: Request<B>,
    next: Next<B>,
) -> Response {
    {
        let mut count = state.active_requests.lock().unwrap();
        *count += 1;
    }
    
    // If cancelled here, decrement is skipped entirely!
    let response = next.run(req).await;
    
    let mut count = state.active_requests.lock().unwrap();
    *count -= 1;
    
    response
}
```

#### Production Standard (Correct)
> **Standard**: Atomic state increment coupled with an RAII Drop guard guarantees decrement occurs under all circumstances: successful completion, Tokio task cancellation, or unwinding panic.
```rust
use axum::{extract::State, http::Request, middleware::Next, response::Response};
use std::sync::{atomic::{AtomicUsize, Ordering}, Arc};

#[derive(Clone, Default)]
pub struct AppState {
    pub active_requests: Arc<AtomicUsize>,
}

// RAII guard ensuring decrement executes even if Tokio task is cancelled or panics
struct RequestCounterGuard(Arc<AtomicUsize>);

impl Drop for RequestCounterGuard {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::Release);
    }
}

pub async fn track_requests<B>(
    State(state): State<AppState>,
    req: Request<B>,
    next: Next<B>,
) -> Response {
    state.active_requests.fetch_add(1, Ordering::Release);
    // RAII token bound to task lifecycle
    let _guard = RequestCounterGuard(Arc::clone(&state.active_requests));

    // If cancelled or unwound here, `_guard` drops automatically, preserving invariants
    next.run(req).await
}
```

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 Tower Middleware Panic Isolation and Cancellation Invariant

Axum Tower Middleware Panic Isolation and Cancellation Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict panic isolation, cancellation safety, and RAII cleanup invariants across Axum and Tower middleware layers. Prevents Tokio task cancellation drops and thread unwinds from poisoning shared state Mutexes, leaking telemetry contexts, or leaving distributed transactional handles dangling. 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: Unprotected Tower Middleware State Mutation and Unhandled Panics Poisoning Shared State on Task Drop 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 DriftUnprotected Tower Middleware State Mutation and Unhandled Panics Poisoning Shared State on Task DropCritical
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 register `tower_http

Engineers MUST ALWAYS register `tower_http::catch_panic::CatchPanicLayer` at the boundary of public Axum routers to intercept unwinding panics before worker thread termination.

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 hold `std

Engineers MUST NOT hold `std::sync::MutexGuard` or `std::sync::RwLockReadGuard`/`RwLockWriteGuard` across `.await` points or within async middleware layers where task cancellation can trigger lock poisoning.

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 Tokio cancellation safety

Code MUST ensure Tokio cancellation safety: state updates across async yield points must either be atomic or guarded by an RAII transaction roll-back token that cleans up transient state on Drop.

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 pass transient request contexts via typed Axum extensions (`req.extensions_mut().insert(...)`) and rely on automatic Drop semantics rather than manual teardown hooks vulnerable to cancellation.

Services MUST pass transient request contexts via typed Axum extensions (`req.extensions_mut().insert(...)`) and rely on automatic Drop semantics rather than manual teardown hooks vulnerable to cancellation.

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

Components NEVER expose shared application state (`axum

Components NEVER expose shared application state (`axum::extract::State`) to partial mutation prior to asynchronous I/O without rollback or commit boundaries.

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 Tower Middleware Panic Isolation and Cancellation Invariant critical for AI coding assistants?

Enforces strict panic isolation, cancellation safety, and RAII cleanup invariants across Axum and Tower middleware layers. Prevents Tokio task cancellation drops and thread unwinds from poisoning shared state Mutexes, leaking telemetry contexts, or leaving distributed transactional handles dangling. 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 (Unprotected Tower Middleware State Mutation and Unhandled Panics Poisoning Shared State on Task Drop) 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