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

Rust Axum 0.8 Type-Safe State Extractors and Tower Middleware Composition

Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef traits while guaranteeing panic-free Tower middleware composition. Prohibits untyped Extension state passing and mandates exhaustive IntoResponse rejection handling across all boundary extractors and service layers.

Prohibited Anti-Pattern: Untyped Extension Passing, Monolithic State Coupling, and Unhandled Tower Service Panics

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Rust Axum 0.8 Type-Safe State Extractors and Tower Middleware Composition - Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef traits while guaranteeing panic-free Tower middleware composition. Prohibits untyped Extension state passing and mandates exhaustive IntoResponse rejection handling across all boundary extractors and service layers.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-08-state-tower-resilience"
---

# Rust Axum 0.8 Type-Safe State Extractors and Tower Middleware Composition

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped Extension Passing, Monolithic State Coupling, and Unhandled Tower Service Panics

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 state extraction, FromRef sub-state isolation, and Tower service resilience. Axum 0.8 requires strict compile-time state typing, modular sub-state extraction through FromRef, and zero unhandled middleware/extractor rejections. Ensure all router trees leverage State over Extension, Tower layers handle errors before reaching the client via HandleErrorLayer, and all custom extractors map rejections deterministically to HTTP response codes.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` and implement or derive `axum::extract::FromRef` on sub-states to keep route handlers decoupled from the global `AppState`.
- Engineers MUST NOT use `axum::Extension` for static dependency injection or shared application services; `Extension` is strictly restricted to dynamic, request-scoped metadata injected by middleware.
- Engineers MUST wrap fallible Tower middleware layers (such as `tower::timeout::TimeoutLayer` or rate limiters) with `tower::ServiceBuilder` and `axum::error_handling::HandleErrorLayer` to prevent unhandled service error panics.
- Custom extractors MUST implement `FromRequestParts` or `FromRequest` with an explicit, strongly typed `Rejection` that implements `IntoResponse`, preventing default opaque 500 internal server errors.
- State-dependent middleware MUST be integrated via `axum::middleware::from_fn_with_state` passing typed sub-state slices rather than casting down raw extensions.
- Components NEVER panic within extractor bodies or middleware services; all fallible operations MUST be lifted into `Result<T, CustomRejection>`.

## Bad vs Good Implementations
### Axum 0.8 State Injection & Tower Layer Composition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension for dependency injection bypasses Axum 0.8's compile-time type-safety; if the extension is missing from the router stack, the handler panics at runtime. Furthermore, applying fallible Tower layers like TimeoutLayer without HandleErrorLayer leaves service errors unhandled, causing compilation errors or runtime 500 panics.
```rust
use axum::{extract::Extension, routing::get, Router};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::timeout::TimeoutLayer;
use std::time::Duration;

struct AppState {
    db_pool: String,
}

// ANTI-PATTERN: Untyped Extension extraction causes runtime panics if omitted.
// Missing FromRef causes handlers to depend on monolithic state.
async fn handler(Extension(state): Extension<Arc<AppState>>) -> String {
    state.db_pool.clone()
}

pub fn app() -> Router {
    let state = Arc::new(AppState { db_pool: "postgres://...".into() });
    
    Router::new()
        .route("/data", get(handler))
        // ANTI-PATTERN: Unhandled TimeoutLayer errors will cause Axum to fail to compile or panic at runtime
        .layer(ServiceBuilder::new().layer(TimeoutLayer::new(Duration::from_secs(5))))
        .layer(Extension(state))
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Axum 0.8's compile-time State extractor combined with the FromRef trait, isolating dependencies so handlers only request their exact sub-state. Fallible Tower middleware is safely handled using HandleErrorLayer to map timeouts into standard HTTP 408 responses with zero panics.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    error_handling::HandleErrorLayer,
    BoxError,
    Router,
};
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::timeout::TimeoutLayer;

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

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

// Type-safe sub-state projection via FromRef
impl FromRef<AppState> for DatabasePool {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

// Handlers depend only on the minimal sub-state required
async fn handler(State(db): State<DatabasePool>) -> impl IntoResponse {
    (StatusCode::OK, db.0)
}

async fn handle_timeout_error(err: BoxError) -> (StatusCode, String) {
    if err.is::<tower::timeout::error::Elapsed>() {
        (StatusCode::REQUEST_TIMEOUT, "Request timed out".to_string())
    } else {
        (StatusCode::INTERNAL_SERVER_ERROR, format!("Unhandled service error: {err}"))
    }
}

pub fn build_app(state: AppState) -> Router {
    let middleware = ServiceBuilder::new()
        .layer(HandleErrorLayer::new(handle_timeout_error))
        .layer(TimeoutLayer::new(Duration::from_secs(5)));

    Router::new()
        .route("/data", get(handler))
        .layer(middleware)
        .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 and Tower Middleware Composition

Rust Axum 0.8 Type-Safe State Extractors and Tower Middleware Composition defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef traits while guaranteeing panic-free Tower middleware composition. Prohibits untyped Extension state passing and mandates exhaustive IntoResponse rejection handling across all boundary extractors and service layers. 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 Extension Passing, Monolithic State Coupling, and Unhandled Tower Service Panics 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 Extension Passing, Monolithic State Coupling, and Unhandled Tower Service PanicsCritical
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` and implement or derive `axum::extract::FromRef` on sub-states to keep route handlers decoupled from the global `AppState`.

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 static dependency injection or shared application services; `Extension` is strictly restricted to dynamic, request-scoped metadata injected by middleware.

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 fallible Tower middleware layers (such as `tower

Engineers MUST wrap fallible Tower middleware layers (such as `tower::timeout::TimeoutLayer` or rate limiters) with `tower::ServiceBuilder` and `axum::error_handling::HandleErrorLayer` to prevent unhandled service error 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.
4

Custom extractors MUST implement `FromRequestParts` or `FromRequest` with an explicit, strongly typed `Rejection` that implements `IntoResponse`, preventing default opaque 500 internal server errors.

Custom extractors MUST implement `FromRequestParts` or `FromRequest` with an explicit, strongly typed `Rejection` that implements `IntoResponse`, preventing default opaque 500 internal server 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.
5

State-dependent middleware MUST be integrated via `axum

State-dependent middleware MUST be integrated via `axum::middleware::from_fn_with_state` passing typed sub-state slices rather than casting down raw extensions.

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

Components NEVER panic within extractor bodies or middleware services

Components NEVER panic within extractor bodies or middleware services; all fallible operations MUST be lifted into `Result<T, CustomRejection>`.

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 and Tower Middleware Composition critical for AI coding assistants?

Enforces compile-time type-safe dependency injection via Axum 0.8 State and FromRef traits while guaranteeing panic-free Tower middleware composition. Prohibits untyped Extension state passing and mandates exhaustive IntoResponse rejection handling across all boundary extractors and service layers. 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 Extension Passing, Monolithic State Coupling, and Unhandled Tower Service Panics) 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