This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: tokio-cooperative-drop-safety-axum-production-standard

Tokio Cooperative Scheduling Budget & Drop-Safety Invariant for Axum 0.8

Enforces deterministic cooperative scheduling budgets and strict drop-safety invariants across Axum 0.8 HTTP/3 stream lifecycles. Eliminates worker-thread starvation caused by unbounded stream polling loops and prevents persistent data corruption resulting from arbitrary task cancellation when HTTP/3 client streams reset mid-mutation.

Prohibited Anti-Pattern: Unbounded Stream Polling Bypassing Tokio Budget and Multi-Stage Awaits Violating Future Drop-Safety During HTTP/3 Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tokio Cooperative Scheduling Budget & Drop-Safety Invariant for Axum 0.8 - Enforces deterministic cooperative scheduling budgets and strict drop-safety invariants across Axum 0.8 HTTP/3 stream lifecycles. Eliminates worker-thread starvation caused by unbounded stream polling loops and prevents persistent data corruption resulting from arbitrary task cancellation when HTTP/3 client streams reset mid-mutation.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tokio-cooperative-drop-safety-axum-production-standard"
---

# Tokio Cooperative Scheduling Budget & Drop-Safety Invariant for Axum 0.8

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Stream Polling Bypassing Tokio Budget and Multi-Stage Awaits Violating Future Drop-Safety During HTTP/3 Cancellation

## System Constraints
You are a Principal Systems Architect enforcing Tokio cooperative scheduling and cancellation drop-safety invariants in Axum 0.8. Ensure all streaming handlers yield to the runtime budget and all partial-state mutations remain fully cancellation-safe against abrupt HTTP/3 stream termination.

## Strict Guidelines
- Engineers MUST ALWAYS enforce cancellation safety across all `.await` points by avoiding intermediate persistent state mutations directly inside volatile Axum HTTP handler futures.
- Engineers MUST NOT maintain uncommitted transactional state or hold critical non-transactional resources across `.await` points where client-side HTTP/3 stream cancellations drop the future.
- Code MUST explicitly integrate `tokio::task::consume_budget().await` or `tokio::task::yield_now().await` inside tight streaming loops or CPU-bound stream decoders to avoid worker starvation.
- Services MUST execute non-cancellable critical operations via detached tasks (`tokio::spawn`) or explicit two-phase transactional rollbacks managed via RAII drop guards.
- Components NEVER assume an Axum handler completes to completion; every `.await` in an HTTP/3 request context is a potential early-termination drop point.

## Bad vs Good Implementations
### HTTP/3 Stream Processing with Cooperative Scheduling and Cancellation-Safe Invariants

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler mutates persistent state sequentially across `.await` points without drop protection. An HTTP/3 RST_STREAM or connection reset causes Axum to immediately drop the future, leaking unfinalized database allocations. Additionally, streaming loops without cooperative scheduling checks can starve Tokio runtime workers during large payload ingestion.
```rust
use axum::{extract::BodyStream, http::StatusCode, response::IntoResponse};
use futures_util::StreamExt;

pub async fn process_audit_log(
    mut stream: BodyStream,
) -> Result<impl IntoResponse, StatusCode> {
    // ANTI-PATTERN: Direct multi-step mutation across await points.
    // If the HTTP/3 stream resets, the DB reservation remains unfinalized, causing state corruption.
    let log_id = db::allocate_audit_slot().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    let mut total_bytes = 0usize;
    // Starvation hazard: Unbounded iteration without budget cooperativity can monopolize worker threads.
    while let Some(chunk_result) = stream.next().await {
        let chunk = chunk_result.map_err(|_| StatusCode::BAD_REQUEST)?;
        total_bytes += chunk.len();
        db::append_raw_chunk(log_id, &chunk).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    }

    // If HTTP/3 RST_STREAM arrives prior to this call, commit is dropped, leaving orphaned logs.
    db::finalize_audit_slot(log_id, total_bytes).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: Implements an RAII drop guard that dispatches guaranteed asynchronous cleanup via `tokio::spawn` if the HTTP/3 stream is aborted prematurely. Incorporates `task::consume_budget().await` to yield execution back to Tokio's cooperative scheduler during heavy stream consumption.
```rust
use axum::{body::Body, extract::Request, http::StatusCode, response::IntoResponse};
use futures_util::StreamExt;
use tokio::task;

struct AuditGuard {
    log_id: u64,
    committed: bool,
}

impl Drop for AuditGuard {
    fn drop(&mut self) {
        if !self.committed {
            let id = self.log_id;
            // Spawn background task ensuring rollback invariant survives future cancellation
            tokio::spawn(async move {
                let _ = db::rollback_audit_slot(id).await;
            });
        }
    }
}

pub async fn process_audit_log(
    req: Request<Body>,
) -> Result<impl IntoResponse, StatusCode> {
    let log_id = db::allocate_audit_slot().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    let mut guard = AuditGuard { log_id, committed: false };
    let mut stream = req.into_body().into_data_stream();
    let mut total_bytes = 0usize;

    while let Some(chunk_res) = stream.next().await {
        // Enforce Tokio cooperative scheduling budget to prevent worker thread starvation
        task::consume_budget().await;

        let chunk = chunk_res.map_err(|_| StatusCode::BAD_REQUEST)?;
        total_bytes += chunk.len();
        db::append_raw_chunk(guard.log_id, &chunk).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    }

    db::finalize_audit_slot(guard.log_id, total_bytes).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    guard.committed = true;

    Ok(StatusCode::OK)
}
```

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: Tokio Cooperative Scheduling Budget & Drop-Safety Invariant for Axum 0.8

Tokio Cooperative Scheduling Budget & Drop-Safety Invariant for Axum 0.8 defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cooperative scheduling budgets and strict drop-safety invariants across Axum 0.8 HTTP/3 stream lifecycles. Eliminates worker-thread starvation caused by unbounded stream polling loops and prevents persistent data corruption resulting from arbitrary task cancellation when HTTP/3 client streams reset mid-mutation. 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 Stream Polling Bypassing Tokio Budget and Multi-Stage Awaits Violating Future Drop-Safety During HTTP/3 Cancellation 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 Stream Polling Bypassing Tokio Budget and Multi-Stage Awaits Violating Future Drop-Safety During HTTP/3 CancellationCritical
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 enforce cancellation safety across all `.await` points by avoiding intermediate persistent state mutations directly inside volatile Axum HTTP handler futures.

Engineers MUST ALWAYS enforce cancellation safety across all `.await` points by avoiding intermediate persistent state mutations directly inside volatile Axum HTTP handler futures.

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 maintain uncommitted transactional state or hold critical non-transactional resources across `.await` points where client-side HTTP/3 stream cancellations drop the future.

Engineers MUST NOT maintain uncommitted transactional state or hold critical non-transactional resources across `.await` points where client-side HTTP/3 stream cancellations drop 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 MUST explicitly integrate `tokio

Code MUST explicitly integrate `tokio::task::consume_budget().await` or `tokio::task::yield_now().await` inside tight streaming loops or CPU-bound stream decoders to avoid worker starvation.

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 execute non-cancellable critical operations via detached tasks (`tokio

Services MUST execute non-cancellable critical operations via detached tasks (`tokio::spawn`) or explicit two-phase transactional rollbacks managed via RAII drop guards.

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 assume an Axum handler completes to completion

Components NEVER assume an Axum handler completes to completion; every `.await` in an HTTP/3 request context is a potential early-termination drop 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 Tokio Cooperative Scheduling Budget & Drop-Safety Invariant for Axum 0.8 critical for AI coding assistants?

Enforces deterministic cooperative scheduling budgets and strict drop-safety invariants across Axum 0.8 HTTP/3 stream lifecycles. Eliminates worker-thread starvation caused by unbounded stream polling loops and prevents persistent data corruption resulting from arbitrary task cancellation when HTTP/3 client streams reset mid-mutation. 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 Stream Polling Bypassing Tokio Budget and Multi-Stage Awaits Violating Future Drop-Safety During HTTP/3 Cancellation) 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

Tokio