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

Axum 0.8 & Tower Async Cancellation and RAII Transaction Invariant

Enforces deterministic cancellation safety and structured RAII resource cleanup in Axum 0.8 / Tower async streaming endpoints over HTTP/3. Prevents mid-stream client disconnects from silently terminating in-flight transactional updates or leaking non-rolled-back pool connections.

Prohibited Anti-Pattern: Interleaving Async Yield Points Across Non-Atomic Transaction Steps Causing State Corruption on Client Disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Tower Async Cancellation and RAII Transaction Invariant - Enforces deterministic cancellation safety and structured RAII resource cleanup in Axum 0.8 / Tower async streaming endpoints over HTTP/3. Prevents mid-stream client disconnects from silently terminating in-flight transactional updates or leaking non-rolled-back pool connections.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-async-cancellation-raii-cleanup"
---

# Axum 0.8 & Tower Async Cancellation and RAII Transaction Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Interleaving Async Yield Points Across Non-Atomic Transaction Steps Causing State Corruption on Client Disconnect

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 Tower Async Cancellation and RAII Cleanup Invariants. Mandate that any endpoint handling streaming responses or multi-step operations cleanly rolls back transactional state upon async task cancellation. Strictly forbid interleaving fallible or mutating database operations across client-facing streaming yield points without transactional boundaries and structured rollback guards.

## Strict Guidelines
- Engineers MUST ALWAYS isolate persistent state mutations into atomic, un-cancellable transactions or execute mutations to completion prior to yielding streaming chunks over HTTP/3.
- Engineers MUST NOT interleave direct DB mutation calls across `.await` points inside client-dependent stream generators or `BodyStream` loops where mid-flight cancellation drops the future.
- Code SHOULD leverage RAII guards (such as SQLx `Transaction` drop implementations) or `tokio::spawn` worker queues to decouple mission-critical database state commit logic from the client transport future.
- Services MUST monitor transport disconnection signals and avoid leaving open side-effects in uncommitted distributed caches or stateful Tower middleware layers.
- Components NEVER rely on async destructor patterns or post-loop cleanup code in Axum handlers, because Rust futures dropped at an `.await` point will never execute code past that yield point.

## Bad vs Good Implementations
### Handling Mid-Stream Disconnects with Decoupled Transactions and RAII

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP/3 client cancels the stream or disconnects, Axum drops the underlying handler future. Any code following an active `.await` point in the stream generator is never executed, leaving the job status stuck in an uncompleted state and leaking partial step updates.
```rust
use axum::{extract::State, response::sse::{Event, Sse}};
use futures::stream::{self, Stream};
use sqlx::PgPool;
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt;

pub async fn stream_handler(
    State(pool): State<PgPool>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    // ANTI-PATTERN: If client disconnects at stream.next().await,
    // the future is dropped mid-loop, leaving partial writes or broken audit records.
    let s = async_stream::stream! {
        for step in 1..=10 {
            // Database mutation interleaved with client streaming
            sqlx::query!("UPDATE jobs SET progress = $1 WHERE id = 1", step)
                .execute(&pool)
                .await
                .unwrap();
            
            tokio::time::sleep(Duration::from_millis(500)).await;
            yield Ok(Event::default().data(format!("Step {}", step)));
        }
        // THIS LINE WILL NEVER RUN IF CLIENT DISCONNECTS EARLY
        sqlx::query!("UPDATE jobs SET status = 'COMPLETED' WHERE id = 1")
            .execute(&pool)
            .await
            .unwrap();
    };
    Sse::new(s)
}
```

#### Production Standard (Correct)
> **Standard**: By decoupling the state modification worker from the streaming response using an explicit `tokio::spawn` and `mpsc` channel, client disconnects drop only the receiver stream. The worker detects channel closure deterministically, performs transactional cleanup or rollback, and prevents partial DB state corruption.
```rust
use axum::{extract::State, response::sse::{Event, Sse}};
use futures::stream::Stream;
use sqlx::PgPool;
use std::{convert::Infallible, sync::Arc};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

pub async fn stream_handler(
    State(pool): State<PgPool>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let (tx, rx) = mpsc::channel::<Result<Event, Infallible>>(16);
    let pool = Arc::new(pool);

    // SPAWN decoupled task: Immune to HTTP/3 transport-level drops.
    // Transaction state transitions run to explicit completion or explicit rollback.
    tokio::spawn(async move {
        let mut tx_db = pool.begin().await.expect("Failed to acquire transaction");
        
        for step in 1..=10 {
            if tx.send(Ok(Event::default().data(format!("Step {}", step)))).await.is_err() {
                // Transport dropped by client: explicit RAII / manual rollback triggers here
                tracing::warn!("Client disconnected mid-stream; rolling back transaction");
                let _ = tx_db.rollback().await;
                return;
            }
            
            if let Err(e) = sqlx::query!("UPDATE jobs SET progress = $1 WHERE id = 1", step)
                .execute(&mut *tx_db)
                .await
            {
                tracing::error!("Database error: {:?}", e);
                let _ = tx_db.rollback().await;
                return;
            }
        }

        let _ = sqlx::query!("UPDATE jobs SET status = 'COMPLETED' WHERE id = 1")
            .execute(&mut *tx_db)
            .await;
        let _ = tx_db.commit().await;
    });

    Sse::new(ReceiverStream::new(rx))
}
```

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 and RAII Transaction Invariant

Axum 0.8 & Tower Async Cancellation and RAII Transaction Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation safety and structured RAII resource cleanup in Axum 0.8 / Tower async streaming endpoints over HTTP/3. Prevents mid-stream client disconnects from silently terminating in-flight transactional updates or leaking non-rolled-back pool connections. 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: Interleaving Async Yield Points Across Non-Atomic Transaction Steps Causing State Corruption on Client Disconnect 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 DriftInterleaving Async Yield Points Across Non-Atomic Transaction Steps Causing State Corruption on Client DisconnectCritical
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 persistent state mutations into atomic, un-cancellable transactions or execute mutations to completion prior to yielding streaming chunks over HTTP/3.

Engineers MUST ALWAYS isolate persistent state mutations into atomic, un-cancellable transactions or execute mutations to completion prior to yielding streaming chunks over HTTP/3.

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 interleave direct DB mutation calls across `.await` points inside client-dependent stream generators or `BodyStream` loops where mid-flight cancellation drops the future.

Engineers MUST NOT interleave direct DB mutation calls across `.await` points inside client-dependent stream generators or `BodyStream` loops where mid-flight cancellation drops the future.

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 leverage RAII guards (such as SQLx `Transaction` drop implementations) or `tokio

Code SHOULD leverage RAII guards (such as SQLx `Transaction` drop implementations) or `tokio::spawn` worker queues to decouple mission-critical database state commit logic from the client transport future.

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 monitor transport disconnection signals and avoid leaving open side-effects in uncommitted distributed caches or stateful Tower middleware layers.

Services MUST monitor transport disconnection signals and avoid leaving open side-effects in uncommitted distributed caches or stateful Tower middleware layers.

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 rely on async destructor patterns or post-loop cleanup code in Axum handlers, because Rust futures dropped at an `.await` point will never execute code past that yield point.

Components NEVER rely on async destructor patterns or post-loop cleanup code in Axum handlers, because Rust futures dropped at an `.await` point will never execute code past that yield point.

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 and RAII Transaction Invariant critical for AI coding assistants?

Enforces deterministic cancellation safety and structured RAII resource cleanup in Axum 0.8 / Tower async streaming endpoints over HTTP/3. Prevents mid-stream client disconnects from silently terminating in-flight transactional updates or leaking non-rolled-back pool connections. 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 (Interleaving Async Yield Points Across Non-Atomic Transaction Steps Causing State Corruption on Client Disconnect) 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