This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-08-state-tower-guardrails

Axum 0.8 Substate Derivation, Tower Layer Ordering, and Zero-Panic Invariants

Enforces type-safe modular substate extraction via axum::extract::FromRef, non-blocking asynchronous concurrency, strict Tower ServiceBuilder middleware ordering, and deterministic panic recovery to prevent connection resets and state-leak vulnerabilities in Axum 0.8 microservices.

Prohibited Anti-Pattern: Monolithic state extraction with blocking standard mutexes and unhandled Tower panic drops causing connection resets and thread starvation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Substate Derivation, Tower Layer Ordering, and Zero-Panic Invariants - Enforces type-safe modular substate extraction via axum::extract::FromRef, non-blocking asynchronous concurrency, strict Tower ServiceBuilder middleware ordering, and deterministic panic recovery to prevent connection resets and state-leak vulnerabilities in Axum 0.8 microservices.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-state-tower-guardrails"
---

# Axum 0.8 Substate Derivation, Tower Layer Ordering, and Zero-Panic Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic state extraction with blocking standard mutexes and unhandled Tower panic drops causing connection resets and thread starvation.

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower Service production standards. You mandate type-safe substate derivation via FromRef, non-blocking Tokio synchronization primitives, correct Tower middleware pipeline ordering, and zero-panic runtime guarantees across all HTTP services.

## Strict Guidelines
- Engineers MUST ALWAYS implement axum::extract::FromRef<AppState> for substate types to decouple handlers from monolithic application states.
- Engineers MUST ALWAYS install tower_http::catch_panic::CatchPanicLayer with a custom JSON error handler at the router root to prevent unhandled handler panics from severing client TCP streams without an HTTP response.
- Engineers MUST NOT hold std::sync::MutexGuard or any non-Send synchronization primitives across .await points; use atomic types, tokio::sync primitives, or read-mostly channels.
- Code SHOULD arrange Tower middleware layers through tower::ServiceBuilder in the canonical sequence: TraceLayer -> CatchPanicLayer -> TimeoutLayer -> CorsLayer -> Identity/State Enrichment -> Application Router.
- Handlers MUST NEVER unwrap() or expect() Fallible operations directly inside route handlers; return custom Result<T, AppError> implementing IntoResponse with explicit HTTP status codes.
- Routers MUST NOT mix different state types without explicit nest_service or pre-applying .with_state() to sub-routers before mounting them to the parent router.

## Bad vs Good Implementations
### Axum 0.8 State Extraction and Tower Middleware Stack

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly depends on monolithic Arc<AppState>, holds a std::sync::Mutex across a Tokio suspension point (blocking the thread pool and risking deadlocks/Send failures), unhandled mutex poisoning via unwrap(), and omits CatchPanicLayer, which drops connections abruptly on panics.
```rust
use axum::{routing::get, Router, extract::State};
use std::sync::{Arc, Mutex};

struct AppState {
    counter: Mutex<u64>,
    db_url: String,
}

// ANTI-PATTERN: Tightly couples handler to monolithic state,
// holds standard synchronous MutexGuard across await,
// and panics with unwrap() with no panic rejection boundary.
async fn handler(State(state): State<Arc<AppState>>) -> String {
    let mut lock = state.counter.lock().unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    *lock += 1;
    format!("Count: {}", *lock)
}

pub fn app() -> Router {
    Router::new()
        .route("/count", get(handler))
        .with_state(Arc::new(AppState {
            counter: Mutex::new(0),
            db_url: "postgres://...".into(),
        }))
}
```

#### Production Standard (Correct)
> **Standard**: Implements FromRef to decouple handler dependencies, eliminates mutex-locking overhead via lock-free atomic operations, and wraps the router in a TraceLayer and CatchPanicLayer that guarantees client connections receive a structured 500 JSON payload instead of an unexpected TCP reset.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json, Router,
};
use serde_json::json;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
pub struct AppState {
    pub counter: Arc<AtomicU64>,
    pub db_url: Arc<str>,
}

// Modular substate extraction prevents leaking entire application context
impl FromRef<AppState> for Arc<AtomicU64> {
    fn from_ref(state: &AppState) -> Self {
        Arc::clone(&state.counter)
    }
}

async fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(json!({"error": "INTERNAL_SERVER_ERROR", "message": "An unexpected error occurred"})),
    )
        .into_response()
}

// Handler only extracts the substate it requires; thread-safe atomic mutation across async tasks
async fn handler(State(counter): State<Arc<AtomicU64>>) -> Json<serde_json::Value> {
    let count = counter.fetch_add(1, Ordering::Relaxed) + 1;
    Json(json!({ "count": count }))
}

pub fn app() -> Router {
    let state = AppState {
        counter: Arc::new(AtomicU64::new(0)),
        db_url: Arc::from("postgres://localhost/db"),
    };

    let middleware = ServiceBuilder::new()
        .layer(TraceLayer::new_for_http())
        .layer(CatchPanicLayer::custom(handle_panic));

    Router::new()
        .route("/count", get(handler))
        .layer(middleware)
        .with_state(state)
}
```

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 Substate Derivation, Tower Layer Ordering, and Zero-Panic Invariants

Axum 0.8 Substate Derivation, Tower Layer Ordering, and Zero-Panic Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces type-safe modular substate extraction via axum::extract::FromRef, non-blocking asynchronous concurrency, strict Tower ServiceBuilder middleware ordering, and deterministic panic recovery to prevent connection resets and state-leak vulnerabilities in Axum 0.8 microservices. 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: Monolithic state extraction with blocking standard mutexes and unhandled Tower panic drops causing connection resets and thread 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 DriftMonolithic state extraction with blocking standard mutexes and unhandled Tower panic drops causing connection resets and thread starvation.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 ALWAYS implement axum

Engineers MUST ALWAYS implement axum::extract::FromRef<AppState> for substate types to decouple handlers from monolithic application states.

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 ALWAYS install tower_http

Engineers MUST ALWAYS install tower_http::catch_panic::CatchPanicLayer with a custom JSON error handler at the router root to prevent unhandled handler panics from severing client TCP streams without an 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.
3

Engineers MUST NOT hold std

Engineers MUST NOT hold std::sync::MutexGuard or any non-Send synchronization primitives across .await points; use atomic types, tokio::sync primitives, or read-mostly 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.
4

Code SHOULD arrange Tower middleware layers through tower

Code SHOULD arrange Tower middleware layers through tower::ServiceBuilder in the canonical sequence: TraceLayer -> CatchPanicLayer -> TimeoutLayer -> CorsLayer -> Identity/State Enrichment -> Application Router.

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 unwrap() or expect() Fallible operations directly inside route handlers

Handlers MUST NEVER unwrap() or expect() Fallible operations directly inside route handlers; return custom Result<T, AppError> implementing IntoResponse with explicit HTTP status codes.

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

Routers MUST NOT mix different state types without explicit nest_service or pre-applying .with_state() to sub-routers before mounting them to the parent router.

Routers MUST NOT mix different state types without explicit nest_service or pre-applying .with_state() to sub-routers before mounting them to the parent router.

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 Substate Derivation, Tower Layer Ordering, and Zero-Panic Invariants critical for AI coding assistants?

Enforces type-safe modular substate extraction via axum::extract::FromRef, non-blocking asynchronous concurrency, strict Tower ServiceBuilder middleware ordering, and deterministic panic recovery to prevent connection resets and state-leak vulnerabilities in Axum 0.8 microservices. 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 (Monolithic state extraction with blocking standard mutexes and unhandled Tower panic drops causing connection resets and thread 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