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

Rust Axum 0.8 Type-Safe State Extractors & Tower Service Invariants

Enforces compile-time type-safe dependency injection via Axum 0.8 State extractors with FromRef composition and Tower ServiceBuilder layers. Mandates zero-panic resilience through CatchPanicLayer and structured custom rejections across all HTTP boundaries.

Prohibited Anti-Pattern: Runtime Extension Panics and Missing CatchPanicLayer Tower Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Rust Axum 0.8 Type-Safe State Extractors & Tower Service Invariants - Enforces compile-time type-safe dependency injection via Axum 0.8 State extractors with FromRef composition and Tower ServiceBuilder layers. Mandates zero-panic resilience through CatchPanicLayer and structured custom rejections across all HTTP boundaries.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-08-state-extractors-tower-service-guardrail"
---

# Rust Axum 0.8 Type-Safe State Extractors & Tower Service Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime Extension Panics and Missing CatchPanicLayer Tower Boundaries

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower production standards. You must strictly reject runtime-dependent `axum::Extension` for core application state in favor of type-safe `axum::extract::State` and `axum::extract::FromRef`. You must enforce a deterministic Tower `ServiceBuilder` middleware stack that includes explicit panic recovery via `tower_http::catch_panic::CatchPanicLayer`, structured request tracing, and strongly typed `IntoResponse` error handling. Ensure no handler, extractor, or middleware failure causes an uncontrolled process abort or drops TCP connections abruptly.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State<T>` with `axum::extract::FromRef` for sub-state slicing, ensuring all dependency injection is verified at compile time.
- Engineers MUST NOT use `axum::Extension` for application state, database connection pools, or environment configuration, as missing extensions trigger runtime panics.
- Services MUST wrap routes with `tower_http::catch_panic::CatchPanicLayer` customized to return a structured JSON response (e.g., RFC 7807/9457) rather than aborting the connection.
- Engineers MUST implement `axum::response::IntoResponse` for custom application error enums, mapping domain failures to explicit HTTP status codes without unhandled unwrap() or expect() calls.
- Tower middleware stacks MUST be constructed using `tower::ServiceBuilder` with deterministic ordering: TraceLayer -> CatchPanicLayer -> TimeoutLayer -> ConcurrencyLimitLayer -> Route Handlers.

## Bad vs Good Implementations
### State Extraction and Panic Boundary Composition in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `Extension` decouples state injection from the compiler's type system, resulting in runtime panics when state is omitted. Handlers unwrapping values without explicit error types, combined with the absence of `CatchPanicLayer`, terminate TCP connections abruptly without returning HTTP 500 error payloads.
```rust
use axum::{routing::get, Extension, Router, Json};
use std::sync::Arc;
use serde_json::json;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Using Extension causes runtime panic if Extension is omitted in Router
async fn get_user(Extension(state): Extension<Arc<AppState>>) -> Json<serde_json::Value> {
    // ANTI-PATTERN: Unhandled unwrap panics and crashes the worker thread/connection
    let db = state.db_pool.parse::<u32>().unwrap();
    Json(json!({ "db_id": db }))
}

pub fn make_router() -> Router {
    // ANTI-PATTERN: No CatchPanicLayer, no ServiceBuilder, untyped state extension
    Router::new()
        .route("/user", get(get_user))
        // Missing .layer(Extension(Arc::new(AppState { db_pool: "invalid".into() })))
        // will compile but panic at runtime on request!
}
```

#### Production Standard (Correct)
> **Standard**: State is verified at compile-time via `State` and `FromRef`. The application captures unexpected panics via `CatchPanicLayer::custom` and serializes them into structured JSON 500 responses. Expected failures use a typed `AppError` implementing `IntoResponse`.
```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;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
pub struct AppState {
    pub db_pool: Arc<String>,
    pub cache_ttl: u64,
}

// Compile-time verified sub-state extraction
impl FromRef<AppState> for Arc<String> {
    fn from_ref(state: &AppState) -> Self {
        Arc::clone(&state.db_pool)
    }
}

#[derive(Debug)]
pub enum AppError {
    ParseError(String),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, err_msg) = match self {
            AppError::ParseError(msg) => (StatusCode::BAD_REQUEST, msg),
        };
        let body = Json(json!({ "error": err_msg, "status": status.as_u16() }));
        (status, body).into_response()
    }
}

async fn get_user(
    State(pool): State<Arc<String>>,
) -> Result<Json<serde_json::Value>, AppError> {
    let db = pool
        .parse::<u32>()
        .map_err(|e| AppError::ParseError(e.to_string()))?;
    Ok(Json(json!({ "db_id": db })))
}

fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let details = if let Some(s) = err.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = err.downcast_ref::<String>() {
        s.clone()
    } else {
        "Unhandled internal panic".to_string()
    };
    
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": details }))).into_response()
}

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

    Router::new()
        .route("/user", get(get_user))
        .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: Rust Axum 0.8 Type-Safe State Extractors & Tower Service Invariants

Rust Axum 0.8 Type-Safe State Extractors & Tower Service Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe dependency injection via Axum 0.8 State extractors with FromRef composition and Tower ServiceBuilder layers. Mandates zero-panic resilience through CatchPanicLayer and structured custom rejections across all HTTP 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 Extension Panics and Missing CatchPanicLayer Tower Boundaries 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 Extension Panics and Missing CatchPanicLayer Tower BoundariesCritical
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<T>` with `axum::extract::FromRef` for sub-state slicing, ensuring all dependency injection is verified at compile time.

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

Engineers MUST NOT use `axum::Extension` for application state, database connection pools, or environment configuration, as missing extensions trigger runtime panics.

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 wrap routes with `tower_http

Services MUST wrap routes with `tower_http::catch_panic::CatchPanicLayer` customized to return a structured JSON response (e.g., RFC 7807/9457) rather than aborting the connection.

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

Engineers MUST implement `axum::response::IntoResponse` for custom application error enums, mapping domain failures to explicit HTTP status codes without unhandled unwrap() or expect() calls.

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 stacks MUST be constructed using `tower

Tower middleware stacks MUST be constructed using `tower::ServiceBuilder` with deterministic ordering: TraceLayer -> CatchPanicLayer -> TimeoutLayer -> ConcurrencyLimitLayer -> 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Rust Axum 0.8 Type-Safe State Extractors & Tower Service Invariants critical for AI coding assistants?

Enforces compile-time type-safe dependency injection via Axum 0.8 State extractors with FromRef composition and Tower ServiceBuilder layers. Mandates zero-panic resilience through CatchPanicLayer and structured custom rejections across all HTTP 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 Extension Panics and Missing CatchPanicLayer Tower Boundaries) 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

Rust