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

PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Invariants

PostgreSQL 17 introduces native logical replication slot synchronization (`sync_replication_slots`) and failover-enabled logical slots (`failover = true`). Failure to configure failover slots alongside bounded `max_slot_wal_keep_size`, adequate `logical_decoding_work_mem`, and streaming transaction parameters leads to unmitigated WAL exhaustion, catastrophic failover data duplication, and buffer pool eviction under high write volume.

Prohibited Anti-Pattern: Unsynchronized Unbounded Logical Replication Slots Spilling to Disk and Exhausting WAL on Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Invariants - PostgreSQL 17 introduces native logical replication slot synchronization (`sync_replication_slots`) and failover-enabled logical slots (`failover = true`). Failure to configure failover slots alongside bounded `max_slot_wal_keep_size`, adequate `logical_decoding_work_mem`, and streaming transaction parameters leads to unmitigated WAL exhaustion, catastrophic failover data duplication, and buffer pool eviction under high write volume.
globs: src/database/**/*.ts, src/infrastructure/**/*.ts, migrations/**/*.sql, infra/postgres/**/*.conf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-replication-failover-buffers-standard"
---

# PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Unbounded Logical Replication Slots Spilling to Disk and Exhausting WAL on Failover

## System Constraints
You are a Principal Database Reliability Engineer and Distributed Systems Architect specializing in PostgreSQL 17 internals. You enforce zero-data-loss failover for logical replication, deterministic slot synchronization, and memory-safe streaming decoding architectures. Reject any configuration or automation script that allocates unmonitored logical replication slots without failover tracking, omits WAL bounds, or violates PostgreSQL memory buffer invariants.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` in PostgreSQL 17 when running High Availability (HA) physical standby topologies.
- Engineers MUST set `sync_replication_slots = true` on physical standby instances and configure `synchronized_standby_slots` on the primary to enforce write ordering before transactions commit.
- Services MUST define `max_slot_wal_keep_size` (e.g., 64GB-128GB) to guarantee that lagging or disconnected logical consumers cannot induce cascade WAL accumulation and crash the primary via storage exhaustion.
- Engineers MUST tune `logical_decoding_work_mem` independently from `shared_buffers`; decode workers must not starve kernel page caches or trigger excessive local disk spill during large multi-statement transactions.
- Subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` for high-throughput publishers to bypass replaying gigantic transactions purely in memory at commit time.
- Database orchestration scripts MUST query `pg_replication_slots.invalidated` and `pg_replication_slots.sync_state` to preemptively sever dead slots and sound PagerDuty alerts prior to catalog starvation.
- Components NEVER execute raw DDL transformations across logically replicated tables without synchronized identity columns (`REPLICA IDENTITY FULL` or validated primary keys) and deterministic sequencing.

## Bad vs Good Implementations
### PostgreSQL 17 Failover-Ready Logical Slot Provisioning & Safety Bounds

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates a legacy unflagged logical slot without failover preservation (`failover => true`), omits WAL retention bounds (`max_slot_wal_keep_size`), and does not leverage PG 17 streaming options (`streaming = parallel`), which risks standby disconnection, OOM during huge transactions, and disk exhaustion.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client, slotName: string, pubName: string) {
  // ANTI-PATTERN: Pre-PG17 pattern without failover flag, unbounded WAL retention, 
  // and no parallel streaming decoding, risking standby loss and disk filling.
  await client.query(`CREATE PUBLICATION ${pubName} FOR ALL TABLES;`);
  await client.query(`SELECT pg_create_logical_replication_slot('${slotName}', 'pgoutput');`);
  await client.query(`
    CREATE SUBSCRIPTION ${slotName}_sub
    CONNECTION 'host=primary dbname=app user=rep_user'
    PUBLICATION ${pubName};
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to PostgreSQL 17 HA architecture: sets failover => true in pg_create_logical_replication_slot, bounds max_slot_wal_keep_size to avoid out-of-disk crashes, and uses streaming = 'parallel' to stream active transactions directly into apply workers without thrashing memory buffers.
```typescript
import { Client } from 'pg';

interface ReplicationSlotOptions {
  slotName: string;
  publicationName: string;
  maxSlotWalKeepMb: number;
  connectionString: string;
}

export async function setupPostgres17LogicalReplication(
  client: Client,
  options: ReplicationSlotOptions
): Promise<void> {
  const { slotName, publicationName, maxSlotWalKeepMb, connectionString } = options;

  // INVARIANT 1: Apply global WAL protection boundary against slot lag disaster
  await client.query(
    `ALTER SYSTEM SET max_slot_wal_keep_size = '${Math.max(1024, maxSlotWalKeepMb)}MB';`
  );
  await client.query(`SELECT pg_reload_conf();`);

  // INVARIANT 2: Create publication with explicit publishing constraints
  await client.query(
    `CREATE PUBLICATION ${publicationName} FOR ALL TABLES WITH (publish = 'insert,update,delete,truncate');`
  );

  // INVARIANT 3: Postgres 17 native failover-enabled logical slot
  // Allows physical standby nodes (with sync_replication_slots = on) to sync this slot
  await client.query(
    `SELECT pg_create_logical_replication_slot(
      $1,
      'pgoutput',
      false,
      'extended',
      true
    );`,
    [slotName]
  );

  // INVARIANT 4: Enable parallel streaming decode on subscription side to protect backend buffers
  await client.query(
    `CREATE SUBSCRIPTION ${slotName}_sub
     CONNECTION '${connectionString}'
     PUBLICATION ${publicationName}
     WITH (
       copy_data = true,
       create_slot = false,
       slot_name = '${slotName}',
       streaming = 'parallel',
       failover = true
     );`
  );
}
```

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 Failover Slot Synchronization, Streaming Decoding, and Memory Invariants

PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Invariants defines an industrial-grade behavioral standard for backend engineering. PostgreSQL 17 introduces native logical replication slot synchronization (`sync_replication_slots`) and failover-enabled logical slots (`failover = true`). Failure to configure failover slots alongside bounded `max_slot_wal_keep_size`, adequate `logical_decoding_work_mem`, and streaming transaction parameters leads to unmitigated WAL exhaustion, catastrophic failover data duplication, and buffer pool eviction under high write volume. 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 Unbounded Logical Replication Slots Spilling to Disk and Exhausting WAL 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 Unbounded Logical Replication Slots Spilling to Disk and Exhausting WAL 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 with `failover => true` in PostgreSQL 17 when running High Availability (HA) physical standby topologies.

Engineers MUST ALWAYS provision logical replication slots with `failover => true` in PostgreSQL 17 when running High Availability (HA) physical standby 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 set `sync_replication_slots = true` on physical standby instances and configure `synchronized_standby_slots` on the primary to enforce write ordering before transactions commit.

Engineers MUST set `sync_replication_slots = true` on physical standby instances and configure `synchronized_standby_slots` on the primary to enforce write ordering before transactions commit.

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

Services MUST define `max_slot_wal_keep_size` (e.g., 64GB-128GB) to guarantee that lagging or disconnected logical consumers cannot induce cascade WAL accumulation and crash the primary via storage exhaustion.

Services MUST define `max_slot_wal_keep_size` (e.g., 64GB-128GB) to guarantee that lagging or disconnected logical consumers cannot induce cascade WAL accumulation and crash the primary via storage exhaustion.

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 tune `logical_decoding_work_mem` independently from `shared_buffers`

Engineers MUST tune `logical_decoding_work_mem` independently from `shared_buffers`; decode workers must not starve kernel page caches or trigger excessive local disk spill during large multi-statement transactions.

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

Subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` for high-throughput publishers to bypass replaying gigantic transactions purely in memory at commit time.

Subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` for high-throughput publishers to bypass replaying gigantic transactions purely in memory at commit time.

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

Database orchestration scripts MUST query `pg_replication_slots.invalidated` and `pg_replication_slots.sync_state` to preemptively sever dead slots and sound PagerDuty alerts prior to catalog starvation.

Database orchestration scripts MUST query `pg_replication_slots.invalidated` and `pg_replication_slots.sync_state` to preemptively sever dead slots and sound PagerDuty alerts prior to catalog starvation.

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.
7

Components NEVER execute raw DDL transformations across logically replicated tables without synchronized identity columns (`REPLICA IDENTITY FULL` or validated primary keys) and deterministic sequencing.

Components NEVER execute raw DDL transformations across logically replicated tables without synchronized identity columns (`REPLICA IDENTITY FULL` or validated primary keys) and deterministic sequencing.

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 Failover Slot Synchronization, Streaming Decoding, and Memory Invariants critical for AI coding assistants?

PostgreSQL 17 introduces native logical replication slot synchronization (`sync_replication_slots`) and failover-enabled logical slots (`failover = true`). Failure to configure failover slots alongside bounded `max_slot_wal_keep_size`, adequate `logical_decoding_work_mem`, and streaming transaction parameters leads to unmitigated WAL exhaustion, catastrophic failover data duplication, and buffer pool eviction under high write volume. 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 Unbounded Logical Replication Slots Spilling to Disk and Exhausting WAL 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

PostgreSQL