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

Axum 0.8 Type-Safe State Extractors & Tower Service Composition

Enforces strict type safety and architectural invariants for Axum 0.8 applications using Router::with_state, sub-state derivation via FromRef, and Tower middleware composition. Prohibits untyped Extension state sharing and unhandled extractor rejections that trigger server panics or unformatted 500 responses.

Prohibited Anti-Pattern: Untyped Extension Injection and Unhandled Missing State Panics in Axum 0.8

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Tower Service Composition - Enforces strict type safety and architectural invariants for Axum 0.8 applications using Router::with_state, sub-state derivation via FromRef, and Tower middleware composition. Prohibits untyped Extension state sharing and unhandled extractor rejections that trigger server panics or unformatted 500 responses.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-state-tower-resilience"
---

# Axum 0.8 Type-Safe State Extractors & Tower Service Composition

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped Extension Injection and Unhandled Missing State Panics in Axum 0.8

## System Constraints
You are a Principal Rust Architect enforcing production-grade invariants for Axum 0.8 and Tower ecosystems. Ensure compile-time state checking with `State<T>`, modular composition using `axum::extract::FromRef`, explicit rejection mapping via `IntoResponse`, and fail-safe Tower middleware layering. Deny any use of runtime `Extension` for core application state and eliminate unhandled handler rejections.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` with `Router::with_state` instead of `Extension` for dependency injection and shared state.
- Engineers MUST implement `axum::extract::FromRef` on compound state structs to allow sub-routers and modular handlers to extract isolated dependencies without coupling to global state.
- Engineers MUST wrap all Tower middleware pipelines with explicit catch-panic or error-handling layers (e.g., `CatchPanicLayer` or custom fallback services) before routing traffic.
- Engineers MUST NOT let custom extractors return standard Rust errors; all extractor rejections MUST explicitly implement `IntoResponse` with structured JSON problem details (RFC 7807) and appropriate HTTP status codes.
- Services MUST order Tower middleware correctly: outer layers execute first on requests and last on responses; load shed, timeout, and trace layers must encompass inner routing and handler logic.
- Components NEVER use `Arc::clone(&state)` inside handler signatures; extractors automatically manage clone semantics through `FromRef` and Axum's `State` container.

## Bad vs Good Implementations
### State Extraction: Runtime Extension Anti-Pattern vs Type-Safe FromRef Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension relies on dynamic typemap lookups at runtime. If the layer is missed during router assembly or sub-router nesting, Axum will fail during the request lifecycle with an unhandled runtime error or 500 response, bypassing Rust's compile-time safety guarantees.
```rust
use axum::{extract::Extension, routing::get, Router};
use std::sync::Arc;

#[derive(Clone)]
struct AppState { db_pool: String }

// ANTI-PATTERN: Extension resolves state at runtime.
// If .layer(Extension(...)) is omitted, this panics at runtime with 500 Internal Server Error.
async fn handler(Extension(state): Extension<Arc<AppState>>) -> String {
    format!("Pool: {}", state.db_pool)
}

pub fn app() -> Router {
    Router::new()
        .route("/api", get(handler))
        // Bug: Developer forgot to attach .layer(Extension(Arc::new(AppState { ... })))
}
```

#### Production Standard (Correct)
> **Standard**: Using `State` with `Router::with_state` and `FromRef` enforces compile-time verification that every extractor's required type is satisfied by the router state. If the state type is missing or mismatched, the code fails to compile. Adding `CatchPanicLayer` guarantees zero unhandled runtime panics.
```rust
use axum::{extract::{FromRef, State}, routing::get, Router};
use tower_http::catch_panic::CatchPanicLayer;

#[derive(Clone)]
pub struct DatabaseConfig { pub pool_url: String }

#[derive(Clone)]
pub struct AppState {
    pub db: DatabaseConfig,
}

// Implement FromRef to decouple handler from monolithic AppState
impl FromRef<AppState> for DatabaseConfig {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

// Handler only requests the sub-state it requires
async fn handler(State(db): State<DatabaseConfig>) -> String {
    format!("Pool: {}", db.pool_url)
}

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/api", get(handler))
        .layer(CatchPanicLayer::new())
        // INVARIANT: Compile-time validation that AppState satisfies State<DatabaseConfig>
        .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 Type-Safe State Extractors & Tower Service Composition

Axum 0.8 Type-Safe State Extractors & Tower Service Composition defines an industrial-grade behavioral standard for backend engineering. Enforces strict type safety and architectural invariants for Axum 0.8 applications using Router::with_state, sub-state derivation via FromRef, and Tower middleware composition. Prohibits untyped Extension state sharing and unhandled extractor rejections that trigger server panics or unformatted 500 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: Untyped Extension Injection and Unhandled Missing State Panics in Axum 0.8 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 DriftUntyped Extension Injection and Unhandled Missing State Panics in Axum 0.8Critical
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` with `Router::with_state` instead of `Extension` for dependency injection and shared state.

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` on compound state structs to allow sub-routers and modular handlers to extract isolated dependencies without coupling to global state.

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 wrap all Tower middleware pipelines with explicit catch-panic or error-handling layers (e.g., `CatchPanicLayer` or custom fallback services) before routing traffic.

Engineers MUST wrap all Tower middleware pipelines with explicit catch-panic or error-handling layers (e.g., `CatchPanicLayer` or custom fallback services) before routing traffic.

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 let custom extractors return standard Rust errors

Engineers MUST NOT let custom extractors return standard Rust errors; all extractor rejections MUST explicitly implement `IntoResponse` with structured JSON problem details (RFC 7807) and appropriate 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.
5

Services MUST order Tower middleware correctly

Services MUST order Tower middleware correctly: outer layers execute first on requests and last on responses; load shed, timeout, and trace layers must encompass inner routing and handler logic.

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

Components NEVER use `Arc

Components NEVER use `Arc::clone(&state)` inside handler signatures; extractors automatically manage clone semantics through `FromRef` and Axum's `State` container.

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 Extractors & Tower Service Composition critical for AI coding assistants?

Enforces strict type safety and architectural invariants for Axum 0.8 applications using Router::with_state, sub-state derivation via FromRef, and Tower middleware composition. Prohibits untyped Extension state sharing and unhandled extractor rejections that trigger server panics or unformatted 500 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 (Untyped Extension Injection and Unhandled Missing State Panics in Axum 0.8) 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