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

Axum 0.8 Type-Safe State Extraction and Tower Middleware Invariants

Enforce strict compile-time state safety in Axum 0.8 using type-safe State extractors and modular FromRef sub-states instead of dynamic Extension containers. Mandate deterministic Tower middleware stack ordering with CatchPanicLayer and ServiceBuilder to guarantee zero unhandled panics or silent connection drops.

Prohibited Anti-Pattern: Relying on Dynamic Extensions, Monolithic AppState Coupling, and Omitting CatchPanicLayer in Tower Middleware Stacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Extraction and Tower Middleware Invariants - Enforce strict compile-time state safety in Axum 0.8 using type-safe State extractors and modular FromRef sub-states instead of dynamic Extension containers. Mandate deterministic Tower middleware stack ordering with CatchPanicLayer and ServiceBuilder to guarantee zero unhandled panics or silent connection drops.
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-invariants"
---

# Axum 0.8 Type-Safe State Extraction and Tower Middleware Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Relying on Dynamic Extensions, Monolithic AppState Coupling, and Omitting CatchPanicLayer in Tower Middleware Stacks

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 state extraction and Tower service composition standards. You must strictly eliminate dynamic runtime `Extension` lookups for application dependencies in favor of type-safe `axum::extract::State`. Require modular sub-state extraction via `FromRef` to prevent route-handler coupling to monolithic state structs. Ensure that every Axum router integrates Tower's `CatchPanicLayer` and `TraceLayer` in the correct execution order, guaranteeing zero unhandled panics and explicit, structured 500 Internal Server Error responses.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` for shared application state dependencies and NEVER use `axum::extract::Extension` for core application state.
- Engineers MUST implement `axum::extract::FromRef` on monolithic application state structs to allow sub-routers and handlers to extract only the minimal dependencies (e.g., `State(pool): State<PgPool>`) they require.
- State structs passed to `axum::Router::with_state` MUST be cheaply cloneable, either containing `Arc<T>` wrappers or consisting exclusively of clone-efficient handles (`PgPool`, `reqwest::Client`).
- Services MUST ALWAYS wrap outer router instances with `tower_http::catch_panic::CatchPanicLayer` to intercept unhandled panics and return standardized HTTP 500 JSON envelopes instead of dropping TCP connections.
- Tower middleware pipelines MUST be composed using `tower::ServiceBuilder` with layers ordered logically: `CatchPanicLayer` outermost, followed by `TraceLayer`, timeouts, and authorization layers.

## Bad vs Good Implementations
### State Extraction & Tower Middleware Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension bypasses compile-time verification, meaning a missing state binding fails only during runtime execution. Handlers depend directly on the monolithic AppState struct, violating encapsulation. Additionally, omitting CatchPanicLayer causes runtime panics inside async tasks to abruptly sever the HTTP connection.
```rust
use axum::{routing::get, Extension, Router, Json};
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
    db_pool: String, // Simulating DB pool
    auth_secret: String,
}

// ANTI-PATTERN: Extension resolves at runtime. If omitted, this panics at runtime with a 500 error.
// Handlers take the entire AppState rather than granular components.
async fn get_user(Extension(state): Extension<Arc<AppState>>) -> Json<String> {
    Json(format!("User fetched using: {}", state.db_pool))
}

pub fn build_router() -> Router {
    // ANTI-PATTERN: Missing CatchPanicLayer; an unhandled panic will abruptly terminate the stream.
    // Uses Extension layer which bypasses compile-time state checking in Axum 0.8.
    let state = Arc::new(AppState {
        db_pool: "postgres://...".into(),
        auth_secret: "secret".into(),
    });

    Router::new()
        .route("/user", get(get_user))
        .layer(Extension(state))
}
```

#### Production Standard (Correct)
> **Standard**: State extraction is verified at compile-time using `axum::extract::State` and `FromRef`. The handler only couples to `DatabaseConfig`. The Tower middleware stack utilizes `CatchPanicLayer::custom` and `TraceLayer` to capture and convert panics into structured JSON responses.
```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::ServiceBuilder;
use tower_http::{catch_panic::CatchPanicLayer, trace::TraceLayer};

#[derive(Clone)]
pub struct DatabaseConfig {
    pub pool_url: String,
}

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

// INVARIANT: Sub-state extraction via FromRef enforces compile-time dependency isolation
impl FromRef<AppState> for DatabaseConfig {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

// Handler only extracts what it needs; compile-time checked
async fn get_user(State(db): State<DatabaseConfig>) -> impl IntoResponse {
    Json(json!({ "status": "ok", "pool": db.pool_url }))
}

fn handle_panic(err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let details = if let Some(s) = err.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = err.downcast_ref::<String>() {
        s.clone()
    } else {
        "Unknown panic occurred".to_string()
    };
    
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": details }))).into_response()
}

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

    Router::new()
        .route("/user", get(get_user))
        .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: Axum 0.8 Type-Safe State Extraction and Tower Middleware Invariants

Axum 0.8 Type-Safe State Extraction and Tower Middleware Invariants defines an industrial-grade behavioral standard for backend engineering. Enforce strict compile-time state safety in Axum 0.8 using type-safe State extractors and modular FromRef sub-states instead of dynamic Extension containers. Mandate deterministic Tower middleware stack ordering with CatchPanicLayer and ServiceBuilder to guarantee zero unhandled panics or silent connection drops. 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: Relying on Dynamic Extensions, Monolithic AppState Coupling, and Omitting CatchPanicLayer in Tower Middleware Stacks 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 DriftRelying on Dynamic Extensions, Monolithic AppState Coupling, and Omitting CatchPanicLayer in Tower Middleware StacksCritical
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` for shared application state dependencies and NEVER use `axum::extract::Extension` for core 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.
2

Engineers MUST implement `axum

Engineers MUST implement `axum::extract::FromRef` on monolithic application state structs to allow sub-routers and handlers to extract only the minimal dependencies (e.g., `State(pool): State<PgPool>`) they require.

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

State structs passed to `axum

State structs passed to `axum::Router::with_state` MUST be cheaply cloneable, either containing `Arc<T>` wrappers or consisting exclusively of clone-efficient handles (`PgPool`, `reqwest::Client`).

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

Services MUST ALWAYS wrap outer router instances with `tower_http

Services MUST ALWAYS wrap outer router instances with `tower_http::catch_panic::CatchPanicLayer` to intercept unhandled panics and return standardized HTTP 500 JSON envelopes instead of 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.
5

Tower middleware pipelines MUST be composed using `tower

Tower middleware pipelines MUST be composed using `tower::ServiceBuilder` with layers ordered logically: `CatchPanicLayer` outermost, followed by `TraceLayer`, timeouts, and 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 Extraction and Tower Middleware Invariants critical for AI coding assistants?

Enforce strict compile-time state safety in Axum 0.8 using type-safe State extractors and modular FromRef sub-states instead of dynamic Extension containers. Mandate deterministic Tower middleware stack ordering with CatchPanicLayer and ServiceBuilder to guarantee zero unhandled panics or silent connection drops. 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 (Relying on Dynamic Extensions, Monolithic AppState Coupling, and Omitting CatchPanicLayer in Tower Middleware Stacks) 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