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

Tokio & Tower Buffer Backpressure and Circular-Wait Deadlock Prevention

Enforces strict ordering, worker isolation, and reservation-dispatch pairing for Tower Buffer middleware in Tokio-based Rust RPC clients and servers. Prevents re-entrant channel deadlocks, circular-wait lockups, and unmetered memory exhaustion in layered interceptor topologies.

Prohibited Anti-Pattern: Interleaved Awaits Between poll_ready and call in Tower Buffers Causing Worker Starvation and Circular-Wait Deadlocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tokio & Tower Buffer Backpressure and Circular-Wait Deadlock Prevention - Enforces strict ordering, worker isolation, and reservation-dispatch pairing for Tower Buffer middleware in Tokio-based Rust RPC clients and servers. Prevents re-entrant channel deadlocks, circular-wait lockups, and unmetered memory exhaustion in layered interceptor topologies.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tokio-tower-buffer-backpressure-deadlock-guardrail"
---

# Tokio & Tower Buffer Backpressure and Circular-Wait Deadlock Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Interleaved Awaits Between poll_ready and call in Tower Buffers Causing Worker Starvation and Circular-Wait Deadlocks

## System Constraints
You are a Principal Rust Systems Architect specializing in Tokio runtime internals and Tower service middleware composition. Enforce strict invariants regarding `tower::buffer::Buffer` channels, readiness permits, and task execution domains. Mandate that `poll_ready` reservations are never held across unrelated asynchronous yield points, re-entrant buffered RPC topologies are structurally forbidden, and bounded backpressure is coupled with timeout and load-shedding barriers.

## Strict Guidelines
- Engineers MUST ALWAYS invoke `Service::call` immediately after `ServiceExt::ready` or `Service::poll_ready` resolves to `Ok(())`, with ZERO intervening `.await` points or fallible async operations.
- Engineers MUST NOT invoke a `tower::buffer::Buffer` service from inside the execution context of the buffer's own inner worker task (re-entrant invocation causes instant single-worker deadlock).
- Services MUST decouple circular RPC dependencies using independent client channel pools, out-of-band notification queues, or non-buffered point-to-point connections rather than nested middleware buffers.
- Code SHOULD prefer `tower::util::ServiceExt::oneshot(service, request)` when consuming cloned multi-threaded service handles to guarantee atomic readiness reservation and request dispatch.
- Engineers MUST NEVER hold a mutable reference or permit acquired during `poll_ready` across an IPC/RPC round-trip, database transaction, or external mutex guard.
- Middleware stacks MUST pair `tower::buffer::Buffer` with upstream `tower::limit::concurrency` or `tower::load_shed::LoadShed` layers to prevent unbounded queue saturation and thread starvation under heavy load.

## Bad vs Good Implementations
### Tower Service Readiness Reservation and Dispatch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `ready().await` reserves a capacity slot in the Tower `Buffer` channel. Awaiting `auth_token_fetcher` while holding that reservation blocks the service slot. If the token fetcher itself triggers an RPC through the same buffered client, a circular-wait deadlock occurs.
```rust
use tower::{Service, ServiceExt};
use tokio::sync::Mutex;
use std::sync::Arc;

async fn execute_reentrant_call<S, Req>(
    client: Arc<Mutex<tower::buffer::Buffer<S, Req>>>,
    req: Req,
    auth_token_fetcher: impl std::future::Future<Output = String>,
) -> Result<S::Response, S::Error>
where
    S: Service<Req> + Send + 'static,
    Req: Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
{
    let mut svc = client.lock().await;
    // ANTI-PATTERN: Reserving buffer channel capacity, then yielding the runtime
    // during a network fetch. If the buffer is near capacity or auth_token_fetcher
    // calls back into the same client, this deadlocks the worker.
    svc.ready().await?;
    
    let _token = auth_token_fetcher.await; // Async yield holds the buffer permit!
    svc.call(req).await
}
```

#### Production Standard (Correct)
> **Standard**: All external asynchronous dependencies are fully resolved before reserving capacity. Using `client.oneshot(req).await` ensures the `poll_ready` permit acquisition and the `call` dispatch occur atomically without interleaved suspension points.
```rust
use tower::{Service, ServiceExt};

async fn execute_safe_call<S, Req>(
    client: tower::buffer::Buffer<S, Req>,
    req: Req,
    auth_token_fetcher: impl std::future::Future<Output = String>,
) -> Result<S::Response, S::Error>
where
    S: Service<Req> + Send + 'static,
    Req: Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
{
    // Invariant: Resolve all auxiliary async work BEFORE acquiring buffer permit
    let _token = auth_token_fetcher.await;
    
    // Atomically reserve buffer permit and dispatch request with no intervening yield
    client.oneshot(req).await
}
```

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 & Tower Buffer Backpressure and Circular-Wait Deadlock Prevention

Tokio & Tower Buffer Backpressure and Circular-Wait Deadlock Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces strict ordering, worker isolation, and reservation-dispatch pairing for Tower Buffer middleware in Tokio-based Rust RPC clients and servers. Prevents re-entrant channel deadlocks, circular-wait lockups, and unmetered memory exhaustion in layered interceptor topologies. 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: Interleaved Awaits Between poll_ready and call in Tower Buffers Causing Worker Starvation and Circular-Wait Deadlocks 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 DriftInterleaved Awaits Between poll_ready and call in Tower Buffers Causing Worker Starvation and Circular-Wait DeadlocksCritical
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 invoke `Service

Engineers MUST ALWAYS invoke `Service::call` immediately after `ServiceExt::ready` or `Service::poll_ready` resolves to `Ok(())`, with ZERO intervening `.await` points or fallible async operations.

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 invoke a `tower

Engineers MUST NOT invoke a `tower::buffer::Buffer` service from inside the execution context of the buffer's own inner worker task (re-entrant invocation causes instant single-worker deadlock).

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 decouple circular RPC dependencies using independent client channel pools, out-of-band notification queues, or non-buffered point-to-point connections rather than nested middleware buffers.

Services MUST decouple circular RPC dependencies using independent client channel pools, out-of-band notification queues, or non-buffered point-to-point connections rather than nested middleware buffers.

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

Code SHOULD prefer `tower

Code SHOULD prefer `tower::util::ServiceExt::oneshot(service, request)` when consuming cloned multi-threaded service handles to guarantee atomic readiness reservation and request dispatch.

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

Engineers MUST NEVER hold a mutable reference or permit acquired during `poll_ready` across an IPC/RPC round-trip, database transaction, or external mutex guard.

Engineers MUST NEVER hold a mutable reference or permit acquired during `poll_ready` across an IPC/RPC round-trip, database transaction, or external mutex 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.
6

Middleware stacks MUST pair `tower

Middleware stacks MUST pair `tower::buffer::Buffer` with upstream `tower::limit::concurrency` or `tower::load_shed::LoadShed` layers to prevent unbounded queue saturation and thread starvation under heavy load.

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 & Tower Buffer Backpressure and Circular-Wait Deadlock Prevention critical for AI coding assistants?

Enforces strict ordering, worker isolation, and reservation-dispatch pairing for Tower Buffer middleware in Tokio-based Rust RPC clients and servers. Prevents re-entrant channel deadlocks, circular-wait lockups, and unmetered memory exhaustion in layered interceptor topologies. 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 (Interleaved Awaits Between poll_ready and call in Tower Buffers Causing Worker Starvation and Circular-Wait Deadlocks) 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