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

PostgreSQL 17 Managed Logical Failover Slots & Streaming I/O Synchronization

Enforces deterministic zero-data-loss failover synchronization across read replicas using PostgreSQL 17 native failover slots (`failover = true`) bound to `synchronized_standby_slots`. Simultaneously optimizes the replication ingestion pipeline via Postgres 17 direct block streaming I/O and vectorized read prefetching (`io_combine_limit`), preventing worker stall during high-throughput WAL replay.

Prohibited Anti-Pattern: Creating Unmanaged Logical Replication Slots Without Standby Synchronization and Default I/O Concurrency

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Managed Logical Failover Slots & Streaming I/O Synchronization - Enforces deterministic zero-data-loss failover synchronization across read replicas using PostgreSQL 17 native failover slots (`failover = true`) bound to `synchronized_standby_slots`. Simultaneously optimizes the replication ingestion pipeline via Postgres 17 direct block streaming I/O and vectorized read prefetching (`io_combine_limit`), preventing worker stall during high-throughput WAL replay.
globs: src/database/**/*.ts, src/infra/postgres/**/*.ts, migrations/**/*.sql, deploy/postgres/**/*.conf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-failover-slots-streaming-io-standard"
---

# PostgreSQL 17 Managed Logical Failover Slots & Streaming I/O Synchronization

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Unmanaged Logical Replication Slots Without Standby Synchronization and Default I/O Concurrency

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing PostgreSQL 17 zero-data-loss logical replication and streaming I/O optimization. You MUST ensure all logical replication slots are provisioned with `failover => true`, synchronized explicitly across physical standby boundaries via `synchronized_standby_slots`, and backed by PostgreSQL 17 direct block vectorized streaming I/O (`io_combine_limit`). Reject legacy Postgres 15/16 slot provisioning patterns and unmonitored replication lag pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17+ to ensure slot state synchronization to physical standbys.
- Engineers MUST set `synchronized_standby_slots` on primary clusters to include all participating physical replica replication slot names, preventing the primary from advancing WAL past standbys.
- Engineers MUST enable `sync_replication_slots = true` in `postgresql.conf` on physical standbys or schedule deterministic executions of `pg_sync_replication_slots()`.
- Engineers MUST configure PostgreSQL 17 streaming I/O parameters (`io_combine_limit >= 16` for NVMe/SAN, non-zero `effective_io_concurrency`) to maximize vectorized WAL sequential prefetch and prevent replay bottlenecks.
- Engineers MUST NOT allow logical replication consumers to connect without validating `pg_replication_slots.failover = true` and `pg_replication_slots.synced = false` on primary nodes.
- Services MUST monitor replication lag using `pg_stat_replication` alongside `pg_replication_slots` to detect stalled `confirmed_flush_lsn` before disk saturation occurs.

## Bad vs Good Implementations
### PostgreSQL 17 Managed Slot Provisioning and Connection Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating logical slots without specifying `failover => true` prevents the slot metadata from syncing to physical replicas. When failover occurs, the new primary will lack this slot, leading to subscriber failure or data duplication. Furthermore, missing synchronization barriers cause WAL truncation on the primary before standby acknowledgment.
```typescript
import { Client } from 'pg';

// ANTI-PATTERN: Creates legacy logical slot without failover parameter or standby sync;
// leaves I/O settings at defaults, risking lost slots on promotion and worker starvation.
export async function setupLogicalReplication(client: Client, slotName: string, pubName: string): Promise<void> {
  // Obsolete syntax without failover flag (defaulting to failover = false in PG17)
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      $1,
      'pgoutput',
      false
    );
  `, [slotName]);

  await client.query(`
    CREATE PUBLICATION ${pubName} FOR ALL TABLES;
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly utilizes PostgreSQL 17's `failover => true` and `two_phase => true` parameters in `pg_create_logical_replication_slot`. Guarantees logical slots are synchronized with physical standbys (preventing data loss upon primary switchover), enforces transactional creation, and establishes optimal block prefetching limits.
```typescript
import { Client } from 'pg';

export interface ReplicationSlotConfig {
  slotName: string;
  publicationName: string;
  standbySlotName: string;
  ioCombineLimitBlocks: number; // PG17 streaming I/O vectorized batch size
}

// PRODUCTION-GRADE: PG17 managed failover slot with physical standby synchronization barrier
export async function setupPg17FailoverReplication(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  await client.query('BEGIN;');

  try {
    // 1. Tune Postgres 17 streaming I/O for high-throughput replication streaming
    await client.query(`
      SET LOCAL io_combine_limit = '${config.ioCombineLimitBlocks}';
      SET LOCAL maintenance_io_concurrency = 16;
    `);

    // 2. Idempotently create publication
    await client.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = '${config.publicationName}') THEN
          CREATE PUBLICATION ${config.publicationName} FOR ALL TABLES;
        END IF;
      END $$;
    `);

    // 3. Provision PG17 logical slot with native failover capability enabled
    await client.query(`
      SELECT pg_create_logical_replication_slot(
        slot_name => $1,
        plugin => 'pgoutput',
        temporary => false,
        two_phase => true,
        failover => true
      )
      WHERE NOT EXISTS (
        SELECT 1 FROM pg_replication_slots WHERE slot_name = $1
      );
    `, [config.slotName]);

    // 4. Assert slot is validated with failover flag active
    const { rows } = await client.query(`
      SELECT slot_name, plugin, failover, synced 
      FROM pg_replication_slots 
      WHERE slot_name = $1;
    `, [config.slotName]);

    if (!rows[0] || rows[0].failover !== true) {
      throw new Error(`Replication slot ${config.slotName} was not created with failover=true`);
    }

    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: PostgreSQL 17 Managed Logical Failover Slots & Streaming I/O Synchronization

PostgreSQL 17 Managed Logical Failover Slots & Streaming I/O Synchronization defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic zero-data-loss failover synchronization across read replicas using PostgreSQL 17 native failover slots (`failover = true`) bound to `synchronized_standby_slots`. Simultaneously optimizes the replication ingestion pipeline via Postgres 17 direct block streaming I/O and vectorized read prefetching (`io_combine_limit`), preventing worker stall during high-throughput WAL replay. 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: Creating Unmanaged Logical Replication Slots Without Standby Synchronization and Default I/O Concurrency 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 DriftCreating Unmanaged Logical Replication Slots Without Standby Synchronization and Default I/O ConcurrencyCritical
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` on PostgreSQL 17+ to ensure slot state synchronization to physical standbys.

Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17+ to ensure slot state synchronization to physical standbys.

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 set `synchronized_standby_slots` on primary clusters to include all participating physical replica replication slot names, preventing the primary from advancing WAL past standbys.

Engineers MUST set `synchronized_standby_slots` on primary clusters to include all participating physical replica replication slot names, preventing the primary from advancing WAL past standbys.

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 enable `sync_replication_slots = true` in `postgresql.conf` on physical standbys or schedule deterministic executions of `pg_sync_replication_slots()`.

Engineers MUST enable `sync_replication_slots = true` in `postgresql.conf` on physical standbys or schedule deterministic executions of `pg_sync_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.
4

Engineers MUST configure PostgreSQL 17 streaming I/O parameters (`io_combine_limit >= 16` for NVMe/SAN, non-zero `effective_io_concurrency`) to maximize vectorized WAL sequential prefetch and prevent replay bottlenecks.

Engineers MUST configure PostgreSQL 17 streaming I/O parameters (`io_combine_limit >= 16` for NVMe/SAN, non-zero `effective_io_concurrency`) to maximize vectorized WAL sequential prefetch and prevent replay bottlenecks.

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 allow logical replication consumers to connect without validating `pg_replication_slots.failover = true` and `pg_replication_slots.synced = false` on primary nodes.

Engineers MUST NOT allow logical replication consumers to connect without validating `pg_replication_slots.failover = true` and `pg_replication_slots.synced = false` on primary nodes.

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 monitor replication lag using `pg_stat_replication` alongside `pg_replication_slots` to detect stalled `confirmed_flush_lsn` before disk saturation occurs.

Services MUST monitor replication lag using `pg_stat_replication` alongside `pg_replication_slots` to detect stalled `confirmed_flush_lsn` before disk saturation occurs.

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 PostgreSQL 17 Managed Logical Failover Slots & Streaming I/O Synchronization critical for AI coding assistants?

Enforces deterministic zero-data-loss failover synchronization across read replicas using PostgreSQL 17 native failover slots (`failover = true`) bound to `synchronized_standby_slots`. Simultaneously optimizes the replication ingestion pipeline via Postgres 17 direct block streaming I/O and vectorized read prefetching (`io_combine_limit`), preventing worker stall during high-throughput WAL replay. 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 (Creating Unmanaged Logical Replication Slots Without Standby Synchronization and Default I/O Concurrency) 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

PostgreSQL