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

Axum 0.8 & Hyper 1.x Cooperative Request Cancellation Propagation

Enforces deterministic cancellation propagation across asynchronous boundaries in Axum 0.8 and Hyper 1.x services. Prevents orphaned compute and connection pool exhaustion by binding subtasks and database operations to client socket drop lifecycles using structured cancellation tokens and RAII drop guards.

Prohibited Anti-Pattern: Detached background execution and unlinked Tokio spawns running after HTTP client disconnection

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Hyper 1.x Cooperative Request Cancellation Propagation - Enforces deterministic cancellation propagation across asynchronous boundaries in Axum 0.8 and Hyper 1.x services. Prevents orphaned compute and connection pool exhaustion by binding subtasks and database operations to client socket drop lifecycles using structured cancellation tokens and RAII drop guards.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-hyper-cooperative-cancellation-propagation"
---

# Axum 0.8 & Hyper 1.x Cooperative Request Cancellation Propagation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached background execution and unlinked Tokio spawns running after HTTP client disconnection

## System Constraints
You are a Principal Rust Systems Architect enforcing cooperative cancellation and resource isolation in Axum 0.8 and Hyper 1.x services. You must reject any unbounded concurrency, unlinked background tasks, or database queries that fail to abort when the client terminates the HTTP connection.

## Strict Guidelines
- Engineers MUST ALWAYS propagate a `tokio_util::sync::CancellationToken` or rely on future drop semantics (RAII) for synchronous cancellation down to database drivers and I/O tasks.
- Engineers MUST NOT call `tokio::spawn` directly inside request handlers without linking the spawned task's lifecycle via an abort handle or child `CancellationToken` (because `JoinHandle::drop` detaches rather than aborts).
- Code MUST use `tokio::select!` cautiously with cancellation-safe futures, ensuring stateful streams or transactions are not dropped in corrupted mid-states.
- Services MUST configure database drivers (e.g., SQLx, Deadpool) with aggressive cancellation awareness or explicit statement timeouts to release pool connections when handler futures drop.
- Components NEVER execute unbound compute-heavy loops without invoking `tokio::task::yield_now()` or periodically checking `cancellation_token.is_cancelled()`.

## Bad vs Good Implementations
### Cooperative Task Abort via Drop Guards vs Detached Fire-and-Forget

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Tokio, dropping a `JoinHandle` does not cancel the underlying task; it detaches it. When a Hyper/Axum client aborts an in-flight HTTP request, the top-level handler future is dropped, but the spawned task continues to execute against PostgreSQL, exhausting pool connections and compute resources.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use sqlx::PgPool;

#[derive(Deserialize)]
pub struct ReportQuery { pub report_id: i64 }

pub async fn generate_report(
    State(pool): State<PgPool>,
    Json(query): Json<ReportQuery>,
) -> Result<impl IntoResponse, StatusCode> {
    // ANTI-PATTERN: `tokio::spawn` detaches on drop.
    // If the client disconnects, Axum drops `generate_report`, but this task
    // continues executing in the background, consuming CPU and DB connections.
    let join_handle = tokio::spawn(async move {
        sqlx::query!("SELECT pg_sleep(30), heavy_compute($1)", query.report_id)
            .fetch_one(&pool)
            .await
    });

    match join_handle.await {
        Ok(Ok(_)) => Ok(StatusCode::OK),
        _ => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}
```

#### Production Standard (Correct)
> **Standard**: A `CancellationToken::drop_guard()` triggers when the client disconnects and Axum drops the parent future. The spawned task races its database query against `child_token.cancelled()`, immediately terminating execution and releasing database and memory resources.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use sqlx::PgPool;
use tokio_util::sync::CancellationToken;

#[derive(Deserialize)]
pub struct ReportQuery { pub report_id: i64 }

pub async fn generate_report(
    State(pool): State<PgPool>,
    Json(query): Json<ReportQuery>,
) -> Result<impl IntoResponse, StatusCode> {
    let token = CancellationToken::new();
    let child_token = token.child_token();

    // RAII guard ensuring subtask cancellation when handler drops
    let _drop_guard = token.drop_guard();

    let mut join_handle = tokio::spawn(async move {
        tokio::select! {
            _ = child_token.cancelled() => {
                // Perform fast deterministic cleanup if necessary
                Err(sqlx::Error::PoolClosed)
            }
            res = sqlx::query!("SELECT heavy_compute($1)", query.report_id).fetch_one(&pool) => {
                res
            }
        }
    });

    match (&mut join_handle).await {
        Ok(Ok(_)) => Ok(StatusCode::OK),
        Ok(Err(_)) => Err(StatusCode::REQUEST_TIMEOUT),
        Err(e) if e.is_cancelled() => Err(StatusCode::SERVICE_UNAVAILABLE),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}
```

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 & Hyper 1.x Cooperative Request Cancellation Propagation

Axum 0.8 & Hyper 1.x Cooperative Request Cancellation Propagation defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation propagation across asynchronous boundaries in Axum 0.8 and Hyper 1.x services. Prevents orphaned compute and connection pool exhaustion by binding subtasks and database operations to client socket drop lifecycles using structured cancellation tokens and RAII drop guards. 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: Detached background execution and unlinked Tokio spawns running after HTTP client disconnection 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 DriftDetached background execution and unlinked Tokio spawns running after HTTP client disconnectionCritical
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 propagate a `tokio_util

Engineers MUST ALWAYS propagate a `tokio_util::sync::CancellationToken` or rely on future drop semantics (RAII) for synchronous cancellation down to database drivers and I/O tasks.

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

Engineers MUST NOT call `tokio::spawn` directly inside request handlers without linking the spawned task's lifecycle via an abort handle or child `CancellationToken` (because `JoinHandle::drop` detaches rather than aborts).

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

Code MUST use `tokio::select!` cautiously with cancellation-safe futures, ensuring stateful streams or transactions are not dropped in corrupted mid-states.

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 database drivers (e.g., SQLx, Deadpool) with aggressive cancellation awareness or explicit statement timeouts to release pool connections when handler futures drop.

Services MUST configure database drivers (e.g., SQLx, Deadpool) with aggressive cancellation awareness or explicit statement timeouts to release pool connections when handler futures drop.

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 execute unbound compute-heavy loops without invoking `tokio

Components NEVER execute unbound compute-heavy loops without invoking `tokio::task::yield_now()` or periodically checking `cancellation_token.is_cancelled()`.

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 & Hyper 1.x Cooperative Request Cancellation Propagation critical for AI coding assistants?

Enforces deterministic cancellation propagation across asynchronous boundaries in Axum 0.8 and Hyper 1.x services. Prevents orphaned compute and connection pool exhaustion by binding subtasks and database operations to client socket drop lifecycles using structured cancellation tokens and RAII drop guards. 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 (Detached background execution and unlinked Tokio spawns running after HTTP client disconnection) 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