This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-logical-replication-buffer-governance

PostgreSQL 17 Failover Slot Sync, Logical Decoding Buffers, and WAL Safeguards

Enforces PostgreSQL 17 logical replication invariants: enabling native slot failover synchronization across physical standbys, enforcing explicit logical_decoding_work_mem boundaries to govern shared buffer interactions, and mandating finite max_slot_wal_keep_size limits to eliminate catastrophic primary node disk exhaustion.

Prohibited Anti-Pattern: Deploying Unsynchronized Logical Slots with Uncapped WAL Retention and Unbounded Decoding Buffers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Sync, Logical Decoding Buffers, and WAL Safeguards - Enforces PostgreSQL 17 logical replication invariants: enabling native slot failover synchronization across physical standbys, enforcing explicit logical_decoding_work_mem boundaries to govern shared buffer interactions, and mandating finite max_slot_wal_keep_size limits to eliminate catastrophic primary node disk exhaustion.
globs: src/database/**/*.ts, src/infrastructure/**/*.ts, migrations/**/*.sql, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-buffer-governance"
---

# PostgreSQL 17 Failover Slot Sync, Logical Decoding Buffers, and WAL Safeguards

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Deploying Unsynchronized Logical Slots with Uncapped WAL Retention and Unbounded Decoding Buffers

## System Constraints
You are a Principal Database Architect and Infrastructure Engineer enforcing PostgreSQL 17 replication and buffer management standards. Mandate the use of PostgreSQL 17's native logical replication failover slots, strict bounds on WAL retention via max_slot_wal_keep_size, proper allocation of logical_decoding_work_mem against shared_buffers, and streaming configuration (streaming = 'parallel') for subscriptions to prevent replication worker deadlocks and storage-induced node crashes.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover = true` in PostgreSQL 17 when high-availability physical standbys are present.
- Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to prevent logical subscribers from consuming changes ahead of physical standbys.
- Services MUST ALWAYS enforce a finite `max_slot_wal_keep_size` (e.g., 64GB - 128GB) to ensure disconnected subscribers or abandoned slots cannot exhaust disk space on primary nodes.
- Engineers MUST tune `logical_decoding_work_mem` (defaulting to 64MB-256MB) distinct from `shared_buffers` to force early on-disk spilling of large transactions and avoid node-level OOMs during reorder buffer assembly.
- Code orchestrating subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` to stream in-progress transactions and prevent subscriber memory bloat during massive batch writes.
- Automated cleanup monitors MUST poll `pg_replication_slots.wal_status` and drop or invalidate slots reporting 'lost' or 'unreserved' states.

## Bad vs Good Implementations
### Configuring PostgreSQL 17 Logical Replication Slot with Failover and Safeguards

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a slot without failover = true causes complete data divergence and subscriber rebuilds after a physical replica promotion in PG 17. Omitting runtime WAL retention and decoding memory bounds exposes the primary cluster to total disk full crashes if subscriber processing halts.
```typescript
import { Client } from 'pg';

export async function setupReplication(client: Client, slotName: string, pubName: string): Promise<void> {
  // ANTI-PATTERN: Creates legacy logical slot without PG17 failover support
  // Lacks max_slot_wal_keep_size safeguard, risking disk exhaustion if downstream stalls.
  // Fails after primary failover because slot does not exist on promoted standby.
  await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput');`, [slotName]);
  
  await client.query(`
    CREATE PUBLICATION ${pubName} FOR ALL TABLES;
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Correctly initializes a PG 17 logical replication slot with failover => true, ensuring slot metadata synchronizes across physical replicas. Protects primary storage by setting max_slot_wal_keep_size and constrains memory via logical_decoding_work_mem.
```typescript
import { Client } from 'pg';

export interface ReplicationConfig {
  slotName: string;
  pubName: string;
  walKeepSizeMb: number;
  decodingWorkMemMb: number;
}

export async function setupPostgres17Replication(
  client: Client,
  config: ReplicationConfig
): Promise<void> {
  // Invariant 1: Enforce finite WAL retention cap to prevent primary storage outages
  await client.query(`ALTER SYSTEM SET max_slot_wal_keep_size = '${config.walKeepSizeMb}MB';`);
  
  // Invariant 2: Isolate logical decoding memory footprint from shared_buffers
  await client.query(`ALTER SYSTEM SET logical_decoding_work_mem = '${config.decodingWorkMemMb}MB';`);
  await client.query(`SELECT pg_reload_conf();`);

  // Invariant 3: Create publication targeting domain entities
  await client.query(`CREATE PUBLICATION ${config.pubName} FOR ALL TABLES;`);

  // Invariant 4: PG17 Native failover-enabled logical slot
  // Creates slot with two_phase and failover synchronization active
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => 'pgoutput',
       temporary => false,
       twophase => true,
       failover => true
     );`,
    [config.slotName]
  );
}
```

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 Sync, Logical Decoding Buffers, and WAL Safeguards

PostgreSQL 17 Failover Slot Sync, Logical Decoding Buffers, and WAL Safeguards defines an industrial-grade behavioral standard for backend engineering. Enforces PostgreSQL 17 logical replication invariants: enabling native slot failover synchronization across physical standbys, enforcing explicit logical_decoding_work_mem boundaries to govern shared buffer interactions, and mandating finite max_slot_wal_keep_size limits to eliminate catastrophic primary node disk exhaustion. 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: Deploying Unsynchronized Logical Slots with Uncapped WAL Retention and Unbounded Decoding Buffers 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 DriftDeploying Unsynchronized Logical Slots with Uncapped WAL Retention and Unbounded Decoding BuffersCritical
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 create logical replication slots with `failover = true` in PostgreSQL 17 when high-availability physical standbys are present.

Engineers MUST ALWAYS create logical replication slots with `failover = true` in PostgreSQL 17 when high-availability physical standbys are present.

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 instance to prevent logical subscribers from consuming changes ahead of physical standbys.

Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to prevent logical subscribers from consuming changes ahead of 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.
3

Services MUST ALWAYS enforce a finite `max_slot_wal_keep_size` (e.g., 64GB - 128GB) to ensure disconnected subscribers or abandoned slots cannot exhaust disk space on primary nodes.

Services MUST ALWAYS enforce a finite `max_slot_wal_keep_size` (e.g., 64GB - 128GB) to ensure disconnected subscribers or abandoned slots cannot exhaust disk space 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.
4

Engineers MUST tune `logical_decoding_work_mem` (defaulting to 64MB-256MB) distinct from `shared_buffers` to force early on-disk spilling of large transactions and avoid node-level OOMs during reorder buffer assembly.

Engineers MUST tune `logical_decoding_work_mem` (defaulting to 64MB-256MB) distinct from `shared_buffers` to force early on-disk spilling of large transactions and avoid node-level OOMs during reorder buffer assembly.

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 orchestrating subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` to stream in-progress transactions and prevent subscriber memory bloat during massive batch writes.

Code orchestrating subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` to stream in-progress transactions and prevent subscriber memory bloat during massive batch writes.

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

Automated cleanup monitors MUST poll `pg_replication_slots.wal_status` and drop or invalidate slots reporting 'lost' or 'unreserved' states.

Automated cleanup monitors MUST poll `pg_replication_slots.wal_status` and drop or invalidate slots reporting 'lost' or 'unreserved' states.

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 Sync, Logical Decoding Buffers, and WAL Safeguards critical for AI coding assistants?

Enforces PostgreSQL 17 logical replication invariants: enabling native slot failover synchronization across physical standbys, enforcing explicit logical_decoding_work_mem boundaries to govern shared buffer interactions, and mandating finite max_slot_wal_keep_size limits to eliminate catastrophic primary node disk exhaustion. 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 (Deploying Unsynchronized Logical Slots with Uncapped WAL Retention and Unbounded Decoding Buffers) 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