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

PostgreSQL 17 Logical Failover Slots, Decoding Buffers, and Memory Invariants

Enforces strict PostgreSQL 17 logical replication configuration invariants, requiring synchronized failover replication slots across physical standby nodes and bounded WAL retention limits. Prevents primary crash cycles from uncontrolled disk exhaustion and WAL bloat by enforcing `max_slot_wal_keep_size`, `logical_decoding_work_mem` ceilings, and PG17 `failover = true` slot flags.

Prohibited Anti-Pattern: Unsynchronized Unbounded Logical Replication Slots Causing Primary Disk Exhaustion and Standby Dropouts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Failover Slots, Decoding Buffers, and Memory Invariants - Enforces strict PostgreSQL 17 logical replication configuration invariants, requiring synchronized failover replication slots across physical standby nodes and bounded WAL retention limits. Prevents primary crash cycles from uncontrolled disk exhaustion and WAL bloat by enforcing `max_slot_wal_keep_size`, `logical_decoding_work_mem` ceilings, and PG17 `failover = true` slot flags.
globs: src/db/**/*.ts, src/infra/**/*.ts, migrations/**/*.sql, docker/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-replication-failover-buffers"
---

# PostgreSQL 17 Logical Failover Slots, Decoding Buffers, and Memory Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Unbounded Logical Replication Slots Causing Primary Disk Exhaustion and Standby Dropouts

## System Constraints
You are a Principal Database Reliability Engineer enforcing PostgreSQL 17 Logical Replication and Memory Buffer invariants. You must prevent replication slot desynchronization on physical failover, unconstrained WAL accumulation via slots, and improper memory buffer allocation during decoding operations. Mandate explicit PG17 failover slot settings, strict WAL caps, streaming decoding modes, and aligned shared_buffers allocation.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` in PostgreSQL 17 HA topologies to enable physical standby slot synchronization via `sync_replication_slots`.
- Engineers MUST ALWAYS configure `max_slot_wal_keep_size` at the database or cluster level to prevent runaway WAL generation from driving storage volume exhaustion upon downstream consumer lag.
- Services MUST enable parallel or streaming logical transaction decoding (`streaming => 'parallel'`) for high-throughput publications rather than spooling complete transactions into memory buffers.
- Code SHOULD explicitly bind `logical_decoding_work_mem` to prevent memory thrashing and excessive disk serialization during large logical decoding tasks.
- Components NEVER drop or recreate replication slots without validating `pg_replication_slots.sync_state` and verifying consumer confirmed flush LSNs.

## Bad vs Good Implementations
### Configuring PostgreSQL 17 Resilient Logical Replication Slot

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates a legacy logical slot without `failover => true` on PostgreSQL 17, meaning physical standby nodes cannot track this slot. If the primary fails over, the new primary will lack this slot and replication permanently halts. Furthermore, no WAL limits or memory decoding streams are guarded.
```typescript
import { Client } from 'pg';

export async function setupConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Anti-Pattern: Missing failover parameter (PG 17), unbound WAL retention risk,
  // and standard non-streamed full transaction spooling.
  await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput');`, [slotName]);
  
  await client.query(`
    CREATE SUBSCRIPTION orders_sub
    CONNECTION 'host=primary dbname=app user=repuser'
    PUBLICATION orders_pub
    WITH (copy_data = false, create_slot = false, slot_name = '${slotName}');
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to PostgreSQL 17 standards: leverages native failover replication slots (`failover => true`) compatible with `sync_replication_slots`, caps unconsumed WAL spooling via `max_slot_wal_keep_size`, and enables parallel transaction streaming decoding to avoid exhausting `logical_decoding_work_mem`.
```typescript
import { Client } from 'pg';

export async function setupConsumerSlot(client: Client, slotName: string): Promise<void> {
  // PG17 Invariant: Enable failover slot synchronization and bound WAL retention
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => 'pgoutput',
       temporary => false,
       twophase => true,
       failover => true
     );`,
    [slotName]
  );

  // Enforce WAL capacity protection on the replication slot (e.g., 64GB max WAL keep)
  await client.query(`ALTER SYSTEM SET max_slot_wal_keep_size = '64GB';`);
  await client.query(`SELECT pg_reload_conf();`);

  // Configure subscription with streaming = 'parallel' and synchronized failover
  await client.query(`
    CREATE SUBSCRIPTION orders_sub
    CONNECTION 'host=primary dbname=app user=repuser'
    PUBLICATION orders_pub
    WITH (
      copy_data = false,
      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 Logical Failover Slots, Decoding Buffers, and Memory Invariants

PostgreSQL 17 Logical Failover Slots, Decoding Buffers, and Memory Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict PostgreSQL 17 logical replication configuration invariants, requiring synchronized failover replication slots across physical standby nodes and bounded WAL retention limits. Prevents primary crash cycles from uncontrolled disk exhaustion and WAL bloat by enforcing `max_slot_wal_keep_size`, `logical_decoding_work_mem` ceilings, and PG17 `failover = true` slot flags. 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 Causing Primary Disk Exhaustion and Standby Dropouts 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 Causing Primary Disk Exhaustion and Standby DropoutsCritical
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 HA topologies to enable physical standby slot synchronization via `sync_replication_slots`.

Engineers MUST ALWAYS provision logical replication slots with `failover => true` in PostgreSQL 17 HA topologies to enable physical standby slot synchronization via `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.
2

Engineers MUST ALWAYS configure `max_slot_wal_keep_size` at the database or cluster level to prevent runaway WAL generation from driving storage volume exhaustion upon downstream consumer lag.

Engineers MUST ALWAYS configure `max_slot_wal_keep_size` at the database or cluster level to prevent runaway WAL generation from driving storage volume exhaustion upon downstream consumer lag.

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 enable parallel or streaming logical transaction decoding (`streaming => 'parallel'`) for high-throughput publications rather than spooling complete transactions into memory buffers.

Services MUST enable parallel or streaming logical transaction decoding (`streaming => 'parallel'`) for high-throughput publications rather than spooling complete transactions into memory buffers.

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

Code SHOULD explicitly bind `logical_decoding_work_mem` to prevent memory thrashing and excessive disk serialization during large logical decoding tasks.

Code SHOULD explicitly bind `logical_decoding_work_mem` to prevent memory thrashing and excessive disk serialization during large logical decoding tasks.

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

Components NEVER drop or recreate replication slots without validating `pg_replication_slots.sync_state` and verifying consumer confirmed flush LSNs.

Components NEVER drop or recreate replication slots without validating `pg_replication_slots.sync_state` and verifying consumer confirmed flush LSNs.

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 Logical Failover Slots, Decoding Buffers, and Memory Invariants critical for AI coding assistants?

Enforces strict PostgreSQL 17 logical replication configuration invariants, requiring synchronized failover replication slots across physical standby nodes and bounded WAL retention limits. Prevents primary crash cycles from uncontrolled disk exhaustion and WAL bloat by enforcing `max_slot_wal_keep_size`, `logical_decoding_work_mem` ceilings, and PG17 `failover = true` slot flags. 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 Causing Primary Disk Exhaustion and Standby Dropouts) 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