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

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

Enforces strict configuration and programmatic management of PostgreSQL 17 logical failover slots, standby synchronization, and memory-bounded decoding buffers. Prevents silent replication breakage during physical node failover, disk exhaustion via runaway WAL retention, and OOM kills by mandating synchronized slots, explicit WAL limits, and bounded logical decoding memory.

Prohibited Anti-Pattern: Creating Unsynchronized Logical Replication Slots Without Failover Support or WAL Retention Caps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants - Enforces strict configuration and programmatic management of PostgreSQL 17 logical failover slots, standby synchronization, and memory-bounded decoding buffers. Prevents silent replication breakage during physical node failover, disk exhaustion via runaway WAL retention, and OOM kills by mandating synchronized slots, explicit WAL limits, and bounded logical decoding memory.
globs: src/**/*.ts, src/db/**/*.ts, src/replication/**/*.ts, migrations/**/*.sql, infra/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-replication-failover-slots-buffer-guardrail"
---

# PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Unsynchronized Logical Replication Slots Without Failover Support or WAL Retention Caps

## System Constraints
You are a Principal Database Architect and Infrastructure Engineer enforcing PostgreSQL 17 logical replication and memory buffer invariants. In PostgreSQL 17, logical replication slots support zero-loss physical failover through the `failover` parameter and `sync_replication_slots` standby syncing. You must reject any slot creation or connection management code that omits PG17 failover parameters, fails to guard against unbounded WAL accumulation with `max_slot_wal_keep_size`, or misallocates `logical_decoding_work_mem` relative to `shared_buffers`.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17+ primaries to ensure persistence across HA failovers.
- Engineers MUST ALWAYS verify that `max_slot_wal_keep_size` is configured to a non-negative finite boundary (never '-1' or unset) to prevent cascading disk out-of-space crashes from lagging subscribers.
- Engineers MUST NOT allow logical replication clients to bypass validation of `standby_slot_names` on the primary and `sync_replication_slots = on` on standby replicas.
- Services MUST bound `logical_decoding_work_mem` (defaulting to 64MB-256MB) per decoding worker to prevent backend processes from consuming OS memory outside of `shared_buffers`.
- Components NEVER execute raw `pg_create_logical_replication_slot` invocations without passing the 5th argument (`failover := true`) or executing `ALTER REPLICATION SLOT ... (failover true)` on existing PostgreSQL 17 slots.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Slot Initialization & Guardrail Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy slot creation without `failover = true` causes replication to permanently stall or lose sync upon physical node failover in PostgreSQL 17. Leaving WAL retention unverified risks total cluster outage due to disk saturation.
```typescript
import { Client } from 'pg';

export async function setupLogicalSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Uses legacy 2-arg signature without PG17 failover flag.
  // If the primary fails over, this slot does not exist on the promoted standby,
  // causing downstream CDC/ETL pipelines to crash or re-read duplicated data.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
  // ANTI-PATTERN: No validation of max_slot_wal_keep_size;
  // an offline subscriber will retain WAL indefinitely until the disk fills up.
}
```

#### Production Standard (Correct)
> **Standard**: Ensures server runtime is PostgreSQL 17+, enforces safety limits on WAL retention, and utilizes the PG17 `failover => true` slot definition so standby instances track LSN progress via `sync_replication_slots`.
```typescript
import { Client } from 'pg';

interface ReplicationSlotOptions {
  slotName: string;
  plugin?: string;
  maxWalRetainMb?: number;
}

export async function setupLogicalSlot(
  client: Client,
  options: ReplicationSlotOptions
): Promise<void> {
  const { slotName, plugin = 'pgoutput', maxWalRetainMb = 32768 } = options;

  // 1. Verify PostgreSQL version is >= 17
  const versionRes = await client.query('SHOW server_version_num;');
  const versionNum = parseInt(versionRes.rows[0].server_version_num, 10);
  if (versionNum < 170000) {
    throw new Error(`PostgreSQL 170000+ required for failover slots. Detected: ${versionNum}`);
  }

  // 2. Validate finite max_slot_wal_keep_size to prevent disk exhaustion
  const walRes = await client.query('SHOW max_slot_wal_keep_size;');
  const walSetting = walRes.rows[0].max_slot_wal_keep_size;
  if (walSetting === '-1') {
    throw new Error('Unsafe cluster configuration: max_slot_wal_keep_size must not be -1.');
  }

  // 3. Create logical replication slot with PG17 failover enabled
  // Signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => $2,
       temporary => false,
       two_phase => false,
       failover => true
     );`,
    [slotName, plugin]
  );
}
```

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 Replication Failover Slots & Memory Buffer Invariants

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict configuration and programmatic management of PostgreSQL 17 logical failover slots, standby synchronization, and memory-bounded decoding buffers. Prevents silent replication breakage during physical node failover, disk exhaustion via runaway WAL retention, and OOM kills by mandating synchronized slots, explicit WAL limits, and bounded logical decoding memory. 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 Unsynchronized Logical Replication Slots Without Failover Support or WAL Retention Caps 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 Unsynchronized Logical Replication Slots Without Failover Support or WAL Retention CapsCritical
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+ primaries to ensure persistence across HA failovers.

Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17+ primaries to ensure persistence across HA failovers.

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 verify that `max_slot_wal_keep_size` is configured to a non-negative finite boundary (never '-1' or unset) to prevent cascading disk out-of-space crashes from lagging subscribers.

Engineers MUST ALWAYS verify that `max_slot_wal_keep_size` is configured to a non-negative finite boundary (never '-1' or unset) to prevent cascading disk out-of-space crashes from lagging subscribers.

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 NOT allow logical replication clients to bypass validation of `standby_slot_names` on the primary and `sync_replication_slots = on` on standby replicas.

Engineers MUST NOT allow logical replication clients to bypass validation of `standby_slot_names` on the primary and `sync_replication_slots = on` on standby replicas.

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

Services MUST bound `logical_decoding_work_mem` (defaulting to 64MB-256MB) per decoding worker to prevent backend processes from consuming OS memory outside of `shared_buffers`.

Services MUST bound `logical_decoding_work_mem` (defaulting to 64MB-256MB) per decoding worker to prevent backend processes from consuming OS memory outside of `shared_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.
5

Components NEVER execute raw `pg_create_logical_replication_slot` invocations without passing the 5th argument (`failover

Components NEVER execute raw `pg_create_logical_replication_slot` invocations without passing the 5th argument (`failover := true`) or executing `ALTER REPLICATION SLOT ... (failover true)` on existing PostgreSQL 17 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.
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 Replication Failover Slots & Memory Buffer Invariants critical for AI coding assistants?

Enforces strict configuration and programmatic management of PostgreSQL 17 logical failover slots, standby synchronization, and memory-bounded decoding buffers. Prevents silent replication breakage during physical node failover, disk exhaustion via runaway WAL retention, and OOM kills by mandating synchronized slots, explicit WAL limits, and bounded logical decoding memory. 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 Unsynchronized Logical Replication Slots Without Failover Support or WAL Retention Caps) 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