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

PostgreSQL 17 Logical Replication Failover Synchronization & Memory Buffer Invariants

Enforces strict PostgreSQL 17 logical replication topologies, requiring failover-enabled logical slots and physical standby synchronization via synchronized_standby_slots. Mandates deterministic memory allocations for shared_buffers and logical_decoding_work_mem to prevent disk spilling and out-of-memory cascading failures during replication stream decode.

Prohibited Anti-Pattern: Creating un-synchronized logical slots lacking failover flags while under-allocating decoding memory buffers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Failover Synchronization & Memory Buffer Invariants - Enforces strict PostgreSQL 17 logical replication topologies, requiring failover-enabled logical slots and physical standby synchronization via synchronized_standby_slots. Mandates deterministic memory allocations for shared_buffers and logical_decoding_work_mem to prevent disk spilling and out-of-memory cascading failures during replication stream decode.
globs: src/**/*.ts, migrations/**/*.sql, infra/**/*.tf, database/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-buffer-invariants"
---

# PostgreSQL 17 Logical Replication Failover Synchronization & Memory Buffer Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating un-synchronized logical slots lacking failover flags while under-allocating decoding memory buffers

## System Constraints
You are a Principal Database Architect and Infrastructure Engineer enforcing PostgreSQL 17 standards. You must mandate that all logical replication slots utilize PG17 failover parameters ('failover = true'), pair them with primary synchronized_standby_slots configurations, enforce non-zero max_slot_wal_keep_size thresholds to protect disk bounds, and allocate logical_decoding_work_mem alongside shared_buffers to prevent decoding transaction serialization to disk.

## Strict Guidelines
- Engineers MUST ALWAYS enable the `failover` option when creating logical replication slots in PostgreSQL 17 (`pg_create_logical_replication_slot(..., failover => true)`) or alter existing slots (`ALTER_REPLICATION_SLOT ... (failover = true)`).
- Services MUST configure `synchronized_standby_slots` on the primary instance to include physical standby slot identifiers before streaming logical replication data to subscribers.
- Engineers MUST configure `logical_decoding_work_mem` (minimum 64MB-256MB per active walsender) alongside `shared_buffers` (capped at 25% of system RAM) to eliminate serialization spillover to ephemeral disk files during high-volume transaction decoding.
- Engineers MUST ALWAYS enforce a finite, monitorable `max_slot_wal_keep_size` on all instances to guarantee replication lag does not trigger catastrophic primary node storage exhaustion.
- Code MUST NOT trigger non-streaming, all-or-nothing logical replication sync scripts without explicitly handling pg_replication_slot_advance() bounds and transient slot invalidations.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Slot Creation and Parameter Setup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates a logical slot without PG17 `failover => true`, leaving subscriber streams orphaned or corrupted upon primary-to-standby failover. Defaults `logical_decoding_work_mem` to baseline (64kB), forcing large transactional decodes to serialize to temp files on disk.
```typescript
import { Client } from 'pg';

export async function setupReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Missing failover parameter (PG17), no max_slot_wal_keep_size safeguard,
  // and logical_decoding_work_mem left to the default 64kB causing disk thrashing.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Leverages PostgreSQL 17 native `failover => true` syntax and sets explicit `logical_decoding_work_mem` to prevent memory eviction and disk-spill penalties while maintaining full failover capability across high-availability standby replicas.
```typescript
import { Client } from 'pg';

interface ReplicationSlotOptions {
  slotName: string;
  outputPlugin?: string;
  maxDecodingWorkMemMb?: number;
}

export async function setupReplicationSlot(
  client: Client,
  options: ReplicationSlotOptions
): Promise<void> {
  const { slotName, outputPlugin = 'pgoutput', maxDecodingWorkMemMb = 128 } = options;

  await client.query('BEGIN');
  try {
    // Set session-level or server-level memory to prevent disk spillage during logical decoding
    await client.query(`SET LOCAL logical_decoding_work_mem = '${maxDecodingWorkMemMb}MB';`);

    // PG17 invariant: failover => true ensures the slot is synchronized across standbys
    await client.query(
      `SELECT pg_create_logical_replication_slot(
        slot_name => $1,
        plugin => $2,
        temporary => false,
        twophase => true,
        failover => true
      );`,
      [slotName, outputPlugin]
    );

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Logical Replication Failover Synchronization & Memory Buffer Invariants

PostgreSQL 17 Logical Replication Failover Synchronization & Memory Buffer Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict PostgreSQL 17 logical replication topologies, requiring failover-enabled logical slots and physical standby synchronization via synchronized_standby_slots. Mandates deterministic memory allocations for shared_buffers and logical_decoding_work_mem to prevent disk spilling and out-of-memory cascading failures during replication stream decode. 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 un-synchronized logical slots lacking failover flags while under-allocating decoding memory buffers 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 un-synchronized logical slots lacking failover flags while under-allocating decoding memory buffersCritical
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 enable the `failover` option when creating logical replication slots in PostgreSQL 17 (`pg_create_logical_replication_slot(..., failover => true)`) or alter existing slots (`ALTER_REPLICATION_SLOT ... (failover = true)`).

Engineers MUST ALWAYS enable the `failover` option when creating logical replication slots in PostgreSQL 17 (`pg_create_logical_replication_slot(..., failover => true)`) or alter existing slots (`ALTER_REPLICATION_SLOT ... (failover = 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

Services MUST configure `synchronized_standby_slots` on the primary instance to include physical standby slot identifiers before streaming logical replication data to subscribers.

Services MUST configure `synchronized_standby_slots` on the primary instance to include physical standby slot identifiers before streaming logical replication data to 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 configure `logical_decoding_work_mem` (minimum 64MB-256MB per active walsender) alongside `shared_buffers` (capped at 25% of system RAM) to eliminate serialization spillover to ephemeral disk files during high-volume transaction decoding.

Engineers MUST configure `logical_decoding_work_mem` (minimum 64MB-256MB per active walsender) alongside `shared_buffers` (capped at 25% of system RAM) to eliminate serialization spillover to ephemeral disk files during high-volume transaction decoding.

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 ALWAYS enforce a finite, monitorable `max_slot_wal_keep_size` on all instances to guarantee replication lag does not trigger catastrophic primary node storage exhaustion.

Engineers MUST ALWAYS enforce a finite, monitorable `max_slot_wal_keep_size` on all instances to guarantee replication lag does not trigger catastrophic primary node storage exhaustion.

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

Code MUST NOT trigger non-streaming, all-or-nothing logical replication sync scripts without explicitly handling pg_replication_slot_advance() bounds and transient slot invalidations.

Code MUST NOT trigger non-streaming, all-or-nothing logical replication sync scripts without explicitly handling pg_replication_slot_advance() bounds and transient slot invalidations.

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 Synchronization & Memory Buffer Invariants critical for AI coding assistants?

Enforces strict PostgreSQL 17 logical replication topologies, requiring failover-enabled logical slots and physical standby synchronization via synchronized_standby_slots. Mandates deterministic memory allocations for shared_buffers and logical_decoding_work_mem to prevent disk spilling and out-of-memory cascading failures during replication stream decode. 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 un-synchronized logical slots lacking failover flags while under-allocating decoding memory buffers) 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