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

Axum 0.8 Tokio Cancellation Token & Bounded Backpressure Guardrail

Enforces deterministic cancellation and bounded queue backpressure across Axum 0.8 service pipelines using tokio_util::sync::CancellationToken and bounded Tokio mpsc channels. Prevents socket starvation, ghost resource consumption, and runaway compute when HTTP clients disconnect or downstream pipelines saturate.

Prohibited Anti-Pattern: Unbounded Channel Spawning and Unguarded Long-Running Tasks Without Cancellation Checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Cancellation Token & Bounded Backpressure Guardrail - Enforces deterministic cancellation and bounded queue backpressure across Axum 0.8 service pipelines using tokio_util::sync::CancellationToken and bounded Tokio mpsc channels. Prevents socket starvation, ghost resource consumption, and runaway compute when HTTP clients disconnect or downstream pipelines saturate.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-backpressure-guardrail"
---

# Axum 0.8 Tokio Cancellation Token & Bounded Backpressure Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Channel Spawning and Unguarded Long-Running Tasks Without Cancellation Checks

## System Constraints
You are a Principal Engineer enforcing Axum 0.8 and Tokio concurrency safety standards. You must ensure that all HTTP request pipelines propagate deterministic cancellation tokens (tokio_util::sync::CancellationToken) into background workers and spawn scopes. You must strictly forbid the use of unbounded channels (`tokio::sync::mpsc::unbounded_channel`) and unmanaged background task spawns (`tokio::spawn` without cancellation or abort handles), which lead to zombie processing jobs, memory exhaustion, and connection starvation upon client disconnect.

## Strict Guidelines
- Engineers MUST ALWAYS tie detached background workers spawned from Axum handlers to a child `tokio_util::sync::CancellationToken` or explicit `JoinHandle` abort guard.
- Engineers MUST ALWAYS enforce bounded channel capacities (`tokio::sync::mpsc::channel(N)`) with explicit backpressure or load-shedding strategies; `tokio::sync::mpsc::unbounded_channel` is strictly forbidden.
- Handlers invoking long-running loops or multistep compute MUST periodically check `token.is_cancelled()` or wrap async steps with `tokio::select!` on `token.cancelled()`.
- Services MUST propagate client socket disconnects to active processing loops via Tower middleware or Axum 0.8 request drop detection semantics.
- Components NEVER drop or ignore channel send errors (`send().await.unwrap()` or `let _ = tx.send()`) without handling downstream consumer termination and backpressure signals.

## Bad vs Good Implementations
### Propagating Cancellation and Bounded Channel Backpressure in Axum Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses an unbounded channel that leads to unbounded memory growth during downstream saturation. Spawns an unmonitored background task with no cancellation token, meaning downstream work continues consuming CPU and memory indefinitely even if the client disconnects or the service shuts down.
```rust
use axum::{extract::State, response::IntoResponse, Json};
use tokio::sync::mpsc;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct JobRequest { pub payload: String }

pub async fn submit_job(
    Json(payload): Json<JobRequest>,
) -> impl IntoResponse {
    // ANTI-PATTERN: Unbounded channel invites OOM under load
    let (tx, mut rx) = mpsc::unbounded_channel();
    
    // ANTI-PATTERN: tokio::spawn without cancellation token or JoinHandle tracking.
    // If client disconnects or pipeline fails, this task runs to completion as a ghost worker.
    tokio::spawn(async move {
        while let Some(item) = rx.recv().await {
            // Heavy computation ignoring cancellation
            tokio::time::sleep(std::time::Duration::from_secs(10)).await;
            println!("Processed: {}", item);
        }
    });

    tx.send(payload.payload).unwrap();
    "Accepted"
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a bounded channel with a strict 500ms timeout backpressure check, avoiding infinite queue buffer buildup. Uses Tokio CancellationToken hierarchy to cleanly abandon operations during server shutdown or client aborts.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use serde::Deserialize;
use std::sync::Arc;

#[derive(Deserialize)]
pub struct JobRequest { pub payload: String }

#[derive(Clone)]
pub struct AppState {
    pub tx: mpsc::Sender<String>,
    pub cancel_token: CancellationToken,
}

pub async fn submit_job(
    State(state): State<Arc<AppState>>,
    Json(payload): Json<JobRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let child_token = state.cancel_token.child_token();

    // INVARIANT: Bounded channel with backpressure and cancellation race
    tokio::select! {
        biased;
        _ = child_token.cancelled() => {
            Err(StatusCode::SERVICE_UNAVAILABLE)
        }
        send_res = state.tx.send_timeout(payload.payload, std::time::Duration::from_millis(500)) => {
            send_res.map_err(|_| StatusCode::TOO_MANY_REQUESTS)?;
            Ok((StatusCode::ACCEPTED, "Accepted"))
        }
    }
}
```

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 Tokio Cancellation Token & Bounded Backpressure Guardrail

Axum 0.8 Tokio Cancellation Token & Bounded Backpressure Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation and bounded queue backpressure across Axum 0.8 service pipelines using tokio_util::sync::CancellationToken and bounded Tokio mpsc channels. Prevents socket starvation, ghost resource consumption, and runaway compute when HTTP clients disconnect or downstream pipelines saturate. 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: Unbounded Channel Spawning and Unguarded Long-Running Tasks Without Cancellation Checks 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 DriftUnbounded Channel Spawning and Unguarded Long-Running Tasks Without Cancellation ChecksCritical
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 tie detached background workers spawned from Axum handlers to a child `tokio_util

Engineers MUST ALWAYS tie detached background workers spawned from Axum handlers to a child `tokio_util::sync::CancellationToken` or explicit `JoinHandle` abort guard.

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 ALWAYS enforce bounded channel capacities (`tokio

Engineers MUST ALWAYS enforce bounded channel capacities (`tokio::sync::mpsc::channel(N)`) with explicit backpressure or load-shedding strategies; `tokio::sync::mpsc::unbounded_channel` is strictly forbidden.

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

Handlers invoking long-running loops or multistep compute MUST periodically check `token.is_cancelled()` or wrap async steps with `tokio

Handlers invoking long-running loops or multistep compute MUST periodically check `token.is_cancelled()` or wrap async steps with `tokio::select!` on `token.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.
4

Services MUST propagate client socket disconnects to active processing loops via Tower middleware or Axum 0.8 request drop detection semantics.

Services MUST propagate client socket disconnects to active processing loops via Tower middleware or Axum 0.8 request drop detection 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.
5

Components NEVER drop or ignore channel send errors (`send().await.unwrap()` or `let _ = tx.send()`) without handling downstream consumer termination and backpressure signals.

Components NEVER drop or ignore channel send errors (`send().await.unwrap()` or `let _ = tx.send()`) without handling downstream consumer termination and backpressure signals.

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 Tokio Cancellation Token & Bounded Backpressure Guardrail critical for AI coding assistants?

Enforces deterministic cancellation and bounded queue backpressure across Axum 0.8 service pipelines using tokio_util::sync::CancellationToken and bounded Tokio mpsc channels. Prevents socket starvation, ghost resource consumption, and runaway compute when HTTP clients disconnect or downstream pipelines saturate. 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 (Unbounded Channel Spawning and Unguarded Long-Running Tasks Without Cancellation Checks) 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