This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-tokio-task-budget-ingress-backpressure-standard

Axum 0.8 Tokio Co-Op Task Budgeting & Ingress Backpressure Standard

Enforces strict cooperative task scheduling budgets, non-blocking async runtime boundaries, and bounded ingress backpressure in Axum 0.8 microservices. Eliminates Tokio event-loop starvation and ungraceful connection drops during synchronous request floods through explicit load shedding and cooperative yielding.

Prohibited Anti-Pattern: Unbounded TCP Ingress & Starving Tokio Worker Threads with Unbudgeted CPU Operations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Co-Op Task Budgeting & Ingress Backpressure Standard - Enforces strict cooperative task scheduling budgets, non-blocking async runtime boundaries, and bounded ingress backpressure in Axum 0.8 microservices. Eliminates Tokio event-loop starvation and ungraceful connection drops during synchronous request floods through explicit load shedding and cooperative yielding.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-tokio-task-budget-ingress-backpressure-standard"
---

# Axum 0.8 Tokio Co-Op Task Budgeting & Ingress Backpressure Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded TCP Ingress & Starving Tokio Worker Threads with Unbudgeted CPU Operations

## System Constraints
You are a Principal Rust Distributed Systems Architect enforcing Axum 0.8 and Tokio co-op scheduling standards. All async handlers and ingress pipelines must defend the Tokio event loop from worker thread starvation, enforce bounded concurrency via Tower middleware, offload compute-heavy routines to dedicated blocking pools, and maintain explicit backpressure signals to prevent cascading tail-latency spikes.

## Strict Guidelines
- Engineers MUST ALWAYS bound incoming TCP concurrency at the HTTP layer using Tower's `ConcurrencyLimitLayer` and `LoadShedLayer` before passing traffic into application routes.
- Engineers MUST offload any CPU-bound or blocking computation exceeding 10-100 microseconds to `tokio::task::spawn_blocking` or a dedicated `rayon` threadpool.
- Engineers MUST call `tokio::task::consume_budget().await` or `tokio::task::yield_now().await` inside tight loops within async contexts to prevent starving other tasks pinned to the same worker thread.
- Services MUST implement graceful draining during termination using `axum::serve::Serve::with_graceful_shutdown` linked to a bounded timeout drain signal.
- Handlers MUST NEVER execute synchronous file I/O, synchronous locks (`std::sync::Mutex`), or unbounded iterator evaluations directly on Tokio runtime worker threads.

## Bad vs Good Implementations
### Ingress Concurrency Limiting and Task Co-Op Budgeting

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler runs CPU-intensive blocking work directly inside an async function without yielding or offloading to `spawn_blocking`. Additionally, the router lacks ingress backpressure (`ConcurrencyLimitLayer` or `LoadShedLayer`), allowing high-concurrency bursts to monopolize Tokio worker threads and cause socket timeouts.
```rust
use axum::{routing::post, Json, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct BatchPayload { items: Vec<String> }

// ANTI-PATTERN: Heavy iteration without co-op yielding on a Tokio worker thread.
// Unbounded ingress allows simultaneous floods to starve the Tokio reactor.
async fn process_batch(Json(payload): Json<BatchPayload>) -> &'static str {
    for item in payload.items {
        // Synchronous heavy hashing/crypto blocks Tokio worker thread
        let _hash = sha256_digest_heavy(&item);
    }
    "done"
}

pub fn app() -> Router {
    // No load shedding, no concurrency bounds
    Router::new().route("/batch", post(process_batch))
}

fn sha256_digest_heavy(_: &str) -> String {
    // Simulated heavy CPU work
    std::thread::sleep(std::time::Duration::from_millis(1));
    String::new()
}
```

#### Production Standard (Correct)
> **Standard**: Enforces backpressure using `ConcurrencyLimitLayer` and `LoadShedLayer` to reject excess requests with HTTP 503 instead of crashing or ballooning memory. Offloads blocking CPU computation to `tokio::task::spawn_blocking`, keeping the Tokio event loop completely responsive.
```rust
use axum::{
    error_handling::HandleErrorLayer,
    http::StatusCode,
    routing::post,
    BoxError, Json, Router,
};
use serde::Deserialize;
use std::time::Duration;
use tower::{limit::ConcurrencyLimitLayer, load_shed::LoadShedLayer, ServiceBuilder};

#[derive(Deserialize, Clone)]
struct BatchPayload { items: Vec<String> }

async fn process_batch(Json(payload): Json<BatchPayload>) -> Result<&'static str, StatusCode> {
    // Offload CPU-heavy computation off the Tokio async worker pool
    tokio::task::spawn_blocking(move || {
        for item in payload.items {
            let _hash = sha256_digest_heavy(&item);
        }
    })
    .await
    .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok("done")
}

pub fn app() -> Router {
    // Apply backpressure: Shed load immediately when bounded concurrency is saturated
    let middleware = ServiceBuilder::new()
        .layer(HandleErrorLayer::new(|err: BoxError| async move {
            if err.is::<tower::load_shed::error::Overloaded>() {
                (StatusCode::SERVICE_UNAVAILABLE, "Server overloaded\n")
            } else {
                (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error\n")
            }
        }))
        .layer(LoadShedLayer::new())
        .layer(ConcurrencyLimitLayer::new(1024))
        .timeout(Duration::from_secs(10));

    Router::new()
        .route("/batch", post(process_batch))
        .layer(middleware)
}

fn sha256_digest_heavy(_: &str) -> String {
    // Safe inside spawn_blocking
    std::thread::sleep(std::time::Duration::from_millis(1));
    String::new()
}
```

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 Co-Op Task Budgeting & Ingress Backpressure Standard

Axum 0.8 Tokio Co-Op Task Budgeting & Ingress Backpressure Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict cooperative task scheduling budgets, non-blocking async runtime boundaries, and bounded ingress backpressure in Axum 0.8 microservices. Eliminates Tokio event-loop starvation and ungraceful connection drops during synchronous request floods through explicit load shedding and cooperative yielding. 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 TCP Ingress & Starving Tokio Worker Threads with Unbudgeted CPU Operations 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 TCP Ingress & Starving Tokio Worker Threads with Unbudgeted CPU OperationsCritical
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 bound incoming TCP concurrency at the HTTP layer using Tower's `ConcurrencyLimitLayer` and `LoadShedLayer` before passing traffic into application routes.

Engineers MUST ALWAYS bound incoming TCP concurrency at the HTTP layer using Tower's `ConcurrencyLimitLayer` and `LoadShedLayer` before passing traffic into application routes.

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 offload any CPU-bound or blocking computation exceeding 10-100 microseconds to `tokio

Engineers MUST offload any CPU-bound or blocking computation exceeding 10-100 microseconds to `tokio::task::spawn_blocking` or a dedicated `rayon` threadpool.

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

Engineers MUST call `tokio::task::consume_budget().await` or `tokio::task::yield_now().await` inside tight loops within async contexts to prevent starving other tasks pinned to the same worker thread.

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 implement graceful draining during termination using `axum

Services MUST implement graceful draining during termination using `axum::serve::Serve::with_graceful_shutdown` linked to a bounded timeout drain signal.

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

Handlers MUST NEVER execute synchronous file I/O, synchronous locks (`std

Handlers MUST NEVER execute synchronous file I/O, synchronous locks (`std::sync::Mutex`), or unbounded iterator evaluations directly on Tokio runtime worker threads.

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 Co-Op Task Budgeting & Ingress Backpressure Standard critical for AI coding assistants?

Enforces strict cooperative task scheduling budgets, non-blocking async runtime boundaries, and bounded ingress backpressure in Axum 0.8 microservices. Eliminates Tokio event-loop starvation and ungraceful connection drops during synchronous request floods through explicit load shedding and cooperative yielding. 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 TCP Ingress & Starving Tokio Worker Threads with Unbudgeted CPU Operations) 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