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-management

PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

Mandates PostgreSQL 17 failover-enabled logical replication slots across physical standby topologies, deterministic WAL retention bounds, and dedicated decoding memory buffers. Prevents silent subscriber invalidation during primary-standby failovers, unbounded disk exhaustion, and backend OOM termination under high-throughput logical streaming.

Prohibited Anti-Pattern: Creating unmanaged logical replication slots without failover synchronization and leaving WAL keep limits unconstrained.

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 across physical standby topologies, deterministic WAL retention bounds, and dedicated decoding memory buffers. Prevents silent subscriber invalidation during primary-standby failovers, unbounded disk exhaustion, and backend OOM termination under high-throughput logical streaming.
globs: src/**/*.ts, src/**/*.sql, migrations/**/*.sql, infra/**/*.tf, k8s/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-and-buffer-management"
---

# PostgreSQL 17 Logical Replication Failover Slots & Memory Buffer Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating unmanaged logical replication slots without failover synchronization and leaving WAL keep limits unconstrained.

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing PostgreSQL 17 Logical Replication and Memory Buffer standards. PostgreSQL 17 introduces native failover-enabled logical slots ('failover = true') and synchronization to physical standbys. You must reject any DDL, migration, or infrastructure-as-code that provisions logical replication without failover attributes, fails to define `synchronized_standby_slots`, leaves `max_slot_wal_keep_size` unbounded, or misallocates `logical_decoding_work_mem` alongside `shared_buffers`.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17 clusters equipped with physical standbys (via `pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).
- Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to reference physical standby slot names, ensuring physical replication precedes logical consumer consumption.
- Engineers MUST NEVER set `max_slot_wal_keep_size = -1` in production; wal retention MUST be bounded to prevent cascading primary disk exhaustion if a subscriber drops offline.
- Services MUST explicitly configure `logical_decoding_work_mem` (recommended 64MB-256MB) to contain in-memory decoding transaction size before spilling to temporary files, preventing OOM against the `shared_buffers` allocation limit.
- Subscribers MUST configure `streaming = 'parallel'` or `streaming = 'on'` when provisioning subscriptions on PG17 to prevent long-running in-memory buffer saturation during bulk transactions.
- Health-check services MUST query `pg_replication_slots` for `sync_state` ('sync', 'ready') and check `pg_stat_replication_slots` for `spill_bytes` and `total_bytes` to detect replication bottlenecks before WAL threshold eviction.

## Bad vs Good Implementations
### PostgreSQL 17 Failover Slot Provisioning & Memory Guardrail Orchestration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical slot without PG17 `failover => true` causes the slot to disappear when a physical standby promotes, permanently breaking logical downstream consumers. In addition, omitted memory parameters allow unconstrained transaction accumulation in memory, risking OOM and disk exhaustion.
```typescript
import { Pool } from 'pg';

export async function setupSubscriptionSlot(pool: Pool, slotName: string): Promise<void> {
  // FAILS: Does not enable failover=true (Postgres 17 feature).
  // If primary fails over to a physical replica, the slot is lost and downstream logical subscribers fail.
  // FAILS: Leaves max_slot_wal_keep_size unbounded, risking primary disk full.
  await pool.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);

  // FAILS: Does not tune logical_decoding_work_mem, risking decoder backend OOM under high transaction volume
  await pool.query(`
    CREATE PUBLICATION app_events_pub FOR ALL TABLES;
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Leverages PostgreSQL 17's native `failover => true` parameter to enable slot synchronization across physical standby instances. Explicitly caps `max_slot_wal_keep_size` to guard against cascading disk exhaustion and sizes `logical_decoding_work_mem` to prevent decoder OOM.
```typescript
import { Pool } from 'pg';

export interface LogicalReplicationConfig {
  slotName: string;
  publicationName: string;
  maxSlotWalKeepSizeMb: number;
  decodingWorkMemMb: number;
}

export async function setupProductionLogicalReplication(
  pool: Pool,
  config: LogicalReplicationConfig
): Promise<void> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // Verify PG17+ server version for failover slot support
    const versionRes = await client.query('SHOW server_version_num');
    const serverVersion = parseInt(versionRes.rows[0].server_version_num, 10);
    if (serverVersion < 170000) {
      throw new Error(`PostgreSQL 170000+ required for native failover slots. Detected: ${serverVersion}`);
    }

    // 1. Bound WAL keep size per slot to prevent disk exhaustion
    await client.query(`ALTER SYSTEM SET max_slot_wal_keep_size = '${config.maxSlotWalKeepSizeMb}MB'`);
    
    // 2. Bound decoding memory to protect shared_buffers and avoid backend process OOM
    await client.query(`ALTER SYSTEM SET logical_decoding_work_mem = '${config.decodingWorkMemMb}MB'`);
    await client.query('SELECT pg_reload_conf()');

    // 3. Create publication if not exists
    await client.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = '${config.publicationName}') THEN
          CREATE PUBLICATION ${config.publicationName} FOR ALL TABLES;
        END IF;
      END
      $$;
    `);

    // 4. Provision logical slot with PG17 failover => true and temporary => false
    await client.query(`
      SELECT pg_create_logical_replication_slot(
        slot_name => $1,
        plugin => 'pgoutput',
        temporary => false,
        twophase => true,
        failover => true
      )
      WHERE NOT EXISTS (
        SELECT 1 FROM pg_replication_slots WHERE slot_name = $1
      );
    `, [config.slotName]);

    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}
```

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 across physical standby topologies, deterministic WAL retention bounds, and dedicated decoding memory buffers. Prevents silent subscriber invalidation during primary-standby failovers, unbounded disk exhaustion, and backend OOM termination under 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: Creating unmanaged logical replication slots without failover synchronization and leaving WAL keep limits unconstrained. 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 replication slots without failover synchronization and leaving WAL keep limits unconstrained.Critical
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 clusters equipped with physical standbys (via `pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).

Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17 clusters equipped with physical standbys (via `pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).

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 `synchronized_standby_slots` on the primary instance to reference physical standby slot names, ensuring physical replication precedes logical consumer consumption.

Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to reference physical standby slot names, ensuring physical replication precedes logical consumer consumption.

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 NEVER set `max_slot_wal_keep_size = -1` in production

Engineers MUST NEVER set `max_slot_wal_keep_size = -1` in production; wal retention MUST be bounded to prevent cascading primary disk exhaustion if a subscriber drops offline.

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 explicitly configure `logical_decoding_work_mem` (recommended 64MB-256MB) to contain in-memory decoding transaction size before spilling to temporary files, preventing OOM against the `shared_buffers` allocation limit.

Services MUST explicitly configure `logical_decoding_work_mem` (recommended 64MB-256MB) to contain in-memory decoding transaction size before spilling to temporary files, preventing OOM against the `shared_buffers` allocation limit.

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

Subscribers MUST configure `streaming = 'parallel'` or `streaming = 'on'` when provisioning subscriptions on PG17 to prevent long-running in-memory buffer saturation during bulk transactions.

Subscribers MUST configure `streaming = 'parallel'` or `streaming = 'on'` when provisioning subscriptions on PG17 to prevent long-running in-memory buffer saturation during bulk 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.
6

Health-check services MUST query `pg_replication_slots` for `sync_state` ('sync', 'ready') and check `pg_stat_replication_slots` for `spill_bytes` and `total_bytes` to detect replication bottlenecks before WAL threshold eviction.

Health-check services MUST query `pg_replication_slots` for `sync_state` ('sync', 'ready') and check `pg_stat_replication_slots` for `spill_bytes` and `total_bytes` to detect replication bottlenecks before WAL threshold eviction.

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 across physical standby topologies, deterministic WAL retention bounds, and dedicated decoding memory buffers. Prevents silent subscriber invalidation during primary-standby failovers, unbounded disk exhaustion, and backend OOM termination under 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 (Creating unmanaged logical replication slots without failover synchronization and leaving WAL keep limits unconstrained.) 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