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

Axum 0.8 Tower Service Async Cancellation Safety and Stream Isolation

Enforces strict cancellation safety and state isolation in Axum 0.8 and Tower services when handling streaming HTTP bodies and chunked client responses. Prevents state corruption, partial distributed commits, and resource leaks caused by Tokio futures being abruptly dropped upon downstream client disconnections.

Prohibited Anti-Pattern: Executing non-atomic multi-step side effects across await points inside cancellable HTTP body streams

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Service Async Cancellation Safety and Stream Isolation - Enforces strict cancellation safety and state isolation in Axum 0.8 and Tower services when handling streaming HTTP bodies and chunked client responses. Prevents state corruption, partial distributed commits, and resource leaks caused by Tokio futures being abruptly dropped upon downstream client disconnections.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-async-cancellation-stream-isolation"
---

# Axum 0.8 Tower Service Async Cancellation Safety and Stream Isolation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing non-atomic multi-step side effects across await points inside cancellable HTTP body streams

## System Constraints
You are a Principal Systems Architect enforcing Async Cancellation Safety and Stream Isolation across Axum 0.8 and Tower services. In Rust asynchronous runtimes, an abrupt downstream client socket termination causes hyper/axum to drop the active handler or body stream future at its current .await point. You must ensure that non-idempotent operations, state transitions, distributed transactions, and financial or quota side effects are never interleaved directly into client-driven stream futures. Mandate the decoupling of critical background side effects using detached tasks, transactional rollback guards, cancellation tokens, and isolated channel pipelines.

## Strict Guidelines
- Engineers MUST NEVER execute non-atomic state mutations or distributed side-effects across `.await` points inside client-polled HTTP streaming bodies.
- Engineers MUST isolate client-facing stream consumption from background processing via detached tasks (`tokio::spawn`) and bounded memory channels (`tokio::sync::mpsc`).
- Services MUST implement explicit drop-safe guards or two-phase transaction handles using RAII types (such as `scopeguard` or explicit custom `Drop` impls) for partial state rollback when unwinding asynchronous scopes.
- Handlers MUST utilize `tokio_util::sync::CancellationToken` to propagate cooperative graceful cancellation rather than relying on uncoordinated future drops.
- Streaming responses that deduct credits, update cursor offsets, or record audit events MUST commit state updates independently of whether the client consumed the stream to completion.
- Components NEVER assume `tower::Service::call` or Axum handler futures run to completion; all critical invariants must survive immediate, arbitrary future drops.

## Bad vs Good Implementations
### Decoupling Stream Generation from Critical Side Effects

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Axum, when the downstream client closes the connection, the Body stream is dropped immediately at whatever `.await` point it was executing. Any side effect interleaved inside the stream future will be half-committed or prematurely aborted, leading to severe ledger and state corruption.
```rust
use axum::{body::Body, response::Response};
use futures_util::stream::{self, StreamExt};

pub async fn stream_export_handler() -> Response {
    // ANTI-PATTERN: If the downstream client disconnects after chunk 3,
    // this entire future is dropped mid-stream. The final audit log and
    // billing deduction are skipped, leaving the ledger in an inconsistent state.
    let stream = stream::iter(0..10).then(|i| async move {
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
        // Interleaving side effects inside a cancellable body stream
        ledger_increment_exported_chunks(i).await;
        Ok::<_, std::io::Error>(format!("chunk {}\n", i))
    });

    Response::new(Body::from_stream(stream))
}

async fn ledger_increment_exported_chunks(_idx: usize) {}
```

#### Production Standard (Correct)
> **Standard**: By decoupling stream generation into an isolated `tokio::spawn` worker communicating through a bounded MPSC channel, downstream client disconnections only cause channel sends to fail. The worker retains execution control, deterministically records the exact number of transmitted chunks, and guarantees completion of non-cancellable audit actions.
```rust
use axum::{
    body::Body,
    response::Response,
    http::StatusCode,
};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

pub async fn stream_export_handler() -> Result<Response, StatusCode> {
    let (tx, rx) = mpsc::channel::<Result<String, std::io::Error>>(16);

    // ISOLATION: Worker runs in a detached task decoupled from socket drops
    tokio::spawn(async move {
        let mut committed_chunks = 0;
        for i in 0..10 {
            // Background processing invariant guaranteed against abrupt client disconnect
            let payload = format!("chunk {}\n", i);
            if tx.send(Ok(payload)).await.is_err() {
                // Downstream disconnected; handle cleanup deterministically
                tracing::warn!(completed = committed_chunks, "Client disconnected prematurely");
                break;
            }
            committed_chunks += 1;
        }
        // Critical side-effect executes regardless of transport termination
        record_final_export_audit(committed_chunks).await;
    });

    let body_stream = ReceiverStream::new(rx);
    Ok(Response::new(Body::from_stream(body_stream)))
}

async fn record_final_export_audit(_count: usize) {}
```

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 Service Async Cancellation Safety and Stream Isolation

Axum 0.8 Tower Service Async Cancellation Safety and Stream Isolation defines an industrial-grade behavioral standard for backend engineering. Enforces strict cancellation safety and state isolation in Axum 0.8 and Tower services when handling streaming HTTP bodies and chunked client responses. Prevents state corruption, partial distributed commits, and resource leaks caused by Tokio futures being abruptly dropped upon downstream client disconnections. 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: Executing non-atomic multi-step side effects across await points inside cancellable HTTP body streams 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 DriftExecuting non-atomic multi-step side effects across await points inside cancellable HTTP body streamsCritical
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 execute non-atomic state mutations or distributed side-effects across `.await` points inside client-polled HTTP streaming bodies.

Engineers MUST NEVER execute non-atomic state mutations or distributed side-effects across `.await` points inside client-polled HTTP streaming bodies.

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 isolate client-facing stream consumption from background processing via detached tasks (`tokio

Engineers MUST isolate client-facing stream consumption from background processing via detached tasks (`tokio::spawn`) and bounded memory channels (`tokio::sync::mpsc`).

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 implement explicit drop-safe guards or two-phase transaction handles using RAII types (such as `scopeguard` or explicit custom `Drop` impls) for partial state rollback when unwinding asynchronous scopes.

Services MUST implement explicit drop-safe guards or two-phase transaction handles using RAII types (such as `scopeguard` or explicit custom `Drop` impls) for partial state rollback when unwinding asynchronous scopes.

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

Handlers MUST utilize `tokio_util

Handlers MUST utilize `tokio_util::sync::CancellationToken` to propagate cooperative graceful cancellation rather than relying on uncoordinated future drops.

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

Streaming responses that deduct credits, update cursor offsets, or record audit events MUST commit state updates independently of whether the client consumed the stream to completion.

Streaming responses that deduct credits, update cursor offsets, or record audit events MUST commit state updates independently of whether the client consumed the stream to completion.

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.
6

Components NEVER assume `tower

Components NEVER assume `tower::Service::call` or Axum handler futures run to completion; all critical invariants must survive immediate, arbitrary future drops.

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 Service Async Cancellation Safety and Stream Isolation critical for AI coding assistants?

Enforces strict cancellation safety and state isolation in Axum 0.8 and Tower services when handling streaming HTTP bodies and chunked client responses. Prevents state corruption, partial distributed commits, and resource leaks caused by Tokio futures being abruptly dropped upon downstream client disconnections. 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 (Executing non-atomic multi-step side effects across await points inside cancellable HTTP body streams) 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