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

Axum 0.8 Type-Safe State Extractors & Tower Middleware Production Guardrails

Enforces strict type-safe state extraction via Axum 0.8 State and FromRef patterns, eliminates runtime Extension panics, mandates outer-boundary CatchPanicLayer integration, and standardizes infallible Tower middleware composition.

Prohibited Anti-Pattern: Untyped runtime Extension extraction, misordered Tower middleware layers, and unhandled panic drops.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Tower Middleware Production Guardrails - Enforces strict type-safe state extraction via Axum 0.8 State and FromRef patterns, eliminates runtime Extension panics, mandates outer-boundary CatchPanicLayer integration, and standardizes infallible Tower middleware composition.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-type-safe-state-tower-service-guardrails"
---

# Axum 0.8 Type-Safe State Extractors & Tower Middleware Production Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped runtime Extension extraction, misordered Tower middleware layers, and unhandled panic drops.

## System Constraints
You are a Principal Rust Systems Architect enforcing Axum 0.8 and Tower service invariants. Mandate compile-time verified State extraction via FromRef, strict Tower layer ordering, explicit rejection handling, and zero unhandled panic rejections across all service boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` instead of `axum::extract::Extension` for core application dependencies (pools, configs, clients) to guarantee compile-time existence validation.
- Engineers MUST implement `axum::extract::FromRef<AppState>` for modular sub-state extraction to allow isolated nested sub-routers without breaking root state propagation.
- Engineers MUST wrap all public routes with `tower_http::catch_panic::CatchPanicLayer` converting thread panics into structured, RFC 7807/JSON 500 Internal Server Error responses.
- Code MUST observe the exact Tower layer execution order: layers registered via `.layer()` execute from bottom-to-top on requests, and top-to-bottom on responses. In Axum, outer infrastructure layers (Trace, CatchPanic, Timeout) MUST wrap the top-level Router.
- Services MUST NOT use fallible Tower services without a preceding `tower::load_shed::LoadShedLayer` or `tower::timeout::TimeoutLayer` combined with an explicit error handler or `HandleErrorLayer`.
- Handlers MUST NEVER rely on Axum's default plain-text extractor rejections; custom extractors or app-level error wrappers MUST implement `IntoResponse` emitting consistent structured JSON errors.
- All application state types stored in `State<S>` MUST implement `Clone + Send + Sync + 'static`, utilizing `std::sync::Arc` internally for heavy or non-copy handles.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension defer resolution to runtime. If an engineer forgets to inject the Extension layer or refactors the type signature, Axum panics or returns runtime 500 errors. Furthermore, lacking CatchPanicLayer means worker thread panics tear down connections without sending a valid HTTP response.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct DatabasePool;
struct AppState { db: Arc<DatabasePool> }

// ANTI-PATTERN: Extension extracts dynamically at runtime.
// If .layer(Extension(...)) is omitted, this panics at runtime with an HTTP 500 error!
async fn handler(Extension(db): Extension<Arc<DatabasePool>>) -> &'static str {
    let _ = db;
    "ok"
}

pub fn make_app() -> Router {
    // Lacks CatchPanicLayer: any panic inside handler aborts the request stream abruptly.
    Router::new()
        .route("/data", get(handler))
        // Fragile: Forgot to add Extension(AppState) or Extension(Arc<DatabasePool>)
}
```

#### Production Standard (Correct)
> **Standard**: Type safety is guaranteed by Axum's State extractor and FromRef implementation, failing at compile-time if state dependencies are missing. CatchPanicLayer::custom ensures thread panics are translated into structured JSON responses rather than broken TCP connections.
```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_http::catch_panic::CatchPanicLayer;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
pub struct DatabasePool;

#[derive(Clone)]
pub struct AppState {
    pub db: Arc<DatabasePool>,
}

// Invariant: Modular sub-state via FromRef allows loose coupling for sub-routers
impl FromRef<AppState> for Arc<DatabasePool> {
    fn from_ref(state: &AppState) -> Self {
        Arc::clone(&state.db)
    }
}

// Handlers extract typed State verified at compile-time
async fn handler(State(db): State<Arc<DatabasePool>>) -> impl IntoResponse {
    let _ = db;
    Json(json!({ "status": "ok" }))
}

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

pub fn make_app(state: AppState) -> Router {
    Router::new()
        .route("/data", get(handler))
        .with_state(state)
        // Tower execution order: catch_panic wraps the execution boundary
        .layer(CatchPanicLayer::custom(handle_panic))
        .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 Extractors & Tower Middleware Production Guardrails

Axum 0.8 Type-Safe State Extractors & Tower Middleware Production Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces strict type-safe state extraction via Axum 0.8 State and FromRef patterns, eliminates runtime Extension panics, mandates outer-boundary CatchPanicLayer integration, and standardizes infallible Tower middleware composition. 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 runtime Extension extraction, misordered Tower middleware layers, and unhandled panic drops. 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 runtime Extension extraction, misordered Tower middleware layers, and unhandled panic drops.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` instead of `axum::extract::Extension` for core application dependencies (pools, configs, clients) to guarantee compile-time existence validation.

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<AppState>` for modular sub-state extraction to allow isolated nested sub-routers without breaking root state propagation.

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

Engineers MUST wrap all public routes with `tower_http::catch_panic::CatchPanicLayer` converting thread panics into structured, RFC 7807/JSON 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 observe the exact Tower layer execution order

Code MUST observe the exact Tower layer execution order: layers registered via `.layer()` execute from bottom-to-top on requests, and top-to-bottom on responses. In Axum, outer infrastructure layers (Trace, CatchPanic, Timeout) MUST wrap the top-level Router.

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 NOT use fallible Tower services without a preceding `tower

Services MUST NOT use fallible Tower services without a preceding `tower::load_shed::LoadShedLayer` or `tower::timeout::TimeoutLayer` combined with an explicit error handler or `HandleErrorLayer`.

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

Handlers MUST NEVER rely on Axum's default plain-text extractor rejections

Handlers MUST NEVER rely on Axum's default plain-text extractor rejections; custom extractors or app-level error wrappers MUST implement `IntoResponse` emitting consistent structured JSON errors.

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.
7

All application state types stored in `State<S>` MUST implement `Clone + Send + Sync + 'static`, utilizing `std

All application state types stored in `State<S>` MUST implement `Clone + Send + Sync + 'static`, utilizing `std::sync::Arc` internally for heavy or non-copy handles.

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 Middleware Production Guardrails critical for AI coding assistants?

Enforces strict type-safe state extraction via Axum 0.8 State and FromRef patterns, eliminates runtime Extension panics, mandates outer-boundary CatchPanicLayer integration, and standardizes infallible Tower middleware composition. 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 runtime Extension extraction, misordered Tower middleware layers, and unhandled panic drops.) 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