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

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

Enforces PostgreSQL 17 native failover-enabled logical replication slot architecture, synchronized standby configuration, bounded WAL retention, and deterministic shared_buffers/logical_decoding_work_mem allocation. Prevents silent replication loss during physical primary failovers and eliminates cascading WAL disk exhaustion under high subscriber lag.

Prohibited Anti-Pattern: Creating Unmanaged Logical Slots Without Failover Support or WAL Retention Bounds

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 PostgreSQL 17 native failover-enabled logical replication slot architecture, synchronized standby configuration, bounded WAL retention, and deterministic shared_buffers/logical_decoding_work_mem allocation. Prevents silent replication loss during physical primary failovers and eliminates cascading WAL disk exhaustion under high subscriber lag.
globs: src/db/**/*.ts, src/infra/**/*.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-buffer-invariants"
---

# PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

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

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing PostgreSQL 17 production invariants. Mandate that all logical replication configurations utilize PG 17 failover slot management (failover = true, synchronized_standby_slots), enforce finite WAL retention limits via max_slot_wal_keep_size, configure parallel streaming logical decoding, and enforce strict shared_buffers and logical_decoding_work_mem invariants.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 with 'failover = true' and configure primary instances with 'synchronized_standby_slots' matching physical replicas to guarantee zero-loss logical stream continuity after HA failover.
- Engineers MUST NEVER provision unbounded logical replication slots; 'max_slot_wal_keep_size' MUST be explicitly configured to an absolute ceiling (e.g., 64GB-128GB) to prevent disconnected subscribers from exhausting primary WAL disk storage.
- Services defining PostgreSQL 17 subscriptions MUST specify 'streaming = parallel' (or 'streaming = on') combined with tuned 'logical_decoding_work_mem' (minimum 128MB, up to 1GB) to eliminate temp-file disk spooling for large concurrent transactions.
- Database configurations MUST tune 'shared_buffers' between 20% and 30% of total system RAM (capped at 32GB unless NUMA and Huge Pages are verified), preserving remaining memory for the OS page cache and PostgreSQL 17 vectorized I/O prefetching engines.
- Components NEVER execute logical decoding setups against unmonitored standbys without continuous assertion of 'pg_sync_replication_slots()' health and standby catalog progress validation.

## Bad vs Good Implementations
### PostgreSQL 17 High-Availability Logical Slot Provisioning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates a logical replication slot without Postgres 17's failover capability, causing logical replication consumers to become permanently orphaned if the physical primary fails over to a replica. Additionally, omission of max_slot_wal_keep_size allows lagging consumers to cause catastrophic primary node out-of-disk crashes.
```typescript
// Anti-pattern: Pre-PG17 style slot creation without failover and unconstrained WAL growth
import { Client } from 'pg';

export async function setupPipelineReplication(client: Client, slotName: string, subName: string) {
  // Flaw 1: Slot lacks failover=true; when physical primary fails over, logical slot is lost
  // Flaw 2: Unbounded WAL retention will consume 100% disk if consumer disconnects
  await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput');`, [slotName]);

  // Flaw 3: Default streaming spools large transactions to disk in temp files
  await client.query(`
    CREATE SUBSCRIPTION ${subName}
    CONNECTION 'host=db-primary.internal dbname=app user=rep_user'
    PUBLICATION app_cdc_pub
    WITH (create_slot = false, slot_name = '${slotName}');
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Implements PostgreSQL 17 native failover logical replication slots ('failover = true'), integrates bounded WAL retention via max_slot_wal_keep_size, and utilizes parallel streaming to ensure high throughput while preventing both disk exhaustion and subscriber loss on HA failover.
```typescript
// Production standard: PG 17 native failover slot with synchronized standby protection and memory streaming
import { Client } from 'pg';

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

export async function setupPipelineReplicationPG17(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  const { slotName, subscriptionName, publicationName, primaryConnString, maxWalKeepSizeMb } = config;

  // Enforce WAL retention safety limit at database/session scope
  await client.query(`SET max_slot_wal_keep_size = '${maxWalKeepSizeMb}MB';`);

  // PostgreSQL 17: Provision logical slot with failover enabled (5th parameter: failover = true)
  // Syntax: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      $1,
      'pgoutput',
      false,
      false,
      true
    );
  `, [slotName]);

  // Create subscription with PG17 parallel streaming and memory decoding parameters
  await client.query(`
    CREATE SUBSCRIPTION ${subscriptionName}
    CONNECTION '${primaryConnString}'
    PUBLICATION ${publicationName}
    WITH (
      create_slot = false,
      slot_name = '${slotName}',
      streaming = 'parallel',
      copy_data = false
    );
  `);
}
```

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 PostgreSQL 17 native failover-enabled logical replication slot architecture, synchronized standby configuration, bounded WAL retention, and deterministic shared_buffers/logical_decoding_work_mem allocation. Prevents silent replication loss during physical primary failovers and eliminates cascading WAL disk exhaustion under high subscriber lag. 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 Unmanaged Logical Slots Without Failover Support or WAL Retention Bounds 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 Unmanaged Logical Slots Without Failover Support or WAL Retention BoundsCritical
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 with 'failover = true' and configure primary instances with 'synchronized_standby_slots' matching physical replicas to guarantee zero-loss logical stream continuity after HA failover.

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 with 'failover = true' and configure primary instances with 'synchronized_standby_slots' matching physical replicas to guarantee zero-loss logical stream continuity after HA failover.

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 provision unbounded logical replication slots

Engineers MUST NEVER provision unbounded logical replication slots; 'max_slot_wal_keep_size' MUST be explicitly configured to an absolute ceiling (e.g., 64GB-128GB) to prevent disconnected subscribers from exhausting primary WAL disk storage.

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 defining PostgreSQL 17 subscriptions MUST specify 'streaming = parallel' (or 'streaming = on') combined with tuned 'logical_decoding_work_mem' (minimum 128MB, up to 1GB) to eliminate temp-file disk spooling for large concurrent transactions.

Services defining PostgreSQL 17 subscriptions MUST specify 'streaming = parallel' (or 'streaming = on') combined with tuned 'logical_decoding_work_mem' (minimum 128MB, up to 1GB) to eliminate temp-file disk spooling for large concurrent transactions.

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

Database configurations MUST tune 'shared_buffers' between 20% and 30% of total system RAM (capped at 32GB unless NUMA and Huge Pages are verified), preserving remaining memory for the OS page cache and PostgreSQL 17 vectorized I/O prefetching engines.

Database configurations MUST tune 'shared_buffers' between 20% and 30% of total system RAM (capped at 32GB unless NUMA and Huge Pages are verified), preserving remaining memory for the OS page cache and PostgreSQL 17 vectorized I/O prefetching engines.

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 logical decoding setups against unmonitored standbys without continuous assertion of 'pg_sync_replication_slots()' health and standby catalog progress validation.

Components NEVER execute logical decoding setups against unmonitored standbys without continuous assertion of 'pg_sync_replication_slots()' health and standby catalog progress validation.

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 PostgreSQL 17 native failover-enabled logical replication slot architecture, synchronized standby configuration, bounded WAL retention, and deterministic shared_buffers/logical_decoding_work_mem allocation. Prevents silent replication loss during physical primary failovers and eliminates cascading WAL disk exhaustion under high subscriber lag. 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 Unmanaged Logical Slots Without Failover Support or WAL Retention Bounds) 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