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

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

Mandates compile-time verified application state extraction using Axum 0.8 State and FromRef sub-states, eliminating runtime untyped Extension lookups. Enforces strict Tower middleware layering order with mandatory panic-catching boundaries and deterministic error response mappings.

Prohibited Anti-Pattern: Runtime state injection via Extension<T> and unprotected Tower middleware stacks causing silent connection drops on 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 & Tower Service Composition - Mandates compile-time verified application state extraction using Axum 0.8 State and FromRef sub-states, eliminating runtime untyped Extension lookups. Enforces strict Tower middleware layering order with mandatory panic-catching boundaries and deterministic error response mappings.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-state-tower-resilience"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime state injection via Extension<T> and unprotected Tower middleware stacks causing silent connection drops on panics.

## System Constraints
You are a Principal Rust Backend Engineer enforcing Axum 0.8 type-safe state extraction, modular FromRef sub-state delegation, and Tower middleware hygiene. You mandate strictly typed State<T>, ordered ServiceBuilder execution pipelines, and zero-panic crash barriers.

## Strict Guidelines
- Engineers MUST ALWAYS use axum::extract::State with axum::extract::FromRef for sub-states instead of dynamic Extension<T> lookups.
- Engineers MUST NOT rely on default panic propagation; all public HTTP routes MUST be shielded by tower_http::catch_panic::CatchPanicLayer with a typed JSON error response converter.
- Code MUST assemble Tower middleware using tower::ServiceBuilder with inbound layers ordered from outermost (first to receive request) to innermost.
- Services MUST implement explicit domain error conversions to axum::response::Response via IntoResponse instead of returning unmapped Result types or calling unwrap/expect in handler bodies.
- Router modules MUST expose typed sub-routers with parameterized states that combine safely into parent routers using with_state or FromRef derivations.

## Bad vs Good Implementations
### State Extraction and Tower Middleware Stack Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension<T> bypasses Rust's compile-time type verification, converting missing state configuration into runtime HTTP 500 errors. Lack of CatchPanicLayer causes abrupt TCP disconnects on worker threads during unexpected panics.
```rust
use axum::{extract::Extension, routing::get, Router};
use tower_http::trace::TraceLayer;

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

// Anti-pattern: Using Extension causes runtime crashes if omitted from layer
async fn handler(Extension(state): Extension<AppState>) -> String {
    // Anti-pattern: direct panic terminates connection without proper HTTP 500 envelope
    if state.db_pool.is_empty() {
        panic!("Database connection lost");
    }
    format!("Connected to {}", state.db_pool)
}

pub fn app() -> Router {
    Router::new()
        .route("/status", get(handler))
        .layer(TraceLayer::new_for_http())
        // Missing State configuration; runtime lookup failure
}
```

#### Production Standard (Correct)
> **Standard**: Axum 0.8 State<T> with FromRef guarantees type safety at compile time. Tower's ServiceBuilder correctly chains CatchPanicLayer as an outer boundary before TraceLayer, converting panics into structured HTTP 500 JSON responses without terminating TCP connections.
```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 AppState {
    pub db_pool: Arc<String>,
    pub cache: Arc<String>,
}

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

impl FromRef<AppState> for DatabaseState {
    fn from_ref(app: &AppState) -> Self {
        DatabaseState(Arc::clone(&app.db_pool))
    }
}

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let body = Json(json!({"error": "internal_server_error", "message": "An unexpected error occurred."}));
    (StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}

async fn handler(State(db): State<DatabaseState>) -> Result<Json<serde_json::Value>, StatusCode> {
    Ok(Json(json!({"status": "healthy", "database": *db.0})))
}

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

    Router::new()
        .route("/status", get(handler))
        .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 Composition

Rust Axum 0.8 Type-Safe State Extractors & Tower Service Composition defines an industrial-grade behavioral standard for backend engineering. Mandates compile-time verified application state extraction using Axum 0.8 State and FromRef sub-states, eliminating runtime untyped Extension lookups. Enforces strict Tower middleware layering order with mandatory panic-catching boundaries and deterministic error response mappings. 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 state injection via Extension<T> and unprotected Tower middleware stacks causing silent connection drops on 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 DriftRuntime state injection via Extension<T> and unprotected Tower middleware stacks causing silent connection drops on panics.Critical
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 with axum::extract::FromRef for sub-states instead of dynamic Extension<T> lookups.

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 rely on default panic propagation

Engineers MUST NOT rely on default panic propagation; all public HTTP routes MUST be shielded by tower_http::catch_panic::CatchPanicLayer with a typed JSON error response converter.

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

Code MUST assemble Tower middleware using tower

Code MUST assemble Tower middleware using tower::ServiceBuilder with inbound layers ordered from outermost (first to receive request) to innermost.

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 implement explicit domain error conversions to axum

Services MUST implement explicit domain error conversions to axum::response::Response via IntoResponse instead of returning unmapped Result types or calling unwrap/expect in handler bodies.

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

Router modules MUST expose typed sub-routers with parameterized states that combine safely into parent routers using with_state or FromRef derivations.

Router modules MUST expose typed sub-routers with parameterized states that combine safely into parent routers using with_state or FromRef derivations.

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

Mandates compile-time verified application state extraction using Axum 0.8 State and FromRef sub-states, eliminating runtime untyped Extension lookups. Enforces strict Tower middleware layering order with mandatory panic-catching boundaries and deterministic error response mappings. 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 state injection via Extension<T> and unprotected Tower middleware stacks causing silent connection drops on 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