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-service-guardrail

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

Enforces type-safe state propagation using Axum 0.8 sub-states via axum::extract::FromRef, deterministic Tower ServiceBuilder middleware sequencing, and panic-resilient request pipelines with zero unhandled extractor rejections.

Prohibited Anti-Pattern: Monolithic Untyped State Injection and Inverse Tower Middleware Stacking Causing Unhandled Panics and Compile Failure

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 type-safe state propagation using Axum 0.8 sub-states via axum::extract::FromRef, deterministic Tower ServiceBuilder middleware sequencing, and panic-resilient request pipelines with zero unhandled extractor rejections.
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-tower-service-guardrail"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic Untyped State Injection and Inverse Tower Middleware Stacking Causing Unhandled Panics and Compile Failure

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower Service production standards. You must mandate compile-time type safety via axum::extract::State, modular state decomposition via axum::extract::FromRef, deterministic middleware ordering via tower::ServiceBuilder, and zero-panic error handling with tower_http::catch_panic::CatchPanicLayer and custom extractor rejection types.

## Strict Guidelines
- Engineers MUST ALWAYS use axum::extract::State<T> instead of axum::Extension for core application dependencies, context, and database pools.
- Engineers MUST implement axum::extract::FromRef<ParentState> for modular sub-states to enable isolated route handlers without coupling modules to the monolithic parent state.
- Engineers MUST ALWAYS construct middleware pipelines with tower::ServiceBuilder to ensure correct top-to-bottom execution order, placing CatchPanicLayer and TraceLayer outside timeout or authorization layers.
- Engineers MUST implement axum::response::IntoResponse on custom extractor rejections to eliminate raw HTTP 500 internal server error fallbacks on client deserialization failures.
- Engineers MUST NOT call Router::with_state multiple times with mismatched state types; sub-routers MUST consume sub-states or rely on FromRef to preserve type invariance across router merges.
- Services MUST wrap handler panics via CatchPanicLayer with custom response mappers to guarantee structured JSON error envelopes on internal failures.
- Components NEVER store request-scoped mutable state directly inside State<T>; shared state MUST explicitly use Arc<T> or concurrency primitives like tokio::sync::RwLock.

## Bad vs Good Implementations
### State Decomposition with FromRef and Tower Middleware Ordering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension for shared state circumvents Axum's compile-time router state verification, fails at runtime if the extension is omitted, breaks modularity by exposing the entire AppState to leaf handlers, and lacks CatchPanicLayer protection against unexpected panics.
```rust
use axum::{routing::get, Extension, Router};
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;

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

// ANTI-PATTERN: Using Extension loses compile-time state guarantees,
// and manual sub-state extraction requires handler to know entire AppState.
async fn handler(Extension(state): Extension<AppState>) -> String {
    format!("DB: {}", state.db)
}

fn app(state: AppState) -> Router {
    Router::new()
        .route("/data", get(handler))
        // ANTI-PATTERN: ServiceBuilder without CatchPanicLayer;
        // Extension layer injected after routes without type-level enforcement.
        .layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))
        .layer(Extension(state))
}
```

#### Production Standard (Correct)
> **Standard**: State<DbPool> ensures compile-time dependency verification. Implementing FromRef<AppState> keeps sub-handlers decoupled from monolithic structs. tower::ServiceBuilder guarantees CatchPanicLayer catches errors from inner layers before returning a deterministic, structured JSON response.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Json,
    Router,
};
use serde_json::json;
use tower::ServiceBuilder;
use tower_http::{
    catch_panic::CatchPanicLayer,
    trace::TraceLayer,
};

#[derive(Clone)]
pub struct AppState {
    pub db_pool: DbPool,
    pub api_client: ApiClient,
}

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

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

// INVARIANT: Sub-state decoupling via FromRef allows modular routers
impl FromRef<AppState> for DbPool {
    fn from_ref(app_state: &AppState) -> Self {
        app_state.db_pool.clone()
    }
}

// Handler only binds to the exact dependency it requires
async fn get_data(State(db): State<DbPool>) -> impl IntoResponse {
    Json(json!({ "database_status": db.0 }))
}

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 create_router(state: AppState) -> Router {
    // INVARIANT: Deterministic outer-to-inner middleware execution via ServiceBuilder
    let middleware_stack = ServiceBuilder::new()
        .layer(CatchPanicLayer::custom(handle_panic))
        .layer(TraceLayer::new_for_http());

    Router::new()
        .route("/data", get(get_data))
        .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 type-safe state propagation using Axum 0.8 sub-states via axum::extract::FromRef, deterministic Tower ServiceBuilder middleware sequencing, and panic-resilient request pipelines with zero unhandled extractor rejections. 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: Monolithic Untyped State Injection and Inverse Tower Middleware Stacking Causing Unhandled Panics and Compile Failure 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 DriftMonolithic Untyped State Injection and Inverse Tower Middleware Stacking Causing Unhandled Panics and Compile FailureCritical
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> instead of axum::Extension for core application dependencies, context, and database pools.

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<ParentState> for modular sub-states to enable isolated route handlers without coupling modules to the monolithic parent 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 ALWAYS construct middleware pipelines with tower

Engineers MUST ALWAYS construct middleware pipelines with tower::ServiceBuilder to ensure correct top-to-bottom execution order, placing CatchPanicLayer and TraceLayer outside timeout or 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.
4

Engineers MUST implement axum

Engineers MUST implement axum::response::IntoResponse on custom extractor rejections to eliminate raw HTTP 500 internal server error fallbacks on client deserialization failures.

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 NOT call Router

Engineers MUST NOT call Router::with_state multiple times with mismatched state types; sub-routers MUST consume sub-states or rely on FromRef to preserve type invariance across router merges.

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

Services MUST wrap handler panics via CatchPanicLayer with custom response mappers to guarantee structured JSON error envelopes on internal failures.

Services MUST wrap handler panics via CatchPanicLayer with custom response mappers to guarantee structured JSON error envelopes on internal failures.

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

Components NEVER store request-scoped mutable state directly inside State<T>

Components NEVER store request-scoped mutable state directly inside State<T>; shared state MUST explicitly use Arc<T> or concurrency primitives like tokio::sync::RwLock.

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 type-safe state propagation using Axum 0.8 sub-states via axum::extract::FromRef, deterministic Tower ServiceBuilder middleware sequencing, and panic-resilient request pipelines with zero unhandled extractor rejections. 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 (Monolithic Untyped State Injection and Inverse Tower Middleware Stacking Causing Unhandled Panics and Compile Failure) 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