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

Axum 0.8 Type-Safe State Composition and Tower Service Invariants

Enforces strict type safety and panic resilience across Axum 0.8 State extractors and Tower middleware stacks. Mandates compile-time substate extraction via FromRef, prevents router state decoupling panics, and guarantees zero unhandled rejection panics through CatchPanic layers and custom IntoResponse error boundaries.

Prohibited Anti-Pattern: Runtime router panics and broken substate isolation caused by untyped state degradation, missing CatchPanic middleware, and unconstrained Tower layers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Composition and Tower Service Invariants - Enforces strict type safety and panic resilience across Axum 0.8 State extractors and Tower middleware stacks. Mandates compile-time substate extraction via FromRef, prevents router state decoupling panics, and guarantees zero unhandled rejection panics through CatchPanic layers and custom IntoResponse error boundaries.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-state-tower-resilience-standard"
---

# Axum 0.8 Type-Safe State Composition and Tower Service Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime router panics and broken substate isolation caused by untyped state degradation, missing CatchPanic middleware, and unconstrained Tower layers.

## System Constraints
You are a Principal Rust Systems Architect specializing in Axum 0.8 and Tower services. Enforce compile-time type-safe substate extraction via FromRef, eliminate untyped Extension usage for application state, require explicit Tower middleware ordering with CatchPanicLayer at the perimeter, and guarantee all fallible handler paths evaluate into deterministic, unwrap-free IntoResponse types.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` paired with `axum::extract::FromRef` for substate extraction instead of monolithic global references or untyped `Extension` containers.
- Engineers MUST NOT place arbitrary Tower middleware between routers and `.with_state()`; router state MUST be fully resolved via `.with_state()` at the router boundary before outer service composition.
- Services MUST mount `tower_http::catch_panic::CatchPanicLayer` before any business logic middleware to intercept panics and convert them into explicit 500 Internal Server Error responses.
- Code MUST NEVER invoke `.unwrap()` or `.expect()` inside Axum handler signatures or extractor implementations; all fallible domain operations must convert cleanly via custom error enums implementing `axum::response::IntoResponse`.
- Components MUST implement `Clone` on state structs cheaply using `std::sync::Arc` internally rather than wrapping the outer `State` struct in multiple redundant `Arc` levels.

## Bad vs Good Implementations
### Substate Extraction & Tower Perimeter Defense

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension discards compile-time type validation; missing extensions produce runtime panics with 500 responses or connection drops. Lack of CatchPanicLayer leaves worker threads vulnerable to unhandled panics crashing or terminating HTTP requests abruptly.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Runtime panics if Extension is missing from Router;
// state is not type-safe at compile-time, unhandled panic if handler unwraps.
async fn handler(Extension(pool): Extension<Arc<AppState>>) -> String {
    // Will panic at runtime if another handler or middleware fails
    format!("Connected to: {}", pool.db_pool)
}

pub fn make_app() -> Router {
    Router::new()
        .route("/data", get(handler))
        // Missing CatchPanicLayer; Extension added without compile-time validation
        .layer(Extension(Arc::new(AppState { db_pool: "postgres://localhost".into() })))
}
```

#### Production Standard (Correct)
> **Standard**: State extraction is verified at compile-time using Axum 0.8 State and FromRef. CatchPanicLayer isolates thread failures safely, and all fallible branches map deterministically through IntoResponse.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::sync::Arc;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::trace::TraceLayer;

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

#[derive(Clone)]
pub struct AppState {
    pub db_pool: DatabasePool,
}

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

// Handler is strictly coupled only to its substate requirement
async fn handler(State(pool): State<DatabasePool>) -> Result<String, AppError> {
    Ok(format!("Connected to: {}", pool.0))
}

enum AppError {
    Internal,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
    }
}

pub fn make_app() -> Router {
    let state = AppState {
        db_pool: DatabasePool(Arc::new("postgres://localhost".into())),
    };

    Router::new()
        .route("/data", get(handler))
        .with_state(state)
        .layer(CatchPanicLayer::new())
        .layer(TraceLayer::new_for_http())
}
```

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 Type-Safe State Composition and Tower Service Invariants

Axum 0.8 Type-Safe State Composition and Tower Service Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict type safety and panic resilience across Axum 0.8 State extractors and Tower middleware stacks. Mandates compile-time substate extraction via FromRef, prevents router state decoupling panics, and guarantees zero unhandled rejection panics through CatchPanic layers and custom IntoResponse error boundaries. 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: Runtime router panics and broken substate isolation caused by untyped state degradation, missing CatchPanic middleware, and unconstrained Tower layers. 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 DriftRuntime router panics and broken substate isolation caused by untyped state degradation, missing CatchPanic middleware, and unconstrained Tower layers.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 use `axum

Engineers MUST ALWAYS use `axum::extract::State` paired with `axum::extract::FromRef` for substate extraction instead of monolithic global references or untyped `Extension` containers.

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 place arbitrary Tower middleware between routers and `.with_state()`

Engineers MUST NOT place arbitrary Tower middleware between routers and `.with_state()`; router state MUST be fully resolved via `.with_state()` at the router boundary before outer service composition.

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

Services MUST mount `tower_http

Services MUST mount `tower_http::catch_panic::CatchPanicLayer` before any business logic middleware to intercept panics and convert them into explicit 500 Internal Server Error 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.
4

Code MUST NEVER invoke `.unwrap()` or `.expect()` inside Axum handler signatures or extractor implementations

Code MUST NEVER invoke `.unwrap()` or `.expect()` inside Axum handler signatures or extractor implementations; all fallible domain operations must convert cleanly via custom error enums implementing `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.
5

Components MUST implement `Clone` on state structs cheaply using `std

Components MUST implement `Clone` on state structs cheaply using `std::sync::Arc` internally rather than wrapping the outer `State` struct in multiple redundant `Arc` levels.

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 Type-Safe State Composition and Tower Service Invariants critical for AI coding assistants?

Enforces strict type safety and panic resilience across Axum 0.8 State extractors and Tower middleware stacks. Mandates compile-time substate extraction via FromRef, prevents router state decoupling panics, and guarantees zero unhandled rejection panics through CatchPanic layers and custom IntoResponse error boundaries. 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 (Runtime router panics and broken substate isolation caused by untyped state degradation, missing CatchPanic middleware, and unconstrained Tower layers.) 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