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-memory-invariants

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

Mandates PostgreSQL 17 failover-enabled logical replication slots combined with synchronized standby slots to guarantee zero subscription loss upon physical replica promotion. Enforces strict logical_decoding_work_mem boundaries and bounded max_slot_wal_keep_size to prevent catastrophic WAL disk bloat and shared_buffers memory contention during high-throughput logical streaming.

Prohibited Anti-Pattern: Unsynchronized Legacy Replication Slots and Unbounded WAL Retention Crashing Primaries

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 - Mandates PostgreSQL 17 failover-enabled logical replication slots combined with synchronized standby slots to guarantee zero subscription loss upon physical replica promotion. Enforces strict logical_decoding_work_mem boundaries and bounded max_slot_wal_keep_size to prevent catastrophic WAL disk bloat and shared_buffers memory contention during high-throughput logical streaming.
globs: src/db/**/*.ts, src/infra/**/*.ts, migrations/**/*.ts, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-memory-invariants"
---

# PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Legacy Replication Slots and Unbounded WAL Retention Crashing Primaries

## System Constraints
You are a Principal Database Reliability Engineer enforcing PostgreSQL 17 logical replication and memory buffer standards. Enforce the failover => true invariant on logical replication slots, explicit synchronized_standby_slots configurations, deterministic logical_decoding_work_mem limits to prevent disk spilling, and non-negotiable max_slot_wal_keep_size ceilings to protect instances from disk saturation.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 using failover => true (e.g., pg_create_logical_replication_slot(slot_name, plugin, false, false, true)) to prevent orphaned logical consumers on standby promotion.
- Engineers MUST ALWAYS set a bounded max_slot_wal_keep_size (recommended: 10GB - 50GB depending on disk volume) to prevent runaway WAL generation from exhausting the primary file system when a subscriber stalls.
- Code MUST set streaming = 'parallel' or streaming = 'on' in CREATE SUBSCRIPTION statements to prevent large transactions from exhausting client-side memory buffers and spilling unbuffered writes to disk.
- Services MUST configure logical_decoding_work_mem (default 64MB; tune up to 512MB for high-volume pipelines) independently of work_mem and shared_buffers to bound WAL decoding memory in the walsender processes.
- Services NEVER create unmonitored logical replication slots; an automated metric monitor MUST track pg_replication_slots.wal_status and pg_replication_slots.active to flag unconsumed slots before max_slot_wal_keep_size triggers WAL invalidation.

## Bad vs Good Implementations
### Postgres 17 Logical Replication Provisioning & Failover Slot Registration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the failover flag creates an ephemeral logical slot that disappears upon physical failover, permanently corrupting subscriber replication pipelines. Omission of streaming settings forces the subscriber to buffer entire transactions in memory, while lack of bounded max_slot_wal_keep_size causes primary node out-of-disk crashes if replication halts.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client, slotName: string, subName: string): Promise<void> {
  // Anti-Pattern: Missing PG17 failover parameter, streaming disabled, no WAL limits
  await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput');`, [slotName]);

  // Subscriber creation defaults to streaming = off, buffering full transaction in memory
  await client.query(`
    CREATE SUBSCRIPTION ${subName}
    CONNECTION 'host=primary.internal dbname=app user=rep_user'
    PUBLICATION app_publication
    WITH (copy_data = true, create_slot = false, slot_name = '${slotName}');
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to PostgreSQL 17 replication slot invariants: sets failover => true in slot generation and subscription configuration, enables parallel transaction streaming to conserve apply-worker memory buffers, and guarantees bounded WAL retention.
```typescript
import { Client } from 'pg';

export interface ReplicationSlotConfig {
  slotName: string;
  subscriptionName: string;
  publicationName: string;
  primaryConnString: string;
  maxWalKeepMb: number;
}

export async function setupLogicalReplication(client: Client, config: ReplicationSlotConfig): Promise<void> {
  // Invariant 1: Ensure max_slot_wal_keep_size is bounded to prevent storage exhaustion
  await client.query(`SET max_slot_wal_keep_size = '${config.maxWalKeepMb}MB';`);

  // Invariant 2: Explicitly provision PostgreSQL 17 slot with failover enabled and pgoutput
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => 'pgoutput',
      temporary => false,
      twophase => true,
      failover => true
    );
  `, [config.slotName]);

  // Invariant 3: Subscription utilizes streaming='parallel' and synchronizes slot state
  await client.query(`
    CREATE SUBSCRIPTION ${config.subscriptionName}
    CONNECTION '${config.primaryConnString}'
    PUBLICATION ${config.publicationName}
    WITH (
      copy_data = true,
      create_slot = false,
      slot_name = '${config.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 Replication Failover Slots & Memory Buffer Invariants

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants defines an industrial-grade behavioral standard for backend engineering. Mandates PostgreSQL 17 failover-enabled logical replication slots combined with synchronized standby slots to guarantee zero subscription loss upon physical replica promotion. Enforces strict logical_decoding_work_mem boundaries and bounded max_slot_wal_keep_size to prevent catastrophic WAL disk bloat and shared_buffers memory contention during high-throughput logical streaming. 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 Legacy Replication Slots and Unbounded WAL Retention Crashing Primaries 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 Legacy Replication Slots and Unbounded WAL Retention Crashing PrimariesCritical
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 in PostgreSQL 17 using failover => true (e.g., pg_create_logical_replication_slot(slot_name, plugin, false, false, true)) to prevent orphaned logical consumers on standby promotion.

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 using failover => true (e.g., pg_create_logical_replication_slot(slot_name, plugin, false, false, true)) to prevent orphaned logical consumers on standby promotion.

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 set a bounded max_slot_wal_keep_size (recommended

Engineers MUST ALWAYS set a bounded max_slot_wal_keep_size (recommended: 10GB - 50GB depending on disk volume) to prevent runaway WAL generation from exhausting the primary file system when a subscriber stalls.

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

Code MUST set streaming = 'parallel' or streaming = 'on' in CREATE SUBSCRIPTION statements to prevent large transactions from exhausting client-side memory buffers and spilling unbuffered writes to disk.

Code MUST set streaming = 'parallel' or streaming = 'on' in CREATE SUBSCRIPTION statements to prevent large transactions from exhausting client-side memory buffers and spilling unbuffered writes to disk.

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 configure logical_decoding_work_mem (default 64MB

Services MUST configure logical_decoding_work_mem (default 64MB; tune up to 512MB for high-volume pipelines) independently of work_mem and shared_buffers to bound WAL decoding memory in the walsender processes.

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 NEVER create unmonitored logical replication slots

Services NEVER create unmonitored logical replication slots; an automated metric monitor MUST track pg_replication_slots.wal_status and pg_replication_slots.active to flag unconsumed slots before max_slot_wal_keep_size triggers WAL invalidation.

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?

Mandates PostgreSQL 17 failover-enabled logical replication slots combined with synchronized standby slots to guarantee zero subscription loss upon physical replica promotion. Enforces strict logical_decoding_work_mem boundaries and bounded max_slot_wal_keep_size to prevent catastrophic WAL disk bloat and shared_buffers memory contention during high-throughput logical streaming. 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 Legacy Replication Slots and Unbounded WAL Retention Crashing Primaries) 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