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

Axum 0.8 Type-Safe State Extractors & Tower Service Composition

Mandate compile-time type-safe state injection using Axum 0.8 `State` extractors with modular `FromRef` derivations instead of fallback runtime `Extension` layers. Enforce robust Tower middleware ordering via `ServiceBuilder` with properly configured `CatchPanicLayer` to prevent unhandled thread panics from dropping TCP connections without RFC-compliant HTTP error responses.

Prohibited Anti-Pattern: Using Untyped Extension Extractors with Misordered Tower Layers Causing Silent 500s and Connection Resets on Panic

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 - Mandate compile-time type-safe state injection using Axum 0.8 `State` extractors with modular `FromRef` derivations instead of fallback runtime `Extension` layers. Enforce robust Tower middleware ordering via `ServiceBuilder` with properly configured `CatchPanicLayer` to prevent unhandled thread panics from dropping TCP connections without RFC-compliant HTTP 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-extractors-tower-service-guardrail"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Using Untyped Extension Extractors with Misordered Tower Layers Causing Silent 500s and Connection Resets on Panic

## System Constraints
You are a Principal Rust Systems Architect enforcing industrial-grade invariants for Axum 0.8 web services and Tower middleware stacks. You mandate compile-time type safety via State extractors and zero unhandled panic aborts.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of `axum::extract::Extension` for injecting shared application dependencies into route handlers.
- Engineers MUST derive or implement `axum::extract::FromRef` for sub-states to keep nested routers and handlers decoupled from the root monolithic state struct.
- Root application states MUST implement `Clone + Send + Sync + 'static`, wrapping mutable or heavy resources in `Arc` or atomic wrappers (`Arc<AppStateInner>`).
- Services MUST position `tower_http::catch_panic::CatchPanicLayer` at the boundary of the Tower stack to convert panics into structured HTTP 500 responses and prevent socket drops.
- Middleware stacks MUST be constructed using `tower::ServiceBuilder` to ensure deterministic execution order and prevent unintended type inference breakage during router nesting.
- Engineers MUST NOT leak raw panic payloads, unformatted backtraces, or database connection strings to HTTP response bodies in release profiles.

## Bad vs Good Implementations
### State Extraction & Middleware Stack Composition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `Extension` circumvents compile-time type guarantees: if an engineer forgets to register the extension, Axum compiles cleanly but fails at runtime on every request. Additionally, lacking `CatchPanicLayer` means internal panics abruptly tear down the TCP connection without returning a valid HTTP 500 response.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Extension fails at RUNTIME with a 500 if omitted from router
async fn get_user(Extension(state): Extension<Arc<AppState>>) -> String {
    // ANTI-PATTERN: Direct unhandled unwrap causes thread panic and dropped TCP socket
    let db = &state.db_pool;
    if db.is_empty() {
        panic!("Database connection missing!");
    }
    format!("Connected to {}", db)
}

pub fn app() -> Router {
    Router::new()
        .route("/users", get(get_user))
        // Missing State/Extension configuration compiles fine, but fails catastrophically at runtime!
}
```

#### Production Standard (Correct)
> **Standard**: Using `State` and `with_state` guarantees compile-time validation that the handler dependencies exist. Implementing `FromRef` allows granular sub-state extraction. The Tower `ServiceBuilder` layers `CatchPanicLayer` with custom panic handling to ensure all unexpected panics are caught and translated into structured HTTP 500 responses.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::trace::TraceLayer;

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

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

// Enables handlers to extract State<DatabaseConfig> directly instead of the full AppState
impl FromRef<AppState> for DatabaseConfig {
    fn from_ref(app_state: &AppState) -> Self {
        app_state.db.clone()
    }
}

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
}

async fn get_user(State(db): State<DatabaseConfig>) -> Result<String, StatusCode> {
    if db.connection_str.is_empty() {
        return Err(StatusCode::SERVICE_UNAVAILABLE);
    }
    Ok(format!("Connected to {}", db.connection_str))
}

pub fn create_app(state: AppState) -> Router {
    let middleware = ServiceBuilder::new()
        .layer(CatchPanicLayer::custom(handle_panic))
        .layer(TraceLayer::new_for_http());

    Router::new()
        .route("/users", get(get_user))
        .layer(middleware)
        .with_state(state) // State completeness verified strictly at compile-time
}
```

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. Mandate compile-time type-safe state injection using Axum 0.8 `State` extractors with modular `FromRef` derivations instead of fallback runtime `Extension` layers. Enforce robust Tower middleware ordering via `ServiceBuilder` with properly configured `CatchPanicLayer` to prevent unhandled thread panics from dropping TCP connections without RFC-compliant HTTP 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: Using Untyped Extension Extractors with Misordered Tower Layers Causing Silent 500s and Connection Resets on Panic 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 DriftUsing Untyped Extension Extractors with Misordered Tower Layers Causing Silent 500s and Connection Resets on PanicCritical
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` instead of `axum::extract::Extension` for injecting shared application dependencies into 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 derive or implement `axum

Engineers MUST derive or implement `axum::extract::FromRef` for sub-states to keep nested routers and handlers decoupled from the root monolithic state struct.

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

Root application states MUST implement `Clone + Send + Sync + 'static`, wrapping mutable or heavy resources in `Arc` or atomic wrappers (`Arc<AppStateInner>`).

Root application states MUST implement `Clone + Send + Sync + 'static`, wrapping mutable or heavy resources in `Arc` or atomic wrappers (`Arc<AppStateInner>`).

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

Services MUST position `tower_http

Services MUST position `tower_http::catch_panic::CatchPanicLayer` at the boundary of the Tower stack to convert panics into structured HTTP 500 responses and prevent socket drops.

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

Middleware stacks MUST be constructed using `tower

Middleware stacks MUST be constructed using `tower::ServiceBuilder` to ensure deterministic execution order and prevent unintended type inference breakage during router nesting.

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

Engineers MUST NOT leak raw panic payloads, unformatted backtraces, or database connection strings to HTTP response bodies in release profiles.

Engineers MUST NOT leak raw panic payloads, unformatted backtraces, or database connection strings to HTTP response bodies in release profiles.

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?

Mandate compile-time type-safe state injection using Axum 0.8 `State` extractors with modular `FromRef` derivations instead of fallback runtime `Extension` layers. Enforce robust Tower middleware ordering via `ServiceBuilder` with properly configured `CatchPanicLayer` to prevent unhandled thread panics from dropping TCP connections without RFC-compliant HTTP 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 (Using Untyped Extension Extractors with Misordered Tower Layers Causing Silent 500s and Connection Resets on Panic) 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