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

Postgres 17 Streaming I/O Optimization and Native Failover Slot Synchronization

Mandates PostgreSQL 17 native logical replication failover slot synchronization and streaming I/O engine configuration for cross-region distributed topologies. Guarantees zero data loss and sub-second cutover by strictly enforcing synchronized_standby_slots, failover-enabled logical slots, and streaming I/O buffer invariants.

Prohibited Anti-Pattern: Unsynchronized Logical Replication Slots and Unbounded I/O Inducing Data Loss During Standby Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Streaming I/O Optimization and Native Failover Slot Synchronization - Mandates PostgreSQL 17 native logical replication failover slot synchronization and streaming I/O engine configuration for cross-region distributed topologies. Guarantees zero data loss and sub-second cutover by strictly enforcing synchronized_standby_slots, failover-enabled logical slots, and streaming I/O buffer invariants.
globs: src/**/*.ts, infra/**/*.tf, database/**/*.sql, config/postgres/**/*.conf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-streaming-io-failover-slot-sync"
---

# Postgres 17 Streaming I/O Optimization and Native Failover Slot Synchronization

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Replication Slots and Unbounded I/O Inducing Data Loss During Standby Promotion

## System Constraints
You are a Principal Software Architect enforcing PostgreSQL 17 enterprise high-availability and I/O engine invariants. Mandate native failover slot synchronization and streaming I/O parameters across all schema migrations, connection managers, and orchestration code. Ensure that logical replication slots cannot lag or disappear across physical promotions, preventing silent data corruption and replay gaps.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with 'failover => true' in PostgreSQL 17+ environments.
- Engineers MUST ALWAYS configure 'synchronized_standby_slots' on the primary cluster to block WAL recycling until physical standbys have confirmed persistence.
- Standby database configurations MUST enable 'sync_replication_slots = on' to keep slot metadata continuously aligned with the primary without third-party daemons.
- Engineers MUST NOT promote a physical standby without verifying that target logical slots reflect 'sync_state = synced' in 'pg_replication_slots'.
- Infrastructure automation MUST configure PostgreSQL 17 streaming I/O parameters ('io_combine_limit' and 'maintenance_io_concurrency') to prevent I/O stalls during replication catch-up.
- Failover orchestration code MUST abort promotion if the delta between physical standby replay LSN and logical slot confirmed_flush_lsn is non-zero.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Slot Creation & Failover Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Postgres 17, creating a replication slot without 'failover => true' excludes it from synchronization to physical standbys. If the standby is promoted, the slot does not exist on the new primary, causing logical downstream consumers to fail or miss committed transactions.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client, slotName: string) {
  // ANTI-PATTERN: Creates legacy logical slot without PG17 failover enablement.
  // Standby promotion will drop this slot or cause silent data gaps on cross-region failover.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}

export async function promoteStandby(client: Client) {
  // ANTI-PATTERN: Promoting without checking logical slot sync state causes split-brain/data loss.
  await client.query('SELECT pg_promote();');
}
```

#### Production Standard (Correct)
> **Standard**: Uses PostgreSQL 17's native 'failover => true' parameter and strictly inspects 'sync_state = synced' and 'conflicting = false' prior to issuing 'pg_promote()', eliminating replication gaps and missing slots upon promotion.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client, slotName: string): Promise<void> {
  // INVARIANT: In PG17, explicitly enable failover flag to sync slot across physical standbys
  await client.query(
    `SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => 'pgoutput',
      temporary => false,
      two_phase => true,
      failover => true
    );`,
    [slotName]
  );
}

export async function promoteStandbySafely(client: Client, criticalSlotNames: string[]): Promise<void> {
  // INVARIANT: Verify all failover slots are fully synced before allowing promotion
  const { rows } = await client.query<{
    slot_name: string;
    sync_state: string;
    conflicting: boolean;
  }>(
    `SELECT slot_name, sync_state, conflicting
     FROM pg_replication_slots
     WHERE slot_name = ANY($1);`,
    [criticalSlotNames]
  );

  for (const slot of rows) {
    if (slot.sync_state !== 'synced' || slot.conflicting) {
      throw new Error(
        `Promotion halted: Slot ${slot.slot_name} is not synchronized (sync_state=${slot.sync_state}, conflicting=${slot.conflicting})`
      );
    }
  }

  await client.query('SELECT pg_promote(wait => true, wait_seconds => 60);');
}
```

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 Optimization and Native Failover Slot Synchronization

Postgres 17 Streaming I/O Optimization and Native Failover Slot Synchronization defines an industrial-grade behavioral standard for backend engineering. Mandates PostgreSQL 17 native logical replication failover slot synchronization and streaming I/O engine configuration for cross-region distributed topologies. Guarantees zero data loss and sub-second cutover by strictly enforcing synchronized_standby_slots, failover-enabled logical slots, and streaming I/O buffer invariants. 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 Replication Slots and Unbounded I/O Inducing Data Loss During Standby Promotion 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 Replication Slots and Unbounded I/O Inducing Data Loss During Standby PromotionCritical
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 with 'failover => true' in PostgreSQL 17+ environments.

Engineers MUST ALWAYS provision logical replication slots with 'failover => true' in PostgreSQL 17+ environments.

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 configure 'synchronized_standby_slots' on the primary cluster to block WAL recycling until physical standbys have confirmed persistence.

Engineers MUST ALWAYS configure 'synchronized_standby_slots' on the primary cluster to block WAL recycling until physical standbys have confirmed persistence.

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 database configurations MUST enable 'sync_replication_slots = on' to keep slot metadata continuously aligned with the primary without third-party daemons.

Standby database configurations MUST enable 'sync_replication_slots = on' to keep slot metadata continuously aligned with the primary without third-party daemons.

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 NOT promote a physical standby without verifying that target logical slots reflect 'sync_state = synced' in 'pg_replication_slots'.

Engineers MUST NOT promote a physical standby without verifying that target logical slots reflect 'sync_state = synced' in 'pg_replication_slots'.

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

Infrastructure automation MUST configure PostgreSQL 17 streaming I/O parameters ('io_combine_limit' and 'maintenance_io_concurrency') to prevent I/O stalls during replication catch-up.

Infrastructure automation MUST configure PostgreSQL 17 streaming I/O parameters ('io_combine_limit' and 'maintenance_io_concurrency') to prevent I/O stalls during replication catch-up.

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

Failover orchestration code MUST abort promotion if the delta between physical standby replay LSN and logical slot confirmed_flush_lsn is non-zero.

Failover orchestration code MUST abort promotion if the delta between physical standby replay LSN and logical slot confirmed_flush_lsn is non-zero.

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 Optimization and Native Failover Slot Synchronization critical for AI coding assistants?

Mandates PostgreSQL 17 native logical replication failover slot synchronization and streaming I/O engine configuration for cross-region distributed topologies. Guarantees zero data loss and sub-second cutover by strictly enforcing synchronized_standby_slots, failover-enabled logical slots, and streaming I/O buffer invariants. 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 Replication Slots and Unbounded I/O Inducing Data Loss During Standby Promotion) 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