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

Axum 0.8 Safe State Extraction, Strict Middleware Sequencing, and Zero-Panic Invariants

Enforces compile-time type-safe state injection via Axum 0.8 FromRef sub-states, guarantees that consume-body extractors are placed strictly last in handler signatures, and mandates a standardized Tower ServiceBuilder stack equipped with CatchPanicLayer and explicit timeout handling to eliminate uncaught unwinds and dropped HTTP connections.

Prohibited Anti-Pattern: Untyped runtime extensions, misordered consuming extractors, and missing Tower CatchPanicLayer causing silent connection termination.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Safe State Extraction, Strict Middleware Sequencing, and Zero-Panic Invariants - Enforces compile-time type-safe state injection via Axum 0.8 FromRef sub-states, guarantees that consume-body extractors are placed strictly last in handler signatures, and mandates a standardized Tower ServiceBuilder stack equipped with CatchPanicLayer and explicit timeout handling to eliminate uncaught unwinds and dropped HTTP connections.
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-guardrail"
---

# Axum 0.8 Safe State Extraction, Strict Middleware Sequencing, and Zero-Panic Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Untyped runtime extensions, misordered consuming extractors, and missing Tower CatchPanicLayer causing silent connection termination.

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 and Tower production standards. You strictly mandate compile-time checked State<T> with FromRef sub-state extraction over untyped Extension<T>. You enforce extractor ordering where body-consuming extractors (Json, Bytes, String) appear strictly as the terminal parameter. You require all Axum routers to be bounded with Tower's CatchPanicLayer, TimeoutLayer, and TraceLayer through ServiceBuilder to prevent unwound threads and silent socket drops.

## Strict Guidelines
- Engineers MUST ALWAYS use `axum::extract::State` with composite state structs implementing `Clone + Send + Sync + 'static` instead of untyped `axum::Extension`.
- Engineers MUST ALWAYS implement `axum::extract::FromRef<AppState>` for sub-states when composing nested routers to prevent monolithic coupling.
- Engineers MUST ALWAYS position body-consuming extractors (e.g., `axum::Json`, `axum::body::Bytes`, `String`) as the final parameter in handler function signatures.
- Services MUST ALWAYS wrap routers with `tower_http::catch_panic::CatchPanicLayer` to convert runtime panics into RFC 7807 Problem Details or standardized 500 Internal Server Error responses.
- Engineers MUST compose Tower layers via `tower::ServiceBuilder` to ensure deterministic execution order and prevent unintended middleware reversal.
- Components NEVER panic across asynchronous boundaries or rely on default process-level panic hooks to handle web request failures.

## Bad vs Good Implementations
### Axum 0.8 State Extraction and Tower Middleware Stack

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Placing Json before Path fails compilation or runtime body reading because the body stream is consumed before preceding extractors execute. Relying on Extension<T> bypasses compile-time verification, resulting in 500 runtime panics if the layer was omitted. The handler panics directly without CatchPanicLayer, terminating the worker thread unwind without sending a clean HTTP 500 response.
```rust
use axum::{routing::post, Router, Extension, Json, extract::Path};
use std::sync::Arc;

#[derive(Clone)]
struct Database;

// ANTI-PATTERN: Consuming extractor (Json) placed before Path,
// using untyped Extension (runtime crash if omitted),
// and panicking inside handler without CatchPanicLayer.
async fn update_user(
    Json(payload): Json<serde_json::Value>, // Body consumed first
    Path(id): Path<u64>,
    Extension(db): Extension<Arc<Database>>, // Untyped runtime lookup
) -> &'static str {
    if id == 0 {
        panic!("invalid user ID"); // Causes unhandled panic and drops connection
    }
    "updated"
}

pub fn app() -> Router {
    Router::new()
        .route("/users/{id}", post(update_user))
        // Missing CatchPanicLayer, TraceLayer, and type-safe state
}
```

#### Production Standard (Correct)
> **Standard**: Type safety is enforced at compile time using State and FromRef<AppState>. Path and State precede the body-consuming Json extractor. The router integrates CatchPanicLayer and TraceLayer inside a ServiceBuilder, ensuring all unhandled unwinds produce a clean 500 Internal Server Error without dropping client sockets.
```rust
use axum::{
    extract::{FromRef, Path, 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, trace::TraceLayer};

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

#[derive(Clone)]
pub struct Database;

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

#[derive(Deserialize)]
pub struct UpdateUserPayload {
    pub username: String,
}

// INVARIANT: Non-consuming extractors (Path, State) first; terminal consuming extractor (Json) last.
async fn update_user(
    Path(id): Path<u64>,
    State(db): State<Arc<Database>>,
    Json(payload): Json<UpdateUserPayload>,
) -> Result<Response, StatusCode> {
    if id == 0 {
        return Err(StatusCode::BAD_REQUEST);
    }
    let _ = (db, payload);
    Ok((StatusCode::OK, "updated").into_response())
}

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

    Router::new()
        .route("/users/{id}", post(update_user))
        .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: Axum 0.8 Safe State Extraction, Strict Middleware Sequencing, and Zero-Panic Invariants

Axum 0.8 Safe State Extraction, Strict Middleware Sequencing, and Zero-Panic Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe state injection via Axum 0.8 FromRef sub-states, guarantees that consume-body extractors are placed strictly last in handler signatures, and mandates a standardized Tower ServiceBuilder stack equipped with CatchPanicLayer and explicit timeout handling to eliminate uncaught unwinds and dropped HTTP connections. 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 runtime extensions, misordered consuming extractors, and missing Tower CatchPanicLayer causing silent connection termination. 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 runtime extensions, misordered consuming extractors, and missing Tower CatchPanicLayer causing silent connection termination.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 composite state structs implementing `Clone + Send + Sync + 'static` instead of untyped `axum::Extension`.

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 implement `axum

Engineers MUST ALWAYS implement `axum::extract::FromRef<AppState>` for sub-states when composing nested routers to prevent monolithic coupling.

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 position body-consuming extractors (e.g., `axum

Engineers MUST ALWAYS position body-consuming extractors (e.g., `axum::Json`, `axum::body::Bytes`, `String`) as the final parameter in handler function signatures.

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

Services MUST ALWAYS wrap routers with `tower_http::catch_panic::CatchPanicLayer` to convert runtime panics into RFC 7807 Problem Details or standardized 500 Internal Server Error responses.

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

Engineers MUST compose Tower layers via `tower::ServiceBuilder` to ensure deterministic execution order and prevent unintended middleware reversal.

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 across asynchronous boundaries or rely on default process-level panic hooks to handle web request failures.

Components NEVER panic across asynchronous boundaries or rely on default process-level panic hooks to handle web request 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.
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 Safe State Extraction, Strict Middleware Sequencing, and Zero-Panic Invariants critical for AI coding assistants?

Enforces compile-time type-safe state injection via Axum 0.8 FromRef sub-states, guarantees that consume-body extractors are placed strictly last in handler signatures, and mandates a standardized Tower ServiceBuilder stack equipped with CatchPanicLayer and explicit timeout handling to eliminate uncaught unwinds and dropped HTTP connections. 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 runtime extensions, misordered consuming extractors, and missing Tower CatchPanicLayer causing silent connection termination.) 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