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

Axum 0.8 Cancellation-Safe Transaction Lifecycle & Pool Starvation Prevention

Enforces strict cancellation safety invariants for database transactions in Axum 0.8 handlers under Tokio task abortion. Mandates atomic commit boundaries, isolated execution shields for non-idempotent mutations, and prohibits holding open transactions across unshielded external async yield points to eliminate connection pool starvation and orphaned locks.

Prohibited Anti-Pattern: Holding Database Transactions Across Arbitrary Async Yield Points Subject to Abrupt TCP Client Drops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Cancellation-Safe Transaction Lifecycle & Pool Starvation Prevention - Enforces strict cancellation safety invariants for database transactions in Axum 0.8 handlers under Tokio task abortion. Mandates atomic commit boundaries, isolated execution shields for non-idempotent mutations, and prohibits holding open transactions across unshielded external async yield points to eliminate connection pool starvation and orphaned locks.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-cancellation-safe-transactions"
---

# Axum 0.8 Cancellation-Safe Transaction Lifecycle & Pool Starvation Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Holding Database Transactions Across Arbitrary Async Yield Points Subject to Abrupt TCP Client Drops

## System Constraints
You are a Principal Rust Architect enforcing cancellation safety in Axum 0.8 and SQLx/deadpool applications. You must prevent connection pool exhaustion, hanging locks, and inconsistent state caused by Tokio future drops during abrupt HTTP client disconnects.

## Strict Guidelines
- Engineers MUST NEVER hold open database transactions (`sqlx::Transaction`, `deadpool::Transaction`) across arbitrary external async I/O, untrusted timers, or streaming response yield points.
- Engineers MUST encapsulate non-cancellable multi-statement state mutations inside an un-cancellable execution boundary (`tokio::task::spawn` or a dedicated background worker) once state modification has initiated.
- Code SHOULD fetch all required remote HTTP dependencies, perform external validation, and parse payloads BEFORE acquiring a database transaction from the pool.
- Services MUST configure aggressive acquire timeouts and connection max lifetimes on database pools to recover connections dropped mid-handshake during client disconnect storms.
- Components NEVER use `tokio::select!` branches that prematurely drop active transaction futures without explicit commit or async drop completion semantics.

## Bad vs Good Implementations
### Preventing Transaction Leaks Across Cancellation Yield Points

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Acquiring a database transaction before an unshielded external network request (`reqwest::get`) leaves the database row locked if the client abruptly drops the connection. The handler future is cancelled at the `.await` point, causing connection pool starvation and lock contention under client retry storms.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct OrderPayload { pub user_id: i64, pub amount: i64 }

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderPayload>,
) -> Result<impl IntoResponse, StatusCode> {
    // ANTI-PATTERN: Transaction acquired prematurely
    let mut tx = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount, payload.user_id)
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::BAD_REQUEST)?;

    // CANCELLATION VULNERABILITY: If the client disconnects during this external await,
    // the future is dropped immediately. The row lock on `accounts` remains until Tokio/SQLx
    // finishes an async rollback in the background, or pool connections starve during high churn.
    let payment_verified = reqwest::get("https://payment.gateway.internal/verify")
        .await
        .map_err(|_| StatusCode::BAD_GATEWAY)?
        .status()
        .is_success();

    if !payment_verified {
        return Err(StatusCode::PAYMENT_REQUIRED);
    }

    tx.commit().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: All external I/O is resolved prior to opening the database transaction. Critical write operations are encapsulated within an atomic `tokio::spawn` task so that client disconnections cannot abort the future mid-commit, eliminating pool exhaustion and orphaned locks.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct OrderPayload { pub user_id: i64, pub amount: i64 }

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderPayload>,
) -> Result<impl IntoResponse, StatusCode> {
    // 1. Perform external I/O BEFORE acquiring database resources
    let payment_verified = reqwest::get("https://payment.gateway.internal/verify")
        .await
        .map_err(|_| StatusCode::BAD_GATEWAY)?
        .status()
        .is_success();

    if !payment_verified {
        return Err(StatusCode::PAYMENT_REQUIRED);
    }

    // 2. Isolate the atomic database phase to an uninterrupted boundary
    // Spawning ensures that once balance deduction starts, it runs to completion
    // even if the incoming HTTP client drops the connection mid-flight.
    let order_task = tokio::spawn(async move {
        let mut tx = pool.begin().await?;

        sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount, payload.user_id)
            .execute(&mut *tx)
            .await?;

        sqlx::query!("INSERT INTO orders (user_id, amount) VALUES ($1, $2)", payload.user_id, payload.amount)
            .execute(&mut *tx)
            .await?;

        tx.commit().await?;
        Ok::<(), sqlx::Error>(())
    });

    order_task
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
        .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 Cancellation-Safe Transaction Lifecycle & Pool Starvation Prevention

Axum 0.8 Cancellation-Safe Transaction Lifecycle & Pool Starvation Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces strict cancellation safety invariants for database transactions in Axum 0.8 handlers under Tokio task abortion. Mandates atomic commit boundaries, isolated execution shields for non-idempotent mutations, and prohibits holding open transactions across unshielded external async yield points to eliminate connection pool starvation and orphaned locks. 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: Holding Database Transactions Across Arbitrary Async Yield Points Subject to Abrupt TCP Client 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 DriftHolding Database Transactions Across Arbitrary Async Yield Points Subject to Abrupt TCP Client 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 NEVER hold open database transactions (`sqlx

Engineers MUST NEVER hold open database transactions (`sqlx::Transaction`, `deadpool::Transaction`) across arbitrary external async I/O, untrusted timers, or streaming response yield points.

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 encapsulate non-cancellable multi-statement state mutations inside an un-cancellable execution boundary (`tokio

Engineers MUST encapsulate non-cancellable multi-statement state mutations inside an un-cancellable execution boundary (`tokio::task::spawn` or a dedicated background worker) once state modification has initiated.

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 SHOULD fetch all required remote HTTP dependencies, perform external validation, and parse payloads BEFORE acquiring a database transaction from the pool.

Code SHOULD fetch all required remote HTTP dependencies, perform external validation, and parse payloads BEFORE acquiring a database transaction from the 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.
4

Services MUST configure aggressive acquire timeouts and connection max lifetimes on database pools to recover connections dropped mid-handshake during client disconnect storms.

Services MUST configure aggressive acquire timeouts and connection max lifetimes on database pools to recover connections dropped mid-handshake during client disconnect storms.

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 prematurely drop active transaction futures without explicit commit or async drop completion semantics.

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 Cancellation-Safe Transaction Lifecycle & Pool Starvation Prevention critical for AI coding assistants?

Enforces strict cancellation safety invariants for database transactions in Axum 0.8 handlers under Tokio task abortion. Mandates atomic commit boundaries, isolated execution shields for non-idempotent mutations, and prohibits holding open transactions across unshielded external async yield points to eliminate connection pool starvation and orphaned locks. 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 (Holding Database Transactions Across Arbitrary Async Yield Points Subject to Abrupt TCP Client 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