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

Axum 0.8 Modular Sub-State Extraction, CatchPanicLayer, and Tower ServiceBuilder

Enforces type-safe modular state extraction using Axum 0.8's FromRef pattern, deterministic Tower ServiceBuilder layer ordering, and mandatory CatchPanicLayer integration. Prevents monolithic state coupling, middleware execution inversion, and unhandled thread panics dropping HTTP connections without RFC 7807/JSON error responses.

Prohibited Anti-Pattern: Monolithic State Passing, Inverted Tower Middleware Chains, and Unhandled Panic Dropouts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Modular Sub-State Extraction, CatchPanicLayer, and Tower ServiceBuilder - Enforces type-safe modular state extraction using Axum 0.8's FromRef pattern, deterministic Tower ServiceBuilder layer ordering, and mandatory CatchPanicLayer integration. Prevents monolithic state coupling, middleware execution inversion, and unhandled thread panics dropping HTTP connections without RFC 7807/JSON error responses.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-state-tower-guardrail"
---

# Axum 0.8 Modular Sub-State Extraction, CatchPanicLayer, and Tower ServiceBuilder

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic State Passing, Inverted Tower Middleware Chains, and Unhandled Panic Dropouts

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower production invariants. Mandate strict encapsulation via `axum::extract::FromRef`, enforce deterministic layer ordering with `tower::ServiceBuilder`, and guarantee zero unhandled panic aborts through `CatchPanicLayer`.

## Strict Guidelines
- Engineers MUST ALWAYS wrap `AppState` fields in `Arc` or use cheap-to-clone handles (e.g., `sqlx::Pool`), deriving `Clone` on the outer `AppState`.
- Engineers MUST implement `axum::extract::FromRef<AppState>` for leaf state slices rather than passing the monolithic `AppState` into decoupled domain routers and handlers.
- Engineers MUST compose middleware using `tower::ServiceBuilder` to maintain intuitive top-to-bottom execution order, placing `CatchPanicLayer` at the outermost boundary.
- Handlers and extractors MUST NEVER leak raw panics or unformatted rejections to the client; all panic unwinds must be caught and transformed into structured HTTP 500 JSON responses.
- Sub-routers MUST be merged or nested using `.with_state()` appropriately to maintain compile-time state guarantees without boxing or dynamic type erasure.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler extracts the entire monolithic AppState, violating encapsulation. A runtime panic aborts the request, terminating the HTTP connection without a structured response because CatchPanicLayer is omitted. Layering directly onto Router without ServiceBuilder makes execution order fragile.
```rust
use axum::{routing::get, Router, extract::State};
use tower_http::trace::TraceLayer;

// Anti-pattern: Handlers tightly coupled to monolithic AppState,
// missing CatchPanicLayer, and incorrect layer stacking order.
#[derive(Clone)]
struct AppState {
    db: String, // Simulating a pool or heavy client
    redis: String,
}

async fn get_db(State(state): State<AppState>) -> String {
    if state.db.is_empty() {
        panic!("database configuration is corrupt"); // Drops TCP connection abruptly
    }
    state.db
}

pub fn app() -> Router {
    let state = AppState { db: "postgres".into(), redis: "redis".into() };
    // Middleware added directly can reverse expected execution order
    Router::new()
        .route("/db", get(get_db))
        .layer(TraceLayer::new_for_http()) // Panics bypass logging/formatting
        .with_state(state)
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to Axum 0.8 standards: AppState implements FromRef to decouple handler dependencies. Tower ServiceBuilder provides clear layer execution order. CatchPanicLayer intercepts unwinding panics and serializes a standard JSON error response.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json,
    Router,
};
use serde_json::json;
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::{
    catch_panic::CatchPanicLayer,
    trace::TraceLayer,
};

#[derive(Clone)]
pub struct AppState {
    pub db: Arc<String>,
    pub redis: Arc<String>,
}

// Modular extraction: Handler only knows about the dependency it requires
impl FromRef<AppState> for Arc<String> {
    fn from_ref(app_state: &AppState) -> Self {
        app_state.db.clone()
    }
}

async fn get_db(State(db): State<Arc<String>>) -> String {
    (*db).clone()
}

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

pub fn app() -> Router {
    let state = AppState {
        db: Arc::new("postgres://localhost:5432".into()),
        redis: Arc::new("redis://localhost:6379".into()),
    };

    // Outermost layers run first: CatchPanic catches everything inside
    let middleware = ServiceBuilder::new()
        .layer(CatchPanicLayer::custom(handle_panic))
        .layer(TraceLayer::new_for_http());

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

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 Modular Sub-State Extraction, CatchPanicLayer, and Tower ServiceBuilder

Axum 0.8 Modular Sub-State Extraction, CatchPanicLayer, and Tower ServiceBuilder defines an industrial-grade behavioral standard for backend engineering. Enforces type-safe modular state extraction using Axum 0.8's FromRef pattern, deterministic Tower ServiceBuilder layer ordering, and mandatory CatchPanicLayer integration. Prevents monolithic state coupling, middleware execution inversion, and unhandled thread panics dropping HTTP connections without RFC 7807/JSON error responses. 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 Passing, Inverted Tower Middleware Chains, and Unhandled Panic Dropouts 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 Passing, Inverted Tower Middleware Chains, and Unhandled Panic DropoutsCritical
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 wrap `AppState` fields in `Arc` or use cheap-to-clone handles (e.g., `sqlx

Engineers MUST ALWAYS wrap `AppState` fields in `Arc` or use cheap-to-clone handles (e.g., `sqlx::Pool`), deriving `Clone` on the outer `AppState`.

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 implement `axum

Engineers MUST implement `axum::extract::FromRef<AppState>` for leaf state slices rather than passing the monolithic `AppState` into decoupled domain routers and handlers.

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 compose middleware using `tower

Engineers MUST compose middleware using `tower::ServiceBuilder` to maintain intuitive top-to-bottom execution order, placing `CatchPanicLayer` at the outermost boundary.

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

Handlers and extractors MUST NEVER leak raw panics or unformatted rejections to the client

Handlers and extractors MUST NEVER leak raw panics or unformatted rejections to the client; all panic unwinds must be caught and transformed into structured HTTP 500 JSON responses.

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

Sub-routers MUST be merged or nested using `.with_state()` appropriately to maintain compile-time state guarantees without boxing or dynamic type erasure.

Sub-routers MUST be merged or nested using `.with_state()` appropriately to maintain compile-time state guarantees without boxing or dynamic type erasure.

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 Modular Sub-State Extraction, CatchPanicLayer, and Tower ServiceBuilder critical for AI coding assistants?

Enforces type-safe modular state extraction using Axum 0.8's FromRef pattern, deterministic Tower ServiceBuilder layer ordering, and mandatory CatchPanicLayer integration. Prevents monolithic state coupling, middleware execution inversion, and unhandled thread panics dropping HTTP connections without RFC 7807/JSON error responses. 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 Passing, Inverted Tower Middleware Chains, and Unhandled Panic Dropouts) 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