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

Axum 0.8 Sub-State Extraction, Tower Ordering, and Panic Resilience Guardrail

Enforces type-safe sub-state extraction using Axum 0.8's FromRef trait, prevents application crashes via tower-http CatchPanicLayer integration, and guarantees deterministic Tower middleware execution order. Mandates custom error rejections implementing IntoResponse across all extractors to eliminate unformatted plain-text 400/422 failures.

Prohibited Anti-Pattern: Global Arc-bloated state extraction, unshielded panics crashing HTTP worker runtimes, and inverted Tower layer ordering.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Sub-State Extraction, Tower Ordering, and Panic Resilience Guardrail - Enforces type-safe sub-state extraction using Axum 0.8's FromRef trait, prevents application crashes via tower-http CatchPanicLayer integration, and guarantees deterministic Tower middleware execution order. Mandates custom error rejections implementing IntoResponse across all extractors to eliminate unformatted plain-text 400/422 failures.
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-and-tower-resilience"
---

# Axum 0.8 Sub-State Extraction, Tower Ordering, and Panic Resilience Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Arc-bloated state extraction, unshielded panics crashing HTTP worker runtimes, and inverted Tower layer ordering.

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower production invariants. Ensure all shared state is decoupled via `axum::extract::FromRef`, middleware stacks are constructed deterministically with `tower::ServiceBuilder`, and every endpoint is shielded from panics via `CatchPanicLayer` and explicit rejection types.

## Strict Guidelines
- Engineers MUST ALWAYS implement `axum::extract::FromRef<AppState>` for modular sub-states instead of passing a monolithic `AppState` directly into isolated route handlers.
- Engineers MUST wrap all state fields requiring concurrency in `Arc<T>` or ensure inner fields are cheap to clone (`Clone` invariant on `AppState`).
- Middleware stacks constructed via `tower::ServiceBuilder` MUST place `CatchPanicLayer` inside the router perimeter to intercept panics before raw socket drops occur.
- Engineers MUST NOT allow unhandled extractor rejections; custom extractor wrappers or composite rejections implementing `IntoResponse` MUST return structured JSON error envelopes.
- Tower middleware execution order MUST follow the convention where layers added to `ServiceBuilder` execute requests from top to bottom and responses from bottom to top.
- Route handlers MUST NEVER invoke `.unwrap()` or `.expect()` directly on fallible domain operations; handlers MUST return `Result<T, AppError>` where `AppError` implements `axum::response::IntoResponse`.

## Bad vs Good Implementations
### Sub-State Extraction and Panic-Resilient Tower Stack in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler forces a hard dependency on the monolithic AppState instead of decoupling dependencies via axum::extract::FromRef. If the handler encounters an unhandled panic (e.g. unwrap()), the client socket is abruptly closed without a valid HTTP 500 response body because CatchPanicLayer is omitted.
```rust
use axum::{extract::State, routing::get, Json, Router};
use std::sync::Arc;

// Bad: Monolithic state coupled to all handlers, no FromRef, missing panic handling
#[derive(Clone)]
struct AppState {
    db_pool: String, // Simulating pool
    metrics_client: String,
}

async fn get_db(State(state): State<AppState>) -> Json<String> {
    // Bad: Unhandled unwrap panics runtime, drops HTTP socket without clean 500 response
    let db_val = state.db_pool.strip_prefix("db:").unwrap();
    Json(db_val.to_string())
}

pub fn app() -> Router {
    let state = AppState {
        db_pool: "invalid_str".into(),
        metrics_client: "datadog".into(),
    };

    // Bad: No CatchPanicLayer, no TraceLayer, leaks raw 500s or hangs sockets
    Router::new()
        .route("/db", get(get_db))
        .with_state(state)
}
```

#### Production Standard (Correct)
> **Standard**: Implements Axum 0.8 FromRef to isolate handler dependencies to DatabasePool only. Replaces panics with explicit Result<Json<String>, AppError> mapping, and guards the entire service stack with Tower's CatchPanicLayer and TraceLayer.
```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 DatabasePool(Arc<String>);

#[derive(Clone)]
pub struct MetricsClient(Arc<String>);

#[derive(Clone)]
pub struct AppState {
    pub db: DatabasePool,
    pub metrics: MetricsClient,
}

// Decouple sub-states using Axum 0.8 FromRef
impl FromRef<AppState> for DatabasePool {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

impl FromRef<AppState> for MetricsClient {
    fn from_ref(state: &AppState) -> Self {
        state.metrics.clone()
    }
}

// Explicit error type ensuring structured JSON responses
pub enum AppError {
    InvalidFormat,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::InvalidFormat => (StatusCode.BAD_REQUEST, "Invalid format"),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

// Handler depends only on its specific domain state slice
async fn get_db(State(db): State<DatabasePool>) -> Result<Json<String>, AppError> {
    let db_val = db.0.strip_prefix("db:").ok_or(AppError::InvalidFormat)?;
    Ok(Json(db_val.to_string()))
}

pub fn app() -> Router {
    let state = AppState {
        db: DatabasePool(Arc::new("db:production_primary".into())),
        metrics: MetricsClient(Arc::new("datadog".into())),
    };

    // Top-to-bottom request execution with Tower ServiceBuilder
    let middleware_stack = ServiceBuilder::new()
        .layer(CatchPanicLayer::new())
        .layer(TraceLayer::new_for_http());

    Router::new()
        .route("/db", get(get_db))
        .layer(middleware_stack)
        .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 Sub-State Extraction, Tower Ordering, and Panic Resilience Guardrail

Axum 0.8 Sub-State Extraction, Tower Ordering, and Panic Resilience Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces type-safe sub-state extraction using Axum 0.8's FromRef trait, prevents application crashes via tower-http CatchPanicLayer integration, and guarantees deterministic Tower middleware execution order. Mandates custom error rejections implementing IntoResponse across all extractors to eliminate unformatted plain-text 400/422 failures. 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: Global Arc-bloated state extraction, unshielded panics crashing HTTP worker runtimes, and inverted Tower layer ordering. 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 DriftGlobal Arc-bloated state extraction, unshielded panics crashing HTTP worker runtimes, and inverted Tower layer ordering.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 modular sub-states instead of passing a monolithic `AppState` directly into isolated route 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.
2

Engineers MUST wrap all state fields requiring concurrency in `Arc<T>` or ensure inner fields are cheap to clone (`Clone` invariant on `AppState`).

Engineers MUST wrap all state fields requiring concurrency in `Arc<T>` or ensure inner fields are cheap to clone (`Clone` invariant on `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.
3

Middleware stacks constructed via `tower

Middleware stacks constructed via `tower::ServiceBuilder` MUST place `CatchPanicLayer` inside the router perimeter to intercept panics before raw socket drops occur.

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

Engineers MUST NOT allow unhandled extractor rejections

Engineers MUST NOT allow unhandled extractor rejections; custom extractor wrappers or composite rejections implementing `IntoResponse` MUST return structured JSON error envelopes.

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

Tower middleware execution order MUST follow the convention where layers added to `ServiceBuilder` execute requests from top to bottom and responses from bottom to top.

Tower middleware execution order MUST follow the convention where layers added to `ServiceBuilder` execute requests from top to bottom and responses from bottom to top.

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

Route handlers MUST NEVER invoke `.unwrap()` or `.expect()` directly on fallible domain operations

Route handlers MUST NEVER invoke `.unwrap()` or `.expect()` directly on fallible domain operations; handlers MUST return `Result<T, AppError>` where `AppError` implements `axum::response::IntoResponse`.

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 Sub-State Extraction, Tower Ordering, and Panic Resilience Guardrail critical for AI coding assistants?

Enforces type-safe sub-state extraction using Axum 0.8's FromRef trait, prevents application crashes via tower-http CatchPanicLayer integration, and guarantees deterministic Tower middleware execution order. Mandates custom error rejections implementing IntoResponse across all extractors to eliminate unformatted plain-text 400/422 failures. 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 (Global Arc-bloated state extraction, unshielded panics crashing HTTP worker runtimes, and inverted Tower layer ordering.) 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