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

Axum 0.8 & Tower Async Cancellation & Drop Cleanup Invariant

Enforces cancellation-safe handlers and deterministic drop mechanics across Axum 0.8 and Tower service pipelines. Ensures aborted client TCP connections and early drops immediately propagate down the future tree to abort downstream SQL/database operations, preventing connection pool exhaustion and phantom writes.

Prohibited Anti-Pattern: Detaching or shielding uncancelable database futures from client drop notifications, causing ghost queries and connection pool starvation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Tower Async Cancellation & Drop Cleanup Invariant - Enforces cancellation-safe handlers and deterministic drop mechanics across Axum 0.8 and Tower service pipelines. Ensures aborted client TCP connections and early drops immediately propagate down the future tree to abort downstream SQL/database operations, preventing connection pool exhaustion and phantom writes.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-async-cancellation-drop-cleanup-invariant"
---

# Axum 0.8 & Tower Async Cancellation & Drop Cleanup Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detaching or shielding uncancelable database futures from client drop notifications, causing ghost queries and connection pool starvation.

## System Constraints
You are a Principal Rust Systems Architect enforcing strict async cancellation safety and drop invariants in Axum 0.8 and Tower applications. You must mandate that when a client drops an HTTP connection, Axum's enclosing future terminates immediately and tears down in-flight I/O, database transactions, and pool allocations without spawning unmanaged background tasks or using cancel-hostile synchronization primitives.

## Strict Guidelines
- Engineers MUST ALWAYS structure Axum 0.8 handlers such that all child futures are awaited inline within the request future tree, allowing Rust's standard drop semantics to propagate cancellation downward.
- Engineers MUST NOT spawn detached tasks (`tokio::spawn`) for operations that depend on or serve an ephemeral client request without explicit structured concurrency (`tokio_util::sync::CancellationToken` or `tokio::task::JoinSet`).
- Code MUST ensure that non-idempotent operations (such as mutations or billing actions) that cannot be safely interrupted mid-execution run inside atomic database transactions (`sqlx::Transaction`) whose drop implementation rolls back uncommitted state, or explicitly uses `tokio_util::sync::CancellationToken` paired with graceful finalizers.
- Services MUST ensure that database connections checked out from pools (e.g., SQLx or Deadpool) are dropped immediately upon cancellation rather than held in a blocked thread or lingering asynchronous loop.
- Components NEVER use `tokio::select!` branches that hold uncancelable references or mutate non-rollbackable in-memory state across branch aborts without implementing custom `Drop` cleanup.

## Bad vs Good Implementations
### Handling Client Disconnects: Detached Spawn vs. Cancellation-Safe Transaction Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning an unmonitored task drops the relationship between the client socket and the database future. When clients disconnect prematurely (e.g., mobile drops or browser refreshes), queries continue executing to completion, consuming database threads and pool leases.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use sqlx::PgPool;

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

// ANTI-PATTERN: Spawning a detached task divorces execution from the HTTP request.
// If the client disconnects, this query continues running, starving pool connections
// and generating phantom records with no listener to receive the response.
pub async fn create_record_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<CreateRecord>,
) -> impl IntoResponse {
    tokio::spawn(async move {
        let mut conn = pool.acquire().await.unwrap();
        sqlx::query!(
            "INSERT INTO records (name) VALUES ($1)",
            payload.name
        )
        .execute(&mut *conn)
        .await
        .unwrap();
    });

    StatusCode::ACCEPTED
}
```

#### Production Standard (Correct)
> **Standard**: Awaiting inline guarantees that if the client connection closes, the future is dropped. The `sqlx::Transaction` RAII drop implementation will issue an asynchronous rollback on drop or close the underlying connection immediately, preventing uncommitted phantom rows and returning pool resources.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use sqlx::PgPool;

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

// PRODUCTION INVARIANT: Await the query inline within an explicit transaction.
// When the client terminates the connection, Axum drops this handler future;
// the sqlx::Transaction drop handler fires, safely issuing ROLLBACK and releasing
// the connection back to the pool immediately.
pub async fn create_record_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<CreateRecord>,
) -> Result<impl IntoResponse, StatusCode> {
    let mut tx = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    sqlx::query!(
        "INSERT INTO records (name) VALUES ($1)",
        payload.name
    )
    .execute(&mut *tx)
    .await
    .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    tx.commit().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok((StatusCode::CREATED, "Created"))
}
```

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 Async Cancellation & Drop Cleanup Invariant

Axum 0.8 & Tower Async Cancellation & Drop Cleanup Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces cancellation-safe handlers and deterministic drop mechanics across Axum 0.8 and Tower service pipelines. Ensures aborted client TCP connections and early drops immediately propagate down the future tree to abort downstream SQL/database operations, preventing connection pool exhaustion and phantom writes. 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: Detaching or shielding uncancelable database futures from client drop notifications, causing ghost queries and connection pool starvation. 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 DriftDetaching or shielding uncancelable database futures from client drop notifications, causing ghost queries and connection pool starvation.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 structure Axum 0.8 handlers such that all child futures are awaited inline within the request future tree, allowing Rust's standard drop semantics to propagate cancellation downward.

Engineers MUST ALWAYS structure Axum 0.8 handlers such that all child futures are awaited inline within the request future tree, allowing Rust's standard drop semantics to propagate cancellation downward.

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 spawn detached tasks (`tokio

Engineers MUST NOT spawn detached tasks (`tokio::spawn`) for operations that depend on or serve an ephemeral client request without explicit structured concurrency (`tokio_util::sync::CancellationToken` or `tokio::task::JoinSet`).

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 ensure that non-idempotent operations (such as mutations or billing actions) that cannot be safely interrupted mid-execution run inside atomic database transactions (`sqlx

Code MUST ensure that non-idempotent operations (such as mutations or billing actions) that cannot be safely interrupted mid-execution run inside atomic database transactions (`sqlx::Transaction`) whose drop implementation rolls back uncommitted state, or explicitly uses `tokio_util::sync::CancellationToken` paired with graceful finalizers.

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 ensure that database connections checked out from pools (e.g., SQLx or Deadpool) are dropped immediately upon cancellation rather than held in a blocked thread or lingering asynchronous loop.

Services MUST ensure that database connections checked out from pools (e.g., SQLx or Deadpool) are dropped immediately upon cancellation rather than held in a blocked thread or lingering asynchronous loop.

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

Components NEVER use `tokio::select!` branches that hold uncancelable references or mutate non-rollbackable in-memory state across branch aborts without implementing custom `Drop` cleanup.

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 Async Cancellation & Drop Cleanup Invariant critical for AI coding assistants?

Enforces cancellation-safe handlers and deterministic drop mechanics across Axum 0.8 and Tower service pipelines. Ensures aborted client TCP connections and early drops immediately propagate down the future tree to abort downstream SQL/database operations, preventing connection pool exhaustion and phantom writes. 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 (Detaching or shielding uncancelable database futures from client drop notifications, causing ghost queries and connection pool starvation.) 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