This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: sqlx-tokio-dead-socket-eviction-guardrail

SQLx/Tokio Active Heartbeat and TCP Half-Close Eviction Invariant

Enforces strict pre-acquisition health validation, aggressive idle eviction, and kernel-level TCP keepalive probes within SQLx pools managed by Tokio runtimes. This eliminates transaction lockups and zero-window worker stalls caused by silent connection state drops across cloud NAT gateways, proxies, and service mesh boundaries.

Prohibited Anti-Pattern: Trusting stale pool connections across cloud NAT boundaries without test-on-acquire or kernel keepalives

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SQLx/Tokio Active Heartbeat and TCP Half-Close Eviction Invariant - Enforces strict pre-acquisition health validation, aggressive idle eviction, and kernel-level TCP keepalive probes within SQLx pools managed by Tokio runtimes. This eliminates transaction lockups and zero-window worker stalls caused by silent connection state drops across cloud NAT gateways, proxies, and service mesh boundaries.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/sqlx-tokio-dead-socket-eviction-guardrail"
---

# SQLx/Tokio Active Heartbeat and TCP Half-Close Eviction Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Trusting stale pool connections across cloud NAT boundaries without test-on-acquire or kernel keepalives

## System Constraints
You are a Principal Rust Architect enforcing resilience invariants on SQLx and Tokio connection pools. Cloud gateways, NAT middleboxes, and service meshes (Envoy, AWS NAT Gateway, GCP Cloud SQL Auth Proxy) silently drop idle TCP connections without propagating FIN/RST packets. You MUST mandate that all SQLx connection pools configure deterministic acquisition timeouts, kernel-level TCP keepalives, active pre-acquisition validation (test_before_acquire), and maximum lifetimes strictly below middlebox idle thresholds to prevent zero-window stalls and asynchronous task hangs.

## Strict Guidelines
- Engineers MUST ALWAYS configure `test_before_acquire(true)` on `sqlx::pool::PoolOptions` to detect dead sockets via ping prior to transaction initialization.
- Engineers MUST ALWAYS set `acquire_timeout` to an upper bound (typically 2 to 5 seconds) to prevent infinite async task suspension on network deadlocks.
- Engineers MUST configure `idle_timeout` and `max_lifetime` on the pool to values strictly lower than intermediary NAT/firewall tracking limits (e.g., maximum 300 seconds for idle timeout against 350-second NAT gateways).
- Engineers MUST explicitly set low-interval OS-level TCP keepalives on database connection options (e.g., `PgConnectOptions::tcp_keepalive`) to detect half-closed sockets out of band.
- Code MUST NEVER invoke `pool.acquire()` or `pool.begin()` without enclosing it in a circuit-breaker, structured timeout, or with a pool configured without `acquire_timeout`.
- Components NEVER assume an idle connection retained across an `await` point or long sleep remains valid without re-verification.

## Bad vs Good Implementations
### Production-grade SQLx PostgreSQL Pool Configuration with Dead-Socket Eviction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default pool construction relies on lazy TCP write errors. When cloud NAT or stateful firewalls drop idle sessions without FIN/RST, the pool hands out zombie sockets. Subsequent read/writes hang on TCP socket timeouts (which can exceed 15 minutes by default under Linux retransmission backoff), exhausting the Tokio worker pool.
```rust
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use std::time::Duration;

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    // ANTI-PATTERN: Default pool options leave connection validation disabled,
    // acquire_timeout unset or excessively long, and no idle/lifetime bounds.
    // A NAT gateway or proxy timeout will cause acquire() or begin() to hang
    // indefinitely into a zero-window TCP retransmit storm.
    PgPoolOptions::new()
        .max_connections(50)
        .connect(database_url)
        .await
}
```

#### Production Standard (Correct)
> **Standard**: By combining `test_before_acquire(true)` with driver-level `tcp_keepalive(60s)` and a bounded `acquire_timeout(3s)`, dead sockets dropped by middleboxes are detected immediately and evicted before transaction binding, preventing zero-window stalls and cascading task starvation.
```rust
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use sqlx::PgPool;
use std::str::FromStr;
use std::time::Duration;

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    // INVARIANT: Explicit TCP keepalives at driver level prevent silent state eviction
    let connect_opts = PgConnectOptions::from_str(database_url)?
        .tcp_keepalive(Some(Duration::from_secs(60)));

    // INVARIANT: Active verification before handoff, strict acquire timeouts,
    // and maximum lifetime lower than cloud NAT conntrack limits (e.g. AWS 350s)
    PgPoolOptions::new()
        .max_connections(50)
        .min_connections(5)
        .acquire_timeout(Duration::from_secs(3))
        .idle_timeout(Some(Duration::from_secs(120)))
        .max_lifetime(Some(Duration::from_secs(600)))
        .test_before_acquire(true)
        .connect_with(connect_opts)
        .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: SQLx/Tokio Active Heartbeat and TCP Half-Close Eviction Invariant

SQLx/Tokio Active Heartbeat and TCP Half-Close Eviction Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict pre-acquisition health validation, aggressive idle eviction, and kernel-level TCP keepalive probes within SQLx pools managed by Tokio runtimes. This eliminates transaction lockups and zero-window worker stalls caused by silent connection state drops across cloud NAT gateways, proxies, and service mesh boundaries. 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: Trusting stale pool connections across cloud NAT boundaries without test-on-acquire or kernel keepalives 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 DriftTrusting stale pool connections across cloud NAT boundaries without test-on-acquire or kernel keepalivesCritical
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 configure `test_before_acquire(true)` on `sqlx

Engineers MUST ALWAYS configure `test_before_acquire(true)` on `sqlx::pool::PoolOptions` to detect dead sockets via ping prior to transaction initialization.

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 set `acquire_timeout` to an upper bound (typically 2 to 5 seconds) to prevent infinite async task suspension on network deadlocks.

Engineers MUST ALWAYS set `acquire_timeout` to an upper bound (typically 2 to 5 seconds) to prevent infinite async task suspension on network deadlocks.

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 configure `idle_timeout` and `max_lifetime` on the pool to values strictly lower than intermediary NAT/firewall tracking limits (e.g., maximum 300 seconds for idle timeout against 350-second NAT gateways).

Engineers MUST configure `idle_timeout` and `max_lifetime` on the pool to values strictly lower than intermediary NAT/firewall tracking limits (e.g., maximum 300 seconds for idle timeout against 350-second NAT gateways).

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

Engineers MUST explicitly set low-interval OS-level TCP keepalives on database connection options (e.g., `PgConnectOptions

Engineers MUST explicitly set low-interval OS-level TCP keepalives on database connection options (e.g., `PgConnectOptions::tcp_keepalive`) to detect half-closed sockets out of band.

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

Code MUST NEVER invoke `pool.acquire()` or `pool.begin()` without enclosing it in a circuit-breaker, structured timeout, or with a pool configured without `acquire_timeout`.

Code MUST NEVER invoke `pool.acquire()` or `pool.begin()` without enclosing it in a circuit-breaker, structured timeout, or with a pool configured without `acquire_timeout`.

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

Components NEVER assume an idle connection retained across an `await` point or long sleep remains valid without re-verification.

Components NEVER assume an idle connection retained across an `await` point or long sleep remains valid without re-verification.

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 SQLx/Tokio Active Heartbeat and TCP Half-Close Eviction Invariant critical for AI coding assistants?

Enforces strict pre-acquisition health validation, aggressive idle eviction, and kernel-level TCP keepalive probes within SQLx pools managed by Tokio runtimes. This eliminates transaction lockups and zero-window worker stalls caused by silent connection state drops across cloud NAT gateways, proxies, and service mesh boundaries. 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 (Trusting stale pool connections across cloud NAT boundaries without test-on-acquire or kernel keepalives) 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

SQLx/Tokio