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

Axum 0.8 Type-Safe State Extractors & Tower Service Composition

Mandates compile-time type-safe state injection via Axum 0.8's State extractor and FromRef sub-states instead of dynamic Extension lookups. Enforces strict Tower layer composition order with mandatory panic isolation boundaries to guarantee zero unhandled rejection crashes in production.

Prohibited Anti-Pattern: Using dynamic Extensions or unisolated Tower layers causing runtime panic drops and state omission crashes

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 - Mandates compile-time type-safe state injection via Axum 0.8's State extractor and FromRef sub-states instead of dynamic Extension lookups. Enforces strict Tower layer composition order with mandatory panic isolation boundaries to guarantee zero unhandled rejection crashes in production.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-state-and-tower-composition"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Using dynamic Extensions or unisolated Tower layers causing runtime panic drops and state omission crashes

## System Constraints
You are a Principal Systems Architect enforcing Rust Axum 0.8 and Tower production guardrails. Enforce compile-time type-checked State extractors, explicit subrouter state transitions via FromRef, and zero unhandled panic rejections across all Tower service stacks.

## Strict Guidelines
- Engineers MUST ALWAYS use axum::extract::State instead of axum::extract::Extension for application dependencies.
- Engineers MUST implement FromRef<ParentState> for nested state slices when composing sub-routers to maintain compile-time safety across modular boundaries.
- Services MUST enclose Tower middleware stacks within a terminal CatchPanicLayer and HandleErrorLayer to prevent unhandled service failures from terminating worker threads or abruptly dropping TCP connections.
- Code MUST map custom extractor errors explicitly to types implementing IntoResponse with structured RFC 7807/JSON payloads; unwrap() or expect() within extractors is strictly prohibited.
- Engineers MUST apply middleware layers in the canonical order: outer CatchPanicLayer, followed by TraceLayer/MetricsLayer, TimeoutLayer (wrapped in HandleErrorLayer), and finally inner authentication/authorization layers.

## Bad vs Good Implementations
### Axum 0.8 State Extraction and Resilient Tower Layer Composition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension relies on dynamic typemap lookups that fail at runtime instead of compile-time if omitted or mismatched. Omitting CatchPanicLayer allows uncaught thread panics to drop client TCP streams without an HTTP 500 response.
```rust
use axum::{extract::Extension, routing::get, Router};
use std::sync::Arc;
use tower_http::trace::TraceLayer;

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

// ANTI-PATTERN: Dynamic Extension lookup fails at runtime if omitted;
// Missing CatchPanicLayer and HandleErrorLayer means panics drop TCP connection.
async fn handler(Extension(state): Extension<Arc<AppState>>) -> String {
    format!("Connected to {}", state.db_pool)
}

pub fn app() -> Router {
    Router::new()
        .route("/data", get(handler))
        .layer(TraceLayer::new_for_http()) // Fails to catch panics or map BoxError
        // Missing .layer(Extension(state)) or .with_state(state) triggers runtime panic at first request
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes Axum 0.8 type-safe State and FromRef to verify state wiring at compile-time. Employs Tower ServiceBuilder with CatchPanicLayer at the outermost boundary and HandleErrorLayer around TimeoutLayer to guarantee robust, panic-safe error responses.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::{
    catch_panic::CatchPanicLayer,
    timeout::TimeoutLayer,
    trace::TraceLayer,
};

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

#[derive(Clone)]
pub struct DatabaseState(pub String);

// Modular FromRef enables sub-router isolation with compile-time state guarantees
impl FromRef<AppState> for DatabaseState {
    fn from_ref(state: &AppState) -> Self {
        DatabaseState(state.db_pool.clone())
    }
}

async fn handler(State(db): State<DatabaseState>) -> impl IntoResponse {
    (StatusCode::OK, format!("Connected to {}", db.0))
}

pub fn app(state: AppState) -> Router {
    // Tower middleware pipeline with panic boundaries and handled timeouts
    let middleware = ServiceBuilder::new()
        .layer(CatchPanicLayer::new())
        .layer(TraceLayer::new_for_http())
        .layer(tower::layer::layer_fn(axum::error_handling::HandleErrorLayer::new(
            |_err: tower::BoxError| async move {
                (StatusCode::REQUEST_TIMEOUT, "Request timed out").into_response()
            },
        )))
        .layer(TimeoutLayer::new(Duration::from_secs(30)));

    Router::new()
        .route("/data", get(handler))
        .layer(middleware)
        .with_state(state)
}
```

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. Mandates compile-time type-safe state injection via Axum 0.8's State extractor and FromRef sub-states instead of dynamic Extension lookups. Enforces strict Tower layer composition order with mandatory panic isolation boundaries to guarantee zero unhandled rejection crashes in production. 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 dynamic Extensions or unisolated Tower layers causing runtime panic drops and state omission crashes 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 dynamic Extensions or unisolated Tower layers causing runtime panic drops and state omission crashesCritical
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 application dependencies.

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 FromRef<ParentState> for nested state slices when composing sub-routers to maintain compile-time safety across modular boundaries.

Engineers MUST implement FromRef<ParentState> for nested state slices when composing sub-routers to maintain compile-time safety across modular boundaries.

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 enclose Tower middleware stacks within a terminal CatchPanicLayer and HandleErrorLayer to prevent unhandled service failures from terminating worker threads or abruptly dropping TCP connections.

Services MUST enclose Tower middleware stacks within a terminal CatchPanicLayer and HandleErrorLayer to prevent unhandled service failures from terminating worker threads or abruptly dropping TCP connections.

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 map custom extractor errors explicitly to types implementing IntoResponse with structured RFC 7807/JSON payloads

Code MUST map custom extractor errors explicitly to types implementing IntoResponse with structured RFC 7807/JSON payloads; unwrap() or expect() within extractors is strictly prohibited.

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 apply middleware layers in the canonical order

Engineers MUST apply middleware layers in the canonical order: outer CatchPanicLayer, followed by TraceLayer/MetricsLayer, TimeoutLayer (wrapped in HandleErrorLayer), and finally inner authentication/authorization layers.

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?

Mandates compile-time type-safe state injection via Axum 0.8's State extractor and FromRef sub-states instead of dynamic Extension lookups. Enforces strict Tower layer composition order with mandatory panic isolation boundaries to guarantee zero unhandled rejection crashes in production. 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 dynamic Extensions or unisolated Tower layers causing runtime panic drops and state omission crashes) 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