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

Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Stack Standard

Enforces compile-time verified state extraction using Axum 0.8 State extractors with modular FromRef implementations, eliminating unsafe runtime Extension lookups. Mandates deterministic Tower middleware composition with explicit panic boundaries and tracing layers to guarantee zero unhandled worker panics and complete observability.

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

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Stack Standard - Enforces compile-time verified state extraction using Axum 0.8 State extractors with modular FromRef implementations, eliminating unsafe runtime Extension lookups. Mandates deterministic Tower middleware composition with explicit panic boundaries and tracing layers to guarantee zero unhandled worker panics and complete observability.
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-production-standard"
---

# Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Stack Standard

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

## System Constraints
You are a Principal Backend Architect specializing in high-throughput, memory-safe Rust services using Axum 0.8 and Tower. Your objective is to enforce strict compile-time verification of application state and deterministic middleware stack composition. You reject untyped Extension lookups for essential application dependencies, demand explicit FromRef implementations for sub-state modularity, and require robust panic boundaries via CatchPanicLayer to prevent service instability.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` rather than `axum::Extension` for core application dependencies such as connection pools, configuration, and caching clients.
- Engineers MUST implement `axum::extract::FromRef` on compound state structs when sub-routers require isolated or modular slices of the application state.
- Engineers MUST wrap handlers and services with `tower_http::catch_panic::CatchPanicLayer` to prevent Tokio worker thread crashes and map unhandled panics into structured HTTP 500 responses.
- Engineers MUST order Tower middleware deterministically using `tower::ServiceBuilder`: outer layers MUST handle telemetry and panic catching, while inner layers handle timeouts, rate limiting, and authorization.
- Engineers MUST supply state via `Router::with_state` before nesting or binding to a listener, ensuring the root application router type is `Router<()>`.
- Engineers MUST NOT rely on implicit default panic hooks; panic responses MUST be standardized using custom panic handlers that redact internal stack traces from client payloads while emitting error spans to tracing subscribers.

## Bad vs Good Implementations
### Type-Safe State and Resilient Tower Middleware Composition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension shifts dependency verification from compile-time to runtime. If an engineer forgets to register the Extension layer or refactors state initialization, requests invoking this handler will panic with a 500 error at runtime. Furthermore, omitting CatchPanicLayer leaves the service vulnerable to unhandled panics that bypass telemetry and crash worker threads.
```rust
use axum::{routing::get, Extension, Router};
use std::sync::Arc;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Using Extension relies on runtime injection.
// If .layer(Extension(...)) is omitted, this handler panics at runtime.
async fn handler(Extension(state): Extension<Arc<AppState>>) -> String {
    format!("Connected to {}", state.db_pool)
}

pub fn make_app() -> Router {
    // Lacks CatchPanicLayer: Unhandled panics crash worker context and drop connections
    Router::new()
        .route("/api/resource", get(handler))
        // If developer forgets to add Extension layer here, compiler does not complain
}
```

#### Production Standard (Correct)
> **Standard**: Using `axum::extract::State` and `FromRef` leverages Rust's type system to ensure all dependencies are present at compile-time; missing state fails the build. Tower's `ServiceBuilder` composes `TraceLayer` and a custom `CatchPanicLayer` on the outer boundary, guaranteeing that runtime panics are caught, logged via tracing, and sanitized into safe HTTP 500 responses without crashing Tokio runtimes.
```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,
    trace::TraceLayer,
};

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

// Sub-state extraction via FromRef ensures modularity
impl FromRef<AppState> for Arc<String> {
    fn from_ref(input: &AppState) -> Self {
        input.db_pool.clone()
    }
}

fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    tracing::error!("Unhandled panic captured: {:?}", err);
    (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
}

// Handlers statically verify state existence at compile-time
async fn handler(State(pool): State<Arc<String>>) -> String {
    format!("Connected to {pool}")
}

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

    Router::new()
        .route("/api/resource", get(handler))
        .layer(middleware)
        .with_state(state) // Router<AppState> becomes Router<()>
}
```

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 & Resilient Tower Middleware Stack Standard

Axum 0.8 Type-Safe State Extractors & Resilient Tower Middleware Stack Standard defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time verified state extraction using Axum 0.8 State extractors with modular FromRef implementations, eliminating unsafe runtime Extension lookups. Mandates deterministic Tower middleware composition with explicit panic boundaries and tracing layers to guarantee zero unhandled worker panics and complete observability. 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 Tower Panic 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 Tower Panic 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` rather than `axum::Extension` for core application dependencies such as connection pools, configuration, and caching clients.

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 when sub-routers require isolated or modular slices of the application 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 handlers and services with `tower_http

Engineers MUST wrap handlers and services with `tower_http::catch_panic::CatchPanicLayer` to prevent Tokio worker thread crashes and map unhandled panics into structured HTTP 500 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

Engineers MUST order Tower middleware deterministically using `tower

Engineers MUST order Tower middleware deterministically using `tower::ServiceBuilder`: outer layers MUST handle telemetry and panic catching, while inner layers handle timeouts, rate limiting, and authorization.

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

Engineers MUST supply state via `Router

Engineers MUST supply state via `Router::with_state` before nesting or binding to a listener, ensuring the root application router type is `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.
6

Engineers MUST NOT rely on implicit default panic hooks

Engineers MUST NOT rely on implicit default panic hooks; panic responses MUST be standardized using custom panic handlers that redact internal stack traces from client payloads while emitting error spans to tracing subscribers.

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 & Resilient Tower Middleware Stack Standard critical for AI coding assistants?

Enforces compile-time verified state extraction using Axum 0.8 State extractors with modular FromRef implementations, eliminating unsafe runtime Extension lookups. Mandates deterministic Tower middleware composition with explicit panic boundaries and tracing layers to guarantee zero unhandled worker panics and complete observability. 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 Tower Panic 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

Axum