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

Axum 0.8 Async Stream Cancellation and Resource Cleanup Guardrail

Enforces atomic state updates and deterministic resource teardown when handling premature HTTP client disconnects during Axum 0.8 response streaming. Prevents orphan Tokio tasks, leaked socket file descriptors, and corrupted partial database writes triggered by mid-stream future drops.

Prohibited Anti-Pattern: Interleaving Non-Idempotent Mutations with Streaming Yields Across Unmonitored Cancellation Points

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Async Stream Cancellation and Resource Cleanup Guardrail - Enforces atomic state updates and deterministic resource teardown when handling premature HTTP client disconnects during Axum 0.8 response streaming. Prevents orphan Tokio tasks, leaked socket file descriptors, and corrupted partial database writes triggered by mid-stream future drops.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-async-stream-cancellation-safety"
---

# Axum 0.8 Async Stream Cancellation and Resource Cleanup Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Interleaving Non-Idempotent Mutations with Streaming Yields Across Unmonitored Cancellation Points

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 async streaming invariants. When clients disconnect prematurely, Axum immediately drops the active response body stream at its current .await point. You must ensure all streaming endpoints decouple critical state updates from the stream lifecycle, manage child resources via RAII Drop guards, and use tokio_util::sync::CancellationToken for spawned worker tasks.

## Strict Guidelines
- Engineers MUST ALWAYS decouple state-mutating transactions from client-driven streaming yields; all database writes must complete prior to streaming or run in an isolated, cancel-safe background task.
- Engineers MUST NOT mutate persistent application state between streaming yield points unless guarded by explicit compensatory rollback logic or idempotent replay tokens.
- Engineers MUST bind stream-associated background tasks and socket descriptors to a tokio_util::sync::CancellationToken derived from the request context or an RAII guard struct.
- Services MUST monitor client disconnects via Body::into_data_stream() or axum::extract::ws / SSE drop semantics and trigger coordinated teardown of upstream buffers and gRPC/TCP handles.
- Components NEVER rely on code executing after a .yield_() or .await statement in an async_stream block, as immediate cancellation on socket drop permanently skips downstream code.

## Bad vs Good Implementations
### Stream Cancellation Handling with CancellationToken and RAII Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts an SSE connection, Axum drops the stream future at the next yield or sleep .await point. The database remains in an incomplete intermediary state, and unmanaged resources like open socket connections are not cleanly shut down.
```rust
use axum::{response::{sse::Event, Sse}, extract::State};
use async_stream::stream;
use std::convert::Infallible;
use std::sync::Arc;

// ANTI-PATTERN: State mutation interleaved with stream yield.
// If the client disconnects at line 16, the order is updated to 'Processing',
// but never completes, and the remote worker socket is leaked without cleanup.
pub async_async fn bad_order_stream(
    State(state): State<Arc<AppState>>,
) -> Sse<impl tokio_stream::Stream<Item = Result<Event, Infallible>>> {
    let s = stream! {
        let socket = state.network_pool.acquire_socket().await;
        for step in 1..=10 {
            // Leaks remote socket handle if client disconnects here
            state.db.execute("UPDATE orders SET step = $1 WHERE id = 42", step).await.unwrap();
            
            // Client disconnect during yield drops the future immediately;
            // downstream cleanup and final 'Completed' update are permanently skipped.
            yield Ok(Event::default().data(format!("Step {step}")));
            tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
        }
        state.db.execute("UPDATE orders SET status = 'Completed' WHERE id = 42").await.unwrap();
    };
    Sse::new(s)
}
```

#### Production Standard (Correct)
> **Standard**: By utilizing RAII drop guards and tokio_util::sync::CancellationToken, socket resources are deterministically released and the persistent order update logic is decoupled into a safe background transaction that catches early disconnects.
```rust
use axum::{response::{sse::Event, Sse}, extract::State};
use async_stream::stream;
use tokio_util::sync::CancellationToken;
use std::convert::Infallible;
use std::sync::Arc;

struct SocketGuard {
    socket_id: u64,
    pool: Arc<NetworkPool>,
}

impl Drop for SocketGuard {
    fn drop(&mut self) {
        // Deterministic cleanup guaranteed even on premature stream abort
        self.pool.release_socket(self.socket_id);
    }
}

pub async fn good_order_stream(
    State(state): State<Arc<AppState>>,
) -> Sse<impl tokio_stream::Stream<Item = Result<Event, Infallible>>> {
    let token = CancellationToken::new();
    let child_token = token.child_token();
    let db = state.db.clone();

    // 1. Critical mutations run in an independent cancellation-safe task
    tokio::spawn(async move {
        tokio::select! {
            _ = child_token.cancelled() => {
                let _ = db.execute("UPDATE orders SET status = 'Cancelled' WHERE id = 42").await;
            }
            res = run_isolated_order_pipeline(&db, 42) => {
                let _ = res;
            }
        }
    });

    let s = stream! {
        // 2. Wrap non-Tokio socket in RAII guard for immediate release on future drop
        let raw_socket = state.network_pool.acquire_socket().await;
        let _guard = SocketGuard { socket_id: raw_socket.id, pool: state.network_pool.clone() };
        
        // 3. Inform background worker if client drops prematurely
        let _drop_token = token.drop_guard();

        for step in 1..=10 {
            yield Ok(Event::default().data(format!("Step {step}")));
            tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
        }
    };

    Sse::new(s)
}
```

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 Async Stream Cancellation and Resource Cleanup Guardrail

Axum 0.8 Async Stream Cancellation and Resource Cleanup Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces atomic state updates and deterministic resource teardown when handling premature HTTP client disconnects during Axum 0.8 response streaming. Prevents orphan Tokio tasks, leaked socket file descriptors, and corrupted partial database writes triggered by mid-stream future drops. 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 Non-Idempotent Mutations with Streaming Yields Across Unmonitored Cancellation Points 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 Non-Idempotent Mutations with Streaming Yields Across Unmonitored Cancellation PointsCritical
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 decouple state-mutating transactions from client-driven streaming yields

Engineers MUST ALWAYS decouple state-mutating transactions from client-driven streaming yields; all database writes must complete prior to streaming or run in an isolated, cancel-safe background task.

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 mutate persistent application state between streaming yield points unless guarded by explicit compensatory rollback logic or idempotent replay tokens.

Engineers MUST NOT mutate persistent application state between streaming yield points unless guarded by explicit compensatory rollback logic or idempotent replay tokens.

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

Engineers MUST bind stream-associated background tasks and socket descriptors to a tokio_util

Engineers MUST bind stream-associated background tasks and socket descriptors to a tokio_util::sync::CancellationToken derived from the request context or an RAII guard struct.

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 client disconnects via Body

Services MUST monitor client disconnects via Body::into_data_stream() or axum::extract::ws / SSE drop semantics and trigger coordinated teardown of upstream buffers and gRPC/TCP 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.
5

Components NEVER rely on code executing after a .yield_() or .await statement in an async_stream block, as immediate cancellation on socket drop permanently skips downstream code.

Components NEVER rely on code executing after a .yield_() or .await statement in an async_stream block, as immediate cancellation on socket drop permanently skips downstream code.

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 Async Stream Cancellation and Resource Cleanup Guardrail critical for AI coding assistants?

Enforces atomic state updates and deterministic resource teardown when handling premature HTTP client disconnects during Axum 0.8 response streaming. Prevents orphan Tokio tasks, leaked socket file descriptors, and corrupted partial database writes triggered by mid-stream future drops. 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 Non-Idempotent Mutations with Streaming Yields Across Unmonitored Cancellation Points) 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