This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-tower-cancellation-propagation-backpressure

Axum 0.8 Tower Client Cancellation Propagation and Database Backpressure

Couples HTTP/2 RST_STREAM and HTTP/3 client socket disconnections directly to Tokio task abort handles and database transactions within Tower services. Prevents orphaned upstream database queries and connection pool exhaustion when clients abort in-flight requests under load.

Prohibited Anti-Pattern: Spawning Detached Tokio Tasks in Handlers Causing Database Pool Starvation on Client Socket Drops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Client Cancellation Propagation and Database Backpressure - Couples HTTP/2 RST_STREAM and HTTP/3 client socket disconnections directly to Tokio task abort handles and database transactions within Tower services. Prevents orphaned upstream database queries and connection pool exhaustion when clients abort in-flight requests under load.
globs: src/**/*.rs, **/routes/**/*.rs, **/handlers/**/*.rs, **/middleware/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-cancellation-propagation-backpressure"
---

# Axum 0.8 Tower Client Cancellation Propagation and Database Backpressure

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Detached Tokio Tasks in Handlers Causing Database Pool Starvation on Client Socket Drops

## System Constraints
You are a Principal Rust Systems Architect specializing in Axum 0.8, Tower, and Tokio async runtimes. Mandate that all incoming HTTP/2 RST_STREAM and HTTP/3 disconnections deterministically cancel in-flight upstream database futures and release connection pools immediately. Enforce strict backpressure invariants at the Tower layer.

## Strict Guidelines
- Engineers MUST ALWAYS keep transactional database operations bounded to the Axum handler's root Future lifecycle or guarded by an explicit DropGuard/CancellationToken.
- Engineers MUST NOT use unconstrained `tokio::spawn` within Axum handlers for workloads holding upstream database connections or scarce system handles.
- Services MUST leverage `tokio::select!` or `axum::serve`'s inherent Future cancellation mechanism so that dropping the socket future automatically drops in-progress SQLx or Tower futures.
- Tower middleware MUST implement explicit backpressure via `Service::poll_ready` and avoid buffering unbounded requests when downstream services are saturated.
- Background worker tasks spawned intentionally outside the request lifecycle MUST NOT reuse the HTTP connection's context and MUST manage their own isolated timeout, concurrency permit, and connection lifecycle.

## Bad vs Good Implementations
### Client Cancellation and Upstream Connection Release

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `tokio::spawn` severs the future from Axum's connection monitor. If the client closes the socket (or sends an HTTP/2 RST_STREAM frame), the detached task continues holding a Postgres connection for 30 seconds, leading to connection pool exhaustion under modest load.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;

pub async fn handle_large_query(
    State(pool): State<PgPool>,
    Json(payload): Json<SearchQuery>,
) -> impl IntoResponse {
    // ANTI-PATTERN: Spawning a detached Tokio task breaks cancellation propagation.
    // When the HTTP/2 client disconnects (RST_STREAM) or times out, this task continues
    // executing against the database, leaking a scarce connection from the pool.
    tokio::spawn(async move {
        let mut conn = pool.acquire().await.unwrap();
        sqlx::query("SELECT pg_sleep(30)")
            .execute(&mut *conn)
            .await
            .unwrap();
    });

    StatusCode::ACCEPTED
}
```

#### Production Standard (Correct)
> **Standard**: Keeping the database future directly inside the handler's execution path leverages Rust's drop semantics. When the HTTP/2 or HTTP/3 client socket drops, Axum drops the handler future, which immediately drops the active SQLx connection future, preventing orphaned queries from exhausting database resources.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use tokio_util::sync::CancellationToken;

pub async fn handle_large_query(
    State(pool): State<PgPool>,
    Json(payload): Json<SearchQuery>,
) -> Result<impl IntoResponse, StatusCode> {
    // INVARIANT: Executing the query in the handler's future tree guarantees that
    // when Axum drops the handler future on client disconnection, SQLx's query future
    // is dropped immediately. Dropping the future aborts the wire query, sends a cancel/closes
    // the stream, and returns the pooled connection to PgPool.
    let mut conn = pool
        .acquire()
        .await
        .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;

    sqlx::query("SELECT pg_sleep(30)")
        .execute(&mut *conn)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(StatusCode::OK)
}
```

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 Tower Client Cancellation Propagation and Database Backpressure

Axum 0.8 Tower Client Cancellation Propagation and Database Backpressure defines an industrial-grade behavioral standard for backend engineering. Couples HTTP/2 RST_STREAM and HTTP/3 client socket disconnections directly to Tokio task abort handles and database transactions within Tower services. Prevents orphaned upstream database queries and connection pool exhaustion when clients abort in-flight requests under load. 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: Spawning Detached Tokio Tasks in Handlers Causing Database Pool Starvation on Client Socket 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 DriftSpawning Detached Tokio Tasks in Handlers Causing Database Pool Starvation on Client Socket DropsCritical
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 keep transactional database operations bounded to the Axum handler's root Future lifecycle or guarded by an explicit DropGuard/CancellationToken.

Engineers MUST ALWAYS keep transactional database operations bounded to the Axum handler's root Future lifecycle or guarded by an explicit DropGuard/CancellationToken.

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 unconstrained `tokio

Engineers MUST NOT use unconstrained `tokio::spawn` within Axum handlers for workloads holding upstream database connections or scarce system handles.

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

Services MUST leverage `tokio

Services MUST leverage `tokio::select!` or `axum::serve`'s inherent Future cancellation mechanism so that dropping the socket future automatically drops in-progress SQLx or Tower futures.

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

Tower middleware MUST implement explicit backpressure via `Service

Tower middleware MUST implement explicit backpressure via `Service::poll_ready` and avoid buffering unbounded requests when downstream services are saturated.

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

Background worker tasks spawned intentionally outside the request lifecycle MUST NOT reuse the HTTP connection's context and MUST manage their own isolated timeout, concurrency permit, and connection lifecycle.

Background worker tasks spawned intentionally outside the request lifecycle MUST NOT reuse the HTTP connection's context and MUST manage their own isolated timeout, concurrency permit, and connection lifecycle.

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 Tower Client Cancellation Propagation and Database Backpressure critical for AI coding assistants?

Couples HTTP/2 RST_STREAM and HTTP/3 client socket disconnections directly to Tokio task abort handles and database transactions within Tower services. Prevents orphaned upstream database queries and connection pool exhaustion when clients abort in-flight requests under load. 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 (Spawning Detached Tokio Tasks in Handlers Causing Database Pool Starvation on Client Socket 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

Axum