This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-subtree-state-tenant-partitioning

Axum 0.8 Subtree State Isolation & Tenant Context Partitioning

Enforces compile-time type-safe separation between root infrastructure state and tenant-isolated routing subtrees in Axum 0.8. Eliminates cross-tenant data contamination and runtime extractor panics by replacing monolithic state bags with strictly bounded Tower service hierarchies and scoped state transformations.

Prohibited Anti-Pattern: Monolithic AppState Anti-Pattern with Dynamic Runtime Tenant Pool Resolution and Extractor Panics

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Subtree State Isolation & Tenant Context Partitioning - Enforces compile-time type-safe separation between root infrastructure state and tenant-isolated routing subtrees in Axum 0.8. Eliminates cross-tenant data contamination and runtime extractor panics by replacing monolithic state bags with strictly bounded Tower service hierarchies and scoped state transformations.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-subtree-state-tenant-partitioning"
---

# Axum 0.8 Subtree State Isolation & Tenant Context Partitioning

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic AppState Anti-Pattern with Dynamic Runtime Tenant Pool Resolution and Extractor Panics

## System Constraints
You are a Principal Systems Architect specializing in type-safe Rust and Axum 0.8 networking architectures. Your objective is to enforce strict subtree state isolation and compile-time multi-tenant context partitioning across nested Tower router topologies. Reject any design relying on dynamically resolved tenant maps inside a monolithic state object or unvalidated request-local extensions.

## Strict Guidelines
- Engineers MUST ALWAYS isolate tenant-scoped state (e.g., tenant connection pools, tenant encryption keys) into a distinct struct separated from `GlobalState` (e.g., metric exporters, global rate limiters, auth verifiers).
- Engineers MUST NOT construct monolithic `AppState` structures holding dynamic `HashMap<TenantId, Pool>` lookups that bypass Axum's compile-time `FromRef` or subtree state typing.
- Router subtrees requiring tenant isolation MUST be constructed via `.with_state(tenant_state)` before merging/nesting into higher-level routers or mapped using type-safe Tower layers that materialize typed sub-states.
- Handlers MUST extract `State(TenantState)` or `State(GlobalState)` with explicit types; untyped or loosely typed `Extension<Arc<T>>` for multi-tenant database contexts is STRICTLY FORBIDDEN.
- Components NEVER bridge cross-tenant contexts without explicit, audit-logged boundary extractors that enforce tenant-level tenant isolation prior to sub-router invocation.

## Bad vs Good Implementations
### Compile-Time Partitioned Subtree State vs. Monolithic Dynamic State Lookup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a monolithic AppState that aggregates tenant connection pools inside a runtime lookup map violates compile-time state isolation. If a handler misidentifies the tenant or fails to check pool existence, it fails at runtime rather than compile time. It also exposes all tenant pools to handlers that only need global metrics or authentication state.
```rust
use axum::{routing::get, extract::State, Router};
use std::collections::HashMap;
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
    // ANTI-PATTERN: Monolithic global state holding dynamic tenant resources.
    // Unchecked runtime lookups can panic, leak across tenants, or fail silently.
    tenant_pools: Arc<HashMap<String, sqlx::PgPool>>,
    metrics_client: Arc<MetricsClient>,
}

async fn get_tenant_orders(
    State(state): State<AppState>,
    // Runtime dependency on header-injected tenant-id without compile-time binding
    tenant_id: axum::extract::Path<String>,
) -> Result<String, ()> {
    let pool = state.tenant_pools.get(&tenant_id.0).ok_or(())?;
    // Unsafe: Connection leakage risk across handlers sharing AppState
    Ok(format!("Orders fetched from pool {:?}", pool))
}

pub fn app() -> Router {
    let state = AppState {
        tenant_pools: Arc::new(HashMap::new()),
        metrics_client: Arc::new(MetricsClient),
    };
    Router::new()
        .route("/:tenant_id/orders", get(get_tenant_orders))
        .with_state(state)
}
```

#### Production Standard (Correct)
> **Standard**: Tenant-scoped state is strictly isolated to its respective subtree using `.with_state(tenant_state)`, transforming the sub-router's required state back to `Router<GlobalState>`. Handlers inside the nested subtree can only extract `TenantState`, guaranteeing at compile time that tenant connection pools cannot be accessed or corrupted by unprivileged or mismatched endpoints.
```rust
use axum::{routing::get, extract::{State, FromRef}, Router};
use std::sync::Arc;

#[derive(Clone)]
pub struct GlobalState {
    pub metrics: Arc<MetricsClient>,
}

#[derive(Clone)]
pub struct TenantState {
    pub tenant_id: String,
    pub pool: sqlx::PgPool,
}

// Subtree handler only has visibility over its dedicated TenantState
async fn get_tenant_orders(State(tenant): State<TenantState>) -> String {
    format!("Orders for tenant {} via isolated pool", tenant.tenant_id)
}

// Global handler only has visibility over GlobalState
async fn health(State(global): State<GlobalState>) -> &'static str {
    "healthy"
}

// Factory for isolated tenant subtrees with compile-time bounded state
pub fn tenant_routes(tenant_state: TenantState) -> Router<GlobalState> {
    Router::new()
        .route("/orders", get(get_tenant_orders))
        .with_state(tenant_state) // Isolates TenantState to this subtree
}

pub fn root_app(global_state: GlobalState, tenant_state: TenantState) -> Router {
    Router::new()
        .route("/health", get(health))
        .nest("/api/tenant", tenant_routes(tenant_state))
        .with_state(global_state)
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Subtree State Isolation & Tenant Context Partitioning

Axum 0.8 Subtree State Isolation & Tenant Context Partitioning defines an industrial-grade behavioral standard for backend engineering. Enforces compile-time type-safe separation between root infrastructure state and tenant-isolated routing subtrees in Axum 0.8. Eliminates cross-tenant data contamination and runtime extractor panics by replacing monolithic state bags with strictly bounded Tower service hierarchies and scoped state transformations. 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: Monolithic AppState Anti-Pattern with Dynamic Runtime Tenant Pool Resolution and Extractor 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 DriftMonolithic AppState Anti-Pattern with Dynamic Runtime Tenant Pool Resolution and Extractor 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 isolate tenant-scoped state (e.g., tenant connection pools, tenant encryption keys) into a distinct struct separated from `GlobalState` (e.g., metric exporters, global rate limiters, auth verifiers).

Engineers MUST ALWAYS isolate tenant-scoped state (e.g., tenant connection pools, tenant encryption keys) into a distinct struct separated from `GlobalState` (e.g., metric exporters, global rate limiters, auth verifiers).

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 construct monolithic `AppState` structures holding dynamic `HashMap<TenantId, Pool>` lookups that bypass Axum's compile-time `FromRef` or subtree state typing.

Engineers MUST NOT construct monolithic `AppState` structures holding dynamic `HashMap<TenantId, Pool>` lookups that bypass Axum's compile-time `FromRef` or subtree state typing.

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

Router subtrees requiring tenant isolation MUST be constructed via `.with_state(tenant_state)` before merging/nesting into higher-level routers or mapped using type-safe Tower layers that materialize typed sub-states.

Router subtrees requiring tenant isolation MUST be constructed via `.with_state(tenant_state)` before merging/nesting into higher-level routers or mapped using type-safe Tower layers that materialize typed sub-states.

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 extract `State(TenantState)` or `State(GlobalState)` with explicit types

Handlers MUST extract `State(TenantState)` or `State(GlobalState)` with explicit types; untyped or loosely typed `Extension<Arc<T>>` for multi-tenant database contexts is STRICTLY FORBIDDEN.

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 bridge cross-tenant contexts without explicit, audit-logged boundary extractors that enforce tenant-level tenant isolation prior to sub-router invocation.

Components NEVER bridge cross-tenant contexts without explicit, audit-logged boundary extractors that enforce tenant-level tenant isolation prior to sub-router invocation.

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 Subtree State Isolation & Tenant Context Partitioning critical for AI coding assistants?

Enforces compile-time type-safe separation between root infrastructure state and tenant-isolated routing subtrees in Axum 0.8. Eliminates cross-tenant data contamination and runtime extractor panics by replacing monolithic state bags with strictly bounded Tower service hierarchies and scoped state transformations. 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 (Monolithic AppState Anti-Pattern with Dynamic Runtime Tenant Pool Resolution and Extractor 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