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

Rust Axum 0.8 Compile-Time State Extraction and Tower Middleware Invariants

Mandate compile-time type-safe state injection using Axum 0.8 State and FromRef traits instead of runtime Extension extractors. Enforce deterministic Tower middleware ordering via ServiceBuilder with CatchPanicLayer and customized rejection types to eliminate unhandled connection drops.

Prohibited Anti-Pattern: Runtime Panics from Untyped Extension Extractors, Unhandled Panics Crashing HTTP Connections, and Broken Middleware Stacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Rust Axum 0.8 Compile-Time State Extraction and Tower Middleware Invariants - Mandate compile-time type-safe state injection using Axum 0.8 State and FromRef traits instead of runtime Extension extractors. Enforce deterministic Tower middleware ordering via ServiceBuilder with CatchPanicLayer and customized rejection types to eliminate unhandled connection drops.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-state-tower-panic-resilience"
---

# Rust Axum 0.8 Compile-Time State Extraction and Tower Middleware Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Runtime Panics from Untyped Extension Extractors, Unhandled Panics Crashing HTTP Connections, and Broken Middleware Stacks

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower invariants. Enforce compile-time State<S> guarantees with FromRef sub-states, deterministic Tower ServiceBuilder ordering, and zero-panic runtime resilience via CatchPanicLayer and custom rejection handlers.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` and implement `axum::extract::FromRef` for sub-states instead of using `axum::Extension` for core application dependencies.
- Engineers MUST ALWAYS position body-consuming extractors (e.g., `axum::Json`, `axum::extract::RawBody`) as the final parameter in handler signatures to prevent premature stream consumption.
- Code MUST wrap root routers with `tower_http::catch_panic::CatchPanicLayer` configured with a custom panic response generator to prevent abrupt TCP connection resets.
- Services MUST compose middleware via `tower::ServiceBuilder` to enforce top-down, deterministic execution order (Outer layers: tracing -> timeout -> catch_panic -> authentication -> inner handler).
- Components NEVER panic inside Axum extractors or Tower services; all extractor failures MUST map to explicitly typed `IntoResponse` rejection types.

## Bad vs Good Implementations
### Axum 0.8 State Extraction and Panic-Resilient Tower Stack

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension defer resolution to runtime, which causes an unrecoverable 500 or panic if the extension is omitted. Placing Json before other extractors breaks extraction ordering. An unhandled panic drops the raw TCP connection rather than returning a structured 500 response.
```rust
use axum::{routing::post, Extension, Json, Router};
use serde::Deserialize;
use std::sync::Arc;

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

#[derive(Deserialize)]
struct Payload { name: String }

// ANTI-PATTERN: Body-consuming extractor is first; Extension fails at runtime if unregistered.
async fn bad_handler(
    Json(payload): Json<Payload>,
    Extension(state): Extension<AppState>,
) -> String {
    // ANTI-PATTERN: Direct panic will drop connection without HTTP 500 response
    if payload.name.is_empty() {
        panic!("empty name");
    }
    format!("Hello {}, db: {}", payload.name, state.db)
}

pub fn app() -> Router {
    // ANTI-PATTERN: Router lacks CatchPanicLayer and type-safe state registration
    Router::new().route("/user", post(bad_handler))
}
```

#### Production Standard (Correct)
> **Standard**: Extracts state using compile-time checked State with FromRef, guarantees correct body parsing by placing Json last, maps business errors into explicit HTTP response codes, and wraps the router in CatchPanicLayer to safeguard connections.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use serde::Deserialize;
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;

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

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

impl FromRef<AppState> for DbPool {
    fn from_ref(state: &AppState) -> Self {
        DbPool(state.db.clone())
    }
}

#[derive(Deserialize)]
pub struct Payload { pub name: String }

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
}

// PRODUCTION FIX: Compile-time State extractor, body extractor placed last
async fn good_handler(
    State(DbPool(db)): State<DbPool>,
    Json(payload): Json<Payload>,
) -> Result<String, (StatusCode, &'static str)> {
    if payload.name.is_empty() {
        return Err((StatusCode::BAD_REQUEST, "Name cannot be empty"));
    }
    Ok(format!("Hello {}, db: {}", payload.name, db))
}

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

    Router::new()
        .route("/user", post(good_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 Compile-Time State Extraction and Tower Middleware Invariants

Rust Axum 0.8 Compile-Time State Extraction and Tower Middleware Invariants defines an industrial-grade behavioral standard for backend engineering. Mandate compile-time type-safe state injection using Axum 0.8 State and FromRef traits instead of runtime Extension extractors. Enforce deterministic Tower middleware ordering via ServiceBuilder with CatchPanicLayer and customized rejection types to eliminate unhandled 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: Runtime Panics from Untyped Extension Extractors, Unhandled Panics Crashing HTTP Connections, and Broken 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 DriftRuntime Panics from Untyped Extension Extractors, Unhandled Panics Crashing HTTP Connections, and Broken 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` and implement `axum::extract::FromRef` for sub-states instead of using `axum::Extension` for core 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 ALWAYS position body-consuming extractors (e.g., `axum

Engineers MUST ALWAYS position body-consuming extractors (e.g., `axum::Json`, `axum::extract::RawBody`) as the final parameter in handler signatures to prevent premature stream consumption.

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 wrap root routers with `tower_http

Code MUST wrap root routers with `tower_http::catch_panic::CatchPanicLayer` configured with a custom panic response generator to prevent abrupt TCP connection resets.

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 compose middleware via `tower

Services MUST compose middleware via `tower::ServiceBuilder` to enforce top-down, deterministic execution order (Outer layers: tracing -> timeout -> catch_panic -> authentication -> inner handler).

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

Components NEVER panic inside Axum extractors or Tower services

Components NEVER panic inside Axum extractors or Tower services; all extractor failures MUST map to explicitly typed `IntoResponse` rejection types.

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 Compile-Time State Extraction and Tower Middleware Invariants critical for AI coding assistants?

Mandate compile-time type-safe state injection using Axum 0.8 State and FromRef traits instead of runtime Extension extractors. Enforce deterministic Tower middleware ordering via ServiceBuilder with CatchPanicLayer and customized rejection types to eliminate unhandled 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 (Runtime Panics from Untyped Extension Extractors, Unhandled Panics Crashing HTTP Connections, and Broken 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

Rust