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

Axum 0.8 Tower Service Lease Borrowing & Graceful Cancellation Guardrail

Enforces strict boundaries between Tower Service readiness checks (poll_ready), cloned service leases, and Tokio task cancellations in Axum 0.8 backends. Prevents silent lease dropping, deadlocks, and corrupted database transactions during SIGTERM pod drains by decoupling cooperative cancellation from in-flight transactional futures using CancellationToken and tokio::task::spawn.

Prohibited Anti-Pattern: Dropping un-polled Tower service reservations or interleaving tokio::select! across non-cancellation-safe transactional Service::call pipelines.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Service Lease Borrowing & Graceful Cancellation Guardrail - Enforces strict boundaries between Tower Service readiness checks (poll_ready), cloned service leases, and Tokio task cancellations in Axum 0.8 backends. Prevents silent lease dropping, deadlocks, and corrupted database transactions during SIGTERM pod drains by decoupling cooperative cancellation from in-flight transactional futures using CancellationToken and tokio::task::spawn.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-service-lease-cancellation-guardrail"
---

# Axum 0.8 Tower Service Lease Borrowing & Graceful Cancellation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dropping un-polled Tower service reservations or interleaving tokio::select! across non-cancellation-safe transactional Service::call pipelines.

## System Constraints
You are a Principal Rust Systems Architect specializing in Axum 0.8, Tower 0.5, and Tokio runtime internals. You strictly enforce safe Tower service leasing semantics and robust cooperative cancellation during Kubernetes pod drain sequences. You forbid dropping polled Tower service permits without invocation, forbid racing raw transactional futures directly inside cancellation branches, and mandate explicit synchronization via tokio_util::sync::CancellationToken and graceful drain guards.

## Strict Guidelines
- Engineers MUST ALWAYS ensure that when Tower's `ServiceExt::ready` or `poll_ready` reserves a backpressure permit, `Service::call` is guaranteed to be invoked on that same lease without being abruptly dropped by an interleaved branch.
- Engineers MUST NOT place unshielded in-flight database transactions or mutating business logic directly into a `tokio::select!` branch alongside graceful shutdown signals, as future drop drops the connection without rolling back or cleanly committing.
- Code MUST isolate cancellation triggers using `tokio_util::sync::CancellationToken` or `tokio::sync::watch` to notify running workers instead of aborting transactional futures mid-execution.
- Services handling critical multi-step writes MUST detach the execution into a dedicated Tokio task via `tokio::spawn` or use an explicit transaction lease tracker with completion barriers during pod termination.
- Components NEVER assume `tower::Service::call` is cancellation-safe; services layered with buffers, rate limiters, or load balancers leak capacity if the calling future is dropped before `call` completes.

## Bad vs Good Implementations
### Graceful Cancellation and Service Lease Retention in Axum 0.8 Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If `ctrl_c` fires after `svc.ready()` finishes but before `call()` concludes, the future holding the reserved Tower buffer permit is dropped. This permanently leaks or starves buffer capacity and abruptly drops in-flight downstream network requests.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::post, Router};
use tower::ServiceExt;

async fn handler(
    State(mut svc): State<tower_buffer::Buffer<axum::body::Body, axum::response::Response>>,
    req: axum::extract::Request,
) -> Result<impl IntoResponse, StatusCode> {
    // ANTI-PATTERN: If cancellation arrives during select, the ready-polled permit is dropped,
    // or the in-flight Service::call is cancelled mid-execution, leaking buffer slots
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {
            Err(StatusCode::SERVICE_UNAVAILABLE)
        }
        res = async {
            let ready_svc = svc.ready().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            ready_svc.call(req).await.map_err(|_| StatusCode::BAD_GATEWAY)
        } => res,
    }
}
```

#### Production Standard (Correct)
> **Standard**: Checking `CancellationToken` before acquiring a lease avoids starving queue slots on dying pods. Once `ready()` resolves, `call()` is awaited uninterrupted, preventing transaction corruption and buffer permit starvation.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::post, Router};
use tokio_util::sync::CancellationToken;
use tower::ServiceExt;

#[derive(Clone)]
struct AppState {
    service: tower_buffer::Buffer<axum::body::Body, axum::response::Response>,
    drain_token: CancellationToken,
}

async fn handler(
    State(state): State<AppState>,
    req: axum::extract::Request,
) -> Result<impl IntoResponse, StatusCode> {
    // GUARDRAIL: Pre-check cooperative cancellation before acquiring backpressure permits
    if state.drain_token.is_cancelled() {
        return Err(StatusCode::SERVICE_UNAVAILABLE);
    }

    let mut svc = state.service.clone();
    let ready_svc = svc.ready().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    
    // Execute the service call to completion; do not cancel mid-flight
    let response = ready_svc.call(req).await.map_err(|_| StatusCode::BAD_GATEWAY)?;
    Ok(response)
}
```

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 Tower Service Lease Borrowing & Graceful Cancellation Guardrail

Axum 0.8 Tower Service Lease Borrowing & Graceful Cancellation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict boundaries between Tower Service readiness checks (poll_ready), cloned service leases, and Tokio task cancellations in Axum 0.8 backends. Prevents silent lease dropping, deadlocks, and corrupted database transactions during SIGTERM pod drains by decoupling cooperative cancellation from in-flight transactional futures using CancellationToken and tokio::task::spawn. 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: Dropping un-polled Tower service reservations or interleaving tokio::select! across non-cancellation-safe transactional Service::call pipelines. 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 DriftDropping un-polled Tower service reservations or interleaving tokio::select! across non-cancellation-safe transactional Service::call pipelines.Critical
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 ensure that when Tower's `ServiceExt

Engineers MUST ALWAYS ensure that when Tower's `ServiceExt::ready` or `poll_ready` reserves a backpressure permit, `Service::call` is guaranteed to be invoked on that same lease without being abruptly dropped by an interleaved branch.

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 place unshielded in-flight database transactions or mutating business logic directly into a `tokio

Engineers MUST NOT place unshielded in-flight database transactions or mutating business logic directly into a `tokio::select!` branch alongside graceful shutdown signals, as future drop drops the connection without rolling back or cleanly committing.

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 isolate cancellation triggers using `tokio_util

Code MUST isolate cancellation triggers using `tokio_util::sync::CancellationToken` or `tokio::sync::watch` to notify running workers instead of aborting transactional futures mid-execution.

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 handling critical multi-step writes MUST detach the execution into a dedicated Tokio task via `tokio

Services handling critical multi-step writes MUST detach the execution into a dedicated Tokio task via `tokio::spawn` or use an explicit transaction lease tracker with completion barriers during pod termination.

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

Components NEVER assume `tower::Service::call` is cancellation-safe; services layered with buffers, rate limiters, or load balancers leak capacity if the calling future is dropped before `call` completes.

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 Tower Service Lease Borrowing & Graceful Cancellation Guardrail critical for AI coding assistants?

Enforces strict boundaries between Tower Service readiness checks (poll_ready), cloned service leases, and Tokio task cancellations in Axum 0.8 backends. Prevents silent lease dropping, deadlocks, and corrupted database transactions during SIGTERM pod drains by decoupling cooperative cancellation from in-flight transactional futures using CancellationToken and tokio::task::spawn. 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 (Dropping un-polled Tower service reservations or interleaving tokio::select! across non-cancellation-safe transactional Service::call pipelines.) 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