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

Axum 0.8 Type-Safe State Sub-typing and Tower Panic Boundary Invariants

Enforce compile-time type-safe state injection via Axum's FromRef pattern across nested routers and guarantee zero unhandled runtime panics using Tower CatchPanicLayer middleware. Handlers must consume state via cloned aggregates or derived sub-states, and must never rely on process-terminating unwraps or loose dynamic state containers.

Prohibited Anti-Pattern: Nested Routers Missing FromRef Implementations and Naked Tower Middleware Stacks Leaking Panics

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Type-Safe State Sub-typing and Tower Panic Boundary Invariants - Enforce compile-time type-safe state injection via Axum's FromRef pattern across nested routers and guarantee zero unhandled runtime panics using Tower CatchPanicLayer middleware. Handlers must consume state via cloned aggregates or derived sub-states, and must never rely on process-terminating unwraps or loose dynamic state containers.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-state-and-tower-composition"
---

# Axum 0.8 Type-Safe State Sub-typing and Tower Panic Boundary Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Nested Routers Missing FromRef Implementations and Naked Tower Middleware Stacks Leaking Panics

## System Constraints
You are a Principal Rust Architect enforcing idiomatic, fail-safe Axum 0.8 and Tower service architecture. Reject loose dynamic states (such as Extensions for core dependencies), missing FromRef sub-state derivations, unhandled panics in Tower middleware stacks, and naked unwrap() calls in HTTP handler pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS implement or derive `axum::extract::FromRef` when sharing sub-components of `AppState` with modular sub-routers.
- Engineers MUST ALWAYS wrap top-level Tower services with `tower_http::catch_panic::CatchPanicLayer` to translate unwinding panics into structured HTTP 500 Internal Server Error responses.
- Engineers MUST NOT rely on `axum::extract::Extension` for static application dependencies; state MUST be passed exclusively via `axum::extract::State`.
- Handlers MUST NEVER call `.unwrap()` or `.expect()` on `Result` types; errors MUST be explicitly converted into custom types implementing `axum::response::IntoResponse`.
- Services MUST place observability and resilience middleware (e.g., `TraceLayer`, `CatchPanicLayer`, `TimeoutLayer`) in deterministic order: CatchPanic outermost to intercept panics from inner middleware and handlers.

## Bad vs Good Implementations
### Modular State Sharing and Tower Panic Boundary Composition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Extension bypasses compile-time state verification, failing at runtime if missing. Calling unwrap inside handlers risks uncaught panics, and the router lacks a CatchPanicLayer, which can abort the connection abruptly.
```rust
use axum::{extract::Extension, routing::get, Router};
use std::sync::Arc;

struct Database;
struct Cache;

// ANTI-PATTERN: Loose extension-based dependency injection with unhandled panics
async fn get_user(Extension(db): Extension<Arc<Database>>) -> &'static str {
    // Naked unwrap can panic and terminate the connection without a 500 response
    let _result = Some("data").unwrap();
    "user data"
}

pub fn app() -> Router {
    Router::new()
        .route("/users", get(get_user))
        .layer(Extension(Arc::new(Database)))
        .layer(Extension(Arc::new(Cache)))
}
```

#### Production Standard (Correct)
> **Standard**: State extraction is verified at compile-time using FromRef. Dependencies are encapsulated in AppState, and the router is wrapped with Tower's CatchPanicLayer to guarantee all panics are caught and returned as clean HTTP 500 responses.
```rust
use axum::{
    extract::{FromRef, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;

#[derive(Clone)]
pub struct Database;

#[derive(Clone)]
pub struct Cache;

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

// Type-safe sub-state extraction via FromRef
impl FromRef<AppState> for Arc<Database> {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

enum AppError {
    Internal,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
    }
}

async fn get_user(
    State(db): State<Arc<Database>>,
) -> Result<&'static str, AppError> {
    let _ = db;
    Ok("user data")
}

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/users", get(get_user))
        .layer(
            ServiceBuilder::new()
                .layer(CatchPanicLayer::new())
        )
        .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 Sub-typing and Tower Panic Boundary Invariants

Axum 0.8 Type-Safe State Sub-typing and Tower Panic Boundary Invariants defines an industrial-grade behavioral standard for backend engineering. Enforce compile-time type-safe state injection via Axum's FromRef pattern across nested routers and guarantee zero unhandled runtime panics using Tower CatchPanicLayer middleware. Handlers must consume state via cloned aggregates or derived sub-states, and must never rely on process-terminating unwraps or loose dynamic state containers. 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: Nested Routers Missing FromRef Implementations and Naked Tower Middleware Stacks Leaking 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 DriftNested Routers Missing FromRef Implementations and Naked Tower Middleware Stacks Leaking PanicsCritical
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 or derive `axum

Engineers MUST ALWAYS implement or derive `axum::extract::FromRef` when sharing sub-components of `AppState` with modular sub-routers.

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 wrap top-level Tower services with `tower_http

Engineers MUST ALWAYS wrap top-level Tower services with `tower_http::catch_panic::CatchPanicLayer` to translate unwinding panics into structured HTTP 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.
3

Engineers MUST NOT rely on `axum

Engineers MUST NOT rely on `axum::extract::Extension` for static application dependencies; state MUST be passed exclusively via `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.
4

Handlers MUST NEVER call `.unwrap()` or `.expect()` on `Result` types

Handlers MUST NEVER call `.unwrap()` or `.expect()` on `Result` types; errors MUST be explicitly converted into custom types implementing `axum::response::IntoResponse`.

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

Services MUST place observability and resilience middleware (e.g., `TraceLayer`, `CatchPanicLayer`, `TimeoutLayer`) in deterministic order

Services MUST place observability and resilience middleware (e.g., `TraceLayer`, `CatchPanicLayer`, `TimeoutLayer`) in deterministic order: CatchPanic outermost to intercept panics from inner middleware and handlers.

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 Sub-typing and Tower Panic Boundary Invariants critical for AI coding assistants?

Enforce compile-time type-safe state injection via Axum's FromRef pattern across nested routers and guarantee zero unhandled runtime panics using Tower CatchPanicLayer middleware. Handlers must consume state via cloned aggregates or derived sub-states, and must never rely on process-terminating unwraps or loose dynamic state containers. 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 (Nested Routers Missing FromRef Implementations and Naked Tower Middleware Stacks Leaking 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

Axum