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

Rust Axum 0.8 Type-Safe State Extraction & Tower Resiliency Pipeline

Enforces compile-time type-safe state extraction via Axum 0.8 FromRef traits, strict sequential extractor ordering with terminal body consumption, and deterministic Tower middleware ordering with explicit panic recovery boundaries to eliminate dropped socket connections.

Prohibited Anti-Pattern: Dynamic Extension injection, premature body extraction, and naked Tower pipelines causing runtime panics and connection drops.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Rust Axum 0.8 Type-Safe State Extraction & Tower Resiliency Pipeline - Enforces compile-time type-safe state extraction via Axum 0.8 FromRef traits, strict sequential extractor ordering with terminal body consumption, and deterministic Tower middleware ordering with explicit panic recovery boundaries to eliminate dropped socket connections.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-state-extractor-tower-pipeline-standard"
---

# Rust Axum 0.8 Type-Safe State Extraction & Tower Resiliency Pipeline

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dynamic Extension injection, premature body extraction, and naked Tower pipelines causing runtime panics and connection drops.

## System Constraints
You are a Principal Rust Systems Architect specializing in Axum 0.8 and the Tower ecosystem. Your mandate is to enforce strict compile-time state safety via FromRef, prevent HTTP extractor sequencing bugs, and guarantee 100% resilient Tower middleware stacks where zero panics escape as dropped TCP connections.

## Strict Guidelines
- Engineers MUST ALWAYS implement `axum::extract::FromRef<AppState>` for granular sub-states to decouple route handlers from monolithic application state.
- Engineers MUST NOT use `axum::extract::Extension` for domain state or database pools; state MUST be passed through type-safe `axum::extract::State`.
- Code MUST ALWAYS place stream-consuming extractors (e.g., `axum::Json<T>`, `axum::body::Bytes`, `axum::extract::Form<T>`) as the final parameter in handler function signatures.
- Services MUST ALWAYS wrap top-level router pipelines with `tower_http::catch_panic::CatchPanicLayer` returning an explicit RFC 7807 Problem Details or structured JSON payload to prevent TCP socket drops.
- Components NEVER store expensive un-clonable types directly in `State`; state wrappers MUST be $O(1)$ cheap to clone, backed by `std::sync::Arc` or native handle pools (e.g., `sqlx::Pool`).

## Bad vs Good Implementations
### State Extraction and Tower Pipeline Resiliency

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension defers type checks to runtime, failing with unhandled 500 errors if the extension is omitted. Consuming the body before other extractors violates Axum's left-to-right extraction contract. Unhandled panics crash the Tower service worker thread, dropping TCP sockets abruptly.
```rust
use axum::{extract::Extension, response::IntoResponse, routing::post, Json, Router};
use serde::Deserialize;

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

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

// ANTI-PATTERN: Body extractor placed before Extension;
// Extension is checked at runtime (causing panics if missing);
// Uncaught panics terminate connection ungracefully.
async fn create_user(
    Json(payload): Json<CreateUser>,
    Extension(state): Extension<AppState>,
) -> impl IntoResponse {
    if payload.name.is_empty() {
        panic!("Critical failure: empty name"); // Causes raw TCP connection reset
    }
    format!("Created user {} in {}", payload.name, state.db)
}

pub fn app() -> Router {
    Router::new()
        .route("/users", post(create_user))
        // No CatchPanicLayer or type-safe State provided
}
```

#### Production Standard (Correct)
> **Standard**: Uses compile-time checked `State` with `FromRef` for modular sub-state slices. Orders the non-consuming `State` extractor before the terminal `Json` extractor. Integrates `tower_http::CatchPanicLayer` to guarantee that unexpected panics result in safe, structured HTTP 500 JSON responses rather than dropped connections.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post, Json, Router
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;

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

// Decoupled sub-state extractor via FromRef
impl FromRef<AppState> for Arc<String> {
    fn from_ref(state: &AppState) -> Self {
        Arc::clone(&state.db_pool)
    }
}

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

#[derive(Serialize)]
struct ErrorResponse { error: String }

// INVARIANT: Infallible / header / sub-state extractors come FIRST;
// Terminal payload-consuming extractors come LAST.
async fn create_user(
    State(db): State<Arc<String>>,
    Json(payload): Json<CreateUser>,
) -> Result<String, (StatusCode, Json<ErrorResponse>)> {
    if payload.name.is_empty() {
        return Err((
            StatusCode::BAD_REQUEST,
            Json(ErrorResponse { error: "Name cannot be empty".into() }),
        ));
    }
    Ok(format!("Created user {} in db {}", payload.name, db))
}

fn handle_panic(_err: Box<dyn std::any::Any + Send + 'static>) -> Response {
    let payload = serde_json::json!({ "error": "Internal server error occurred" });
    (StatusCode::INTERNAL_SERVER_ERROR, Json(payload)).into_response()
}

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/users", post(create_user))
        .layer(
            ServiceBuilder::new()
                .layer(CatchPanicLayer::custom(handle_panic))
        )
        .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 Extraction & Tower Resiliency Pipeline

Rust Axum 0.8 Type-Safe State Extraction & Tower Resiliency Pipeline defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe state extraction via Axum 0.8 FromRef traits, strict sequential extractor ordering with terminal body consumption, and deterministic Tower middleware ordering with explicit panic recovery boundaries to eliminate dropped socket 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: Dynamic Extension injection, premature body extraction, and naked Tower pipelines causing runtime panics and connection drops. 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 DriftDynamic Extension injection, premature body extraction, and naked Tower pipelines causing runtime panics and connection drops.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 implement `axum

Engineers MUST ALWAYS implement `axum::extract::FromRef<AppState>` for granular sub-states to decouple route handlers from monolithic 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 NOT use `axum

Engineers MUST NOT use `axum::extract::Extension` for domain state or database pools; state MUST be passed through type-safe `axum::extract::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

Code MUST ALWAYS place stream-consuming extractors (e.g., `axum

Code MUST ALWAYS place stream-consuming extractors (e.g., `axum::Json<T>`, `axum::body::Bytes`, `axum::extract::Form<T>`) 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 top-level router pipelines with `tower_http

Services MUST ALWAYS wrap top-level router pipelines with `tower_http::catch_panic::CatchPanicLayer` returning an explicit RFC 7807 Problem Details or structured JSON payload to prevent TCP socket drops.

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 store expensive un-clonable types directly in `State`

Components NEVER store expensive un-clonable types directly in `State`; state wrappers MUST be $O(1)$ cheap to clone, backed by `std::sync::Arc` or native handle pools (e.g., `sqlx::Pool`).

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 Extraction & Tower Resiliency Pipeline critical for AI coding assistants?

Enforces compile-time type-safe state extraction via Axum 0.8 FromRef traits, strict sequential extractor ordering with terminal body consumption, and deterministic Tower middleware ordering with explicit panic recovery boundaries to eliminate dropped socket 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 (Dynamic Extension injection, premature body extraction, and naked Tower pipelines causing runtime panics and connection drops.) 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