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

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Standards

Standardizes the programmatic management of PostgreSQL 17 logical replication slots and memory buffers in high-availability topologies. Mandates the use of PG17 failover-enabled slots synchronized across physical standbys, explicit max_slot_wal_keep_size bounding, and calibrated logical_decoding_work_mem to prevent primary node crashes and split-brain data streams.

Prohibited Anti-Pattern: Unsynchronized Logical Slots Lacking Failover Flags and Unbounded WAL Retention

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Standards - Standardizes the programmatic management of PostgreSQL 17 logical replication slots and memory buffers in high-availability topologies. Mandates the use of PG17 failover-enabled slots synchronized across physical standbys, explicit max_slot_wal_keep_size bounding, and calibrated logical_decoding_work_mem to prevent primary node crashes and split-brain data streams.
globs: src/**/*.ts, src/**/*.pg.ts, migrations/**/*.sql, infra/**/*.conf, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-and-buffer-invariants"
---

# PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Standards

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots Lacking Failover Flags and Unbounded WAL Retention

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 logical replication and shared buffer standards. Mandate failover-safe replication slot management (pg_create_logical_replication_slot with failover=true), synchronized standby slots coordination, strict WAL retention bounding via max_slot_wal_keep_size, and explicit logical_decoding_work_mem governance to safeguard shared_buffers from transaction reassembly thrashing.

## Strict Guidelines
- Engineers MUST ALWAYS specify 'failover => true' when invoking 'pg_create_logical_replication_slot' on PostgreSQL 17 to ensure slot synchronization across physical standbys.
- Engineers MUST NEVER permit unconstrained logical replication slots; 'max_slot_wal_keep_size' MUST be explicitly configured and monitored to prevent out-of-disk primary crashes.
- Services managing logical replication connections MUST verify that the physical replica slot is registered in 'synchronized_standby_slots' before starting CDC consumers.
- Engineers MUST calibrate 'logical_decoding_work_mem' independently of 'work_mem', keeping it between 64MB and 1GB per decoding worker to prevent spill-to-disk serialization without starving 'shared_buffers'.
- Services MUST query 'pg_replication_slots' for 'conflicting = true' or 'invalidated' reasons (such as 'wal_removed') and implement active alerting and recovery paths rather than assuming infinite slot validity.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Slot Provisioning with Failover & Memory Guards

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without `failover => true` on PostgreSQL 17 means the slot will not sync to physical standbys. Upon primary failover, CDC consumers will fail completely or re-stream from epoch. Omitting WAL limits or buffer boundaries exposes the primary database to disk saturation if the consumer lags.
```typescript
import { Client } from 'pg';

export async function initConsumerReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Pre-PG17 syntax, no failover flag, unbounded WAL accumulation risk,
  // and ignores physical standby synchronization dependencies.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
  
  console.log(`Replication slot ${slotName} created without failover sync.`);
}
```

#### Production Standard (Correct)
> **Standard**: Uses PostgreSQL 17's explicit `failover => true` parameter in `pg_create_logical_replication_slot`, bounds `logical_decoding_work_mem` to prevent memory contention with `shared_buffers`, and asserts that `max_slot_wal_keep_size` is non-infinite to protect host disk health.
```typescript
import { Client } from 'pg';

export interface ReplicationSlotConfig {
  slotName: string;
  plugin?: 'pgoutput';
  failover?: boolean;
  decodingWorkMemMb?: number;
}

export async function initConsumerReplicationSlot(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  const plugin = config.plugin ?? 'pgoutput';
  const failover = config.failover ?? true;
  const decodingMem = config.decodingWorkMemMb ?? 128;

  // Guardrail 1: Enforce logical decoding work memory for the current session
  // to protect shared_buffers while preventing spill-to-disk for large transactions
  await client.query(`SET logical_decoding_work_mem = '${decodingMem}MB';`);

  // Guardrail 2: Ensure max_slot_wal_keep_size is bounded to prevent storage exhaustion
  const walKeepRes = await client.query(
    `SHOW max_slot_wal_keep_size;`
  );
  const walKeepSize = walKeepRes.rows[0]?.max_slot_wal_keep_size;
  if (walKeepSize === '-1' || walKeepSize === '0') {
    throw new Error('Unsafe cluster configuration: max_slot_wal_keep_size must be explicitly bounded (> 0).');
  }

  // Guardrail 3: Postgres 17 failover-enabled logical slot creation
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => $2,
       temporary => false,
       twophase => false,
       failover => $3
     );`,
    [config.slotName, plugin, failover]
  );

  // Guardrail 4: Verify slot health and failover configuration in pg_replication_slots
  const slotCheck = await client.query(
    `SELECT slot_name, failover, synced, conflicting
     FROM pg_replication_slots
     WHERE slot_name = $1;`,
    [config.slotName]
  );

  if (!slotCheck.rows[0]?.failover) {
    throw new Error(`Failed to initialize Postgres 17 failover-enabled slot: ${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 Logical Replication Failover Slots & Memory Buffer Standards

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Standards defines an industrial-grade behavioral standard for backend engineering. Standardizes the programmatic management of PostgreSQL 17 logical replication slots and memory buffers in high-availability topologies. Mandates the use of PG17 failover-enabled slots synchronized across physical standbys, explicit max_slot_wal_keep_size bounding, and calibrated logical_decoding_work_mem to prevent primary node crashes and split-brain data streams. 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 Logical Slots Lacking Failover Flags and Unbounded WAL Retention 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 Logical Slots Lacking Failover Flags and Unbounded WAL RetentionCritical
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 specify 'failover => true' when invoking 'pg_create_logical_replication_slot' on PostgreSQL 17 to ensure slot synchronization across physical standbys.

Engineers MUST ALWAYS specify 'failover => true' when invoking 'pg_create_logical_replication_slot' on PostgreSQL 17 to ensure slot synchronization across 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 NEVER permit unconstrained logical replication slots

Engineers MUST NEVER permit unconstrained logical replication slots; 'max_slot_wal_keep_size' MUST be explicitly configured and monitored to prevent out-of-disk primary crashes.

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 managing logical replication connections MUST verify that the physical replica slot is registered in 'synchronized_standby_slots' before starting CDC consumers.

Services managing logical replication connections MUST verify that the physical replica slot is registered in 'synchronized_standby_slots' before starting CDC consumers.

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 calibrate 'logical_decoding_work_mem' independently of 'work_mem', keeping it between 64MB and 1GB per decoding worker to prevent spill-to-disk serialization without starving 'shared_buffers'.

Engineers MUST calibrate 'logical_decoding_work_mem' independently of 'work_mem', keeping it between 64MB and 1GB per decoding worker to prevent spill-to-disk serialization without starving '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

Services MUST query 'pg_replication_slots' for 'conflicting = true' or 'invalidated' reasons (such as 'wal_removed') and implement active alerting and recovery paths rather than assuming infinite slot validity.

Services MUST query 'pg_replication_slots' for 'conflicting = true' or 'invalidated' reasons (such as 'wal_removed') and implement active alerting and recovery paths rather than assuming infinite slot validity.

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 Standards critical for AI coding assistants?

Standardizes the programmatic management of PostgreSQL 17 logical replication slots and memory buffers in high-availability topologies. Mandates the use of PG17 failover-enabled slots synchronized across physical standbys, explicit max_slot_wal_keep_size bounding, and calibrated logical_decoding_work_mem to prevent primary node crashes and split-brain data streams. 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 Logical Slots Lacking Failover Flags and Unbounded WAL Retention) 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