This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-streaming-io-failover-slot-invariants

Postgres 17 Streaming I/O & Failover Slot Invariants

Enforces deterministic replication slot failover synchronization and vectorized streaming I/O bounds in PostgreSQL 17 topologies. Prevents unbounded WAL retention spirals, logical subscriber invalidation across node promotions, and unthrottled streaming read/write saturation during zero-downtime cluster transitions.

Prohibited Anti-Pattern: Unsynchronized Logical Slots and Unbounded WAL Retention Leading to Cascading Cluster Exhaustion on Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Streaming I/O & Failover Slot Invariants - Enforces deterministic replication slot failover synchronization and vectorized streaming I/O bounds in PostgreSQL 17 topologies. Prevents unbounded WAL retention spirals, logical subscriber invalidation across node promotions, and unthrottled streaming read/write saturation during zero-downtime cluster transitions.
globs: src/db/**/*.ts, src/infra/**/*.ts, src/services/cdc/**/*.ts, migrations/**/*.ts, scripts/db/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-streaming-io-failover-slot-invariants"
---

# Postgres 17 Streaming I/O & Failover Slot Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots and Unbounded WAL Retention Leading to Cascading Cluster Exhaustion on Failover

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 streaming I/O controls and failover replication slot invariants. All database initialization, connection pooling, and change data capture (CDC) slot management logic must explicitly define failover synchronization, bound streaming WAL consumption, and prevent disk exhaustion cascades across node promotions.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 with failover => true enabled when operating in high-availability topologies.
- Engineers MUST configure max_slot_wal_keep_size to a deterministic threshold (e.g., 64GB) to guarantee that lagging or disconnected subscribers cannot exhaust primary filesystem storage.
- Standby replicas MUST have sync_replication_slots enabled and maintain synchronized slot metadata from the primary via pg_sync_replication_slots() or native background workers.
- Database connection pooling configurations MUST specify target_session_attrs=read-write for write transactions and utilize deterministic read streaming batch bounds to accommodate PG17's vectorized I/O subsystem.
- Engineers MUST NOT execute ad-hoc replication slot creations without explicit WAL retain limits or failover synchronization guarantees.
- Services MUST query pg_replication_slots for active, failover, and synced statuses before initiating downstream consumer streams after a cluster topology transition.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Slot Initialization and Streaming Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot in PostgreSQL 17 without failover => true causes the slot to be lost when the standby replica is promoted during failover. Omitting max_slot_wal_keep_size allows disconnected downstream consumers to cause infinite WAL accumulation, crashing the primary node via disk exhaustion.
```typescript
import { Client } from 'pg';

export async function setupConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Missing failover parameter (PG17), no WAL retention bounds,
  // and unconstrained streaming consumption leading to WAL bloat and slot dropping on failover.
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      $1,
      'pgoutput'
    );
  `, [slotName]);

  console.log(`Replication slot ${slotName} created without failover sync.`);
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to PostgreSQL 17 failover invariants by setting failover => true and two_phase => true. Explicitly bounds max_slot_wal_keep_size to prevent runaway WAL bloat, and verifies slot registration metadata in pg_replication_slots before acknowledging pipeline provisioning.
```typescript
import { Client } from 'pg';

interface ReplicationSlotConfig {
  slotName: string;
  outputPlugin?: string;
  maxWalKeepSizeMb: number;
  enableFailover: boolean;
}

export async function setupConsumerSlot(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  const { slotName, outputPlugin = 'pgoutput', maxWalKeepSizeMb, enableFailover } = config;

  await client.query('BEGIN');
  try {
    // Bound WAL retention to prevent disk exhaustion cascades
    await client.query(
      `ALTER SYSTEM SET max_slot_wal_keep_size = $1;`,
      [`${maxWalKeepSizeMb}MB`]
    );
    await client.query('SELECT pg_reload_conf();');

    // PG17-native failover-enabled logical slot declaration
    await client.query(`
      SELECT pg_create_logical_replication_slot(
        slot_name => $1,
        plugin => $2,
        temporary => false,
        two_phase => true,
        failover => $3
      );
    `, [slotName, outputPlugin, enableFailover]);

    // Verify slot metadata and synchronization capability
    const result = await client.query(`
      SELECT slot_name, plugin, failover, synced, wal_status
      FROM pg_replication_slots
      WHERE slot_name = $1;
    `, [slotName]);

    const slot = result.rows[0];
    if (!slot || (enableFailover && !slot.failover)) {
      throw new Error(`Slot ${slotName} creation invariant violation: failover sync not active.`);
    }

    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  }
}
```

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: Postgres 17 Streaming I/O & Failover Slot Invariants

Postgres 17 Streaming I/O & Failover Slot Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic replication slot failover synchronization and vectorized streaming I/O bounds in PostgreSQL 17 topologies. Prevents unbounded WAL retention spirals, logical subscriber invalidation across node promotions, and unthrottled streaming read/write saturation during zero-downtime cluster transitions. 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: Unsynchronized Logical Slots and Unbounded WAL Retention Leading to Cascading Cluster Exhaustion on Failover 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 DriftUnsynchronized Logical Slots and Unbounded WAL Retention Leading to Cascading Cluster Exhaustion on FailoverCritical
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 provision logical replication slots in PostgreSQL 17 with failover => true enabled when operating in high-availability topologies.

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 with failover => true enabled when operating in high-availability topologies.

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 configure max_slot_wal_keep_size to a deterministic threshold (e.g., 64GB) to guarantee that lagging or disconnected subscribers cannot exhaust primary filesystem storage.

Engineers MUST configure max_slot_wal_keep_size to a deterministic threshold (e.g., 64GB) to guarantee that lagging or disconnected subscribers cannot exhaust primary filesystem storage.

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

Standby replicas MUST have sync_replication_slots enabled and maintain synchronized slot metadata from the primary via pg_sync_replication_slots() or native background workers.

Standby replicas MUST have sync_replication_slots enabled and maintain synchronized slot metadata from the primary via pg_sync_replication_slots() or native background workers.

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

Database connection pooling configurations MUST specify target_session_attrs=read-write for write transactions and utilize deterministic read streaming batch bounds to accommodate PG17's vectorized I/O subsystem.

Database connection pooling configurations MUST specify target_session_attrs=read-write for write transactions and utilize deterministic read streaming batch bounds to accommodate PG17's vectorized I/O subsystem.

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 NOT execute ad-hoc replication slot creations without explicit WAL retain limits or failover synchronization guarantees.

Engineers MUST NOT execute ad-hoc replication slot creations without explicit WAL retain limits or failover synchronization guarantees.

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

Services MUST query pg_replication_slots for active, failover, and synced statuses before initiating downstream consumer streams after a cluster topology transition.

Services MUST query pg_replication_slots for active, failover, and synced statuses before initiating downstream consumer streams after a cluster topology transition.

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 Postgres 17 Streaming I/O & Failover Slot Invariants critical for AI coding assistants?

Enforces deterministic replication slot failover synchronization and vectorized streaming I/O bounds in PostgreSQL 17 topologies. Prevents unbounded WAL retention spirals, logical subscriber invalidation across node promotions, and unthrottled streaming read/write saturation during zero-downtime cluster transitions. 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 (Unsynchronized Logical Slots and Unbounded WAL Retention Leading to Cascading Cluster Exhaustion on Failover) 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

Postgres