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

PostgreSQL 17 Failover Slot Synchronization & Buffer Tuning Invariants

Enforces PostgreSQL 17 failover-enabled logical replication slot configurations and validates synchronized standby slots to prevent replication invalidation upon node promotion. Guarantees memory safety by decoupling logical decoding allocations from shared_buffers, tuning logical_decoding_work_mem to prevent disk spilling, and setting max_slot_wal_keep_size boundaries.

Prohibited Anti-Pattern: Unsynchronized failover-disabled logical slots and unbounded logical memory allocation leading to failover data loss and shared_buffers eviction storms

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization & Buffer Tuning Invariants - Enforces PostgreSQL 17 failover-enabled logical replication slot configurations and validates synchronized standby slots to prevent replication invalidation upon node promotion. Guarantees memory safety by decoupling logical decoding allocations from shared_buffers, tuning logical_decoding_work_mem to prevent disk spilling, and setting max_slot_wal_keep_size boundaries.
globs: src/db/**/*.ts, migrations/**/*.ts, infra/**/*.tf, src/services/replication/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-memory-guardrails"
---

# PostgreSQL 17 Failover Slot Synchronization & Buffer Tuning Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized failover-disabled logical slots and unbounded logical memory allocation leading to failover data loss and shared_buffers eviction storms

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 Logical Replication and Memory Buffer invariants. Mandate that all logical replication slots utilize PG17 failover options and standby synchronization, enforce non-spilling streaming modes, bound WAL retention with max_slot_wal_keep_size, and ensure logical_decoding_work_mem and shared_buffers are strictly bounded to prevent out-of-memory errors and WAL directory exhaustion.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` and verify synchronization against `synchronized_standby_slots` in PostgreSQL 17 clusters.
- Engineers MUST NOT allow logical replication subscriptions to use default blocking streaming; subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` to avoid local spool thrashing.
- Services MUST ALWAYS define an explicit `max_slot_wal_keep_size` on primary instances to avoid disk exhaustion caused by stale or disconnected logical slots.
- Engineers MUST ALWAYS set `logical_decoding_work_mem` within bounds (minimum 64MB, maximum 1GB depending on instance RAM) to isolate logical decoding allocations from `shared_buffers`.
- Components NEVER execute raw DDL drops on logical replication slots without inspecting `pg_replication_slots.conflicting` and issuing proper graceful subscriber detach procedures.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Slot Creation and Subscription Provisioning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Postgres 17, omitting failover: true leaves logical slots out of standby synchronization; upon primary failover, the subscriber cannot resume and requires full resync. Omitting max_slot_wal_keep_size risks primary node disk exhaustion, and defaulting streaming to off causes massive unstreamed buffer memory usage.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client, slotName: string, pubName: string) {
  // Anti-pattern: Missing PG17 failover parameter, no WAL retention guardrail,
  // and unstreamed subscription defaulting to memory/disk spill buffers.
  await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput');`, [slotName]);
  await client.query(`CREATE PUBLICATION ${pubName} FOR ALL TABLES;`);
  await client.query(`
    CREATE SUBSCRIPTION app_sub
    CONNECTION 'host=db-primary port=5432 user=rep_user dbname=app'
    PUBLICATION ${pubName}
    WITH (copy_data = true, create_slot = false, slot_name = '${slotName}');
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to PostgreSQL 17 invariants by setting failover = true on both the slot creation and subscription, enforces parallel transaction streaming to avoid memory spills, and bounds WAL buffer retention with max_slot_wal_keep_size.
```typescript
import { Client } from 'pg';

export interface ReplicationSlotConfig {
  slotName: string;
  publicationName: string;
  primaryConnString: string;
  maxSlotWalKeepSizeMb?: number;
  logicalDecodingWorkMemMb?: number;
}

export async function setupLogicalReplication(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  const maxWalMb = config.maxSlotWalKeepSizeMb ?? 8192; // 8GB cap
  const decodingMemMb = config.logicalDecodingWorkMemMb ?? 128; // 128MB isolated decoding buffer

  // 1. Ensure WAL retention and decoding work mem bounds are configured
  await client.query(`SET max_slot_wal_keep_size = '${maxWalMb}MB';`);
  await client.query(`SET logical_decoding_work_mem = '${decodingMemMb}MB';`);

  // 2. PG 17: Provision failover-capable slot synced with physical standbys
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       $1,
       'pgoutput',
       false, -- temporary = false
       false, -- two_phase = false
       true   -- failover = true (PostgreSQL 17 invariant)
     );`,
    [config.slotName]
  );

  // 3. Create publication explicitly scoped
  await client.query(`CREATE PUBLICATION ${config.publicationName} FOR ALL TABLES;`);

  // 4. Create subscription enabling parallel streaming to eliminate memory thrash
  await client.query(`
    CREATE SUBSCRIPTION app_sub
    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 Failover Slot Synchronization & Buffer Tuning Invariants

PostgreSQL 17 Failover Slot Synchronization & Buffer Tuning Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces PostgreSQL 17 failover-enabled logical replication slot configurations and validates synchronized standby slots to prevent replication invalidation upon node promotion. Guarantees memory safety by decoupling logical decoding allocations from shared_buffers, tuning logical_decoding_work_mem to prevent disk spilling, and setting max_slot_wal_keep_size boundaries. 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 failover-disabled logical slots and unbounded logical memory allocation leading to failover data loss and shared_buffers eviction storms 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 failover-disabled logical slots and unbounded logical memory allocation leading to failover data loss and shared_buffers eviction stormsCritical
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` and verify synchronization against `synchronized_standby_slots` in PostgreSQL 17 clusters.

Engineers MUST ALWAYS provision logical replication slots with `failover => true` and verify synchronization against `synchronized_standby_slots` in PostgreSQL 17 clusters.

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 NOT allow logical replication subscriptions to use default blocking streaming

Engineers MUST NOT allow logical replication subscriptions to use default blocking streaming; subscriptions MUST specify `streaming = 'parallel'` or `streaming = 'on'` to avoid local spool thrashing.

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 MUST ALWAYS define an explicit `max_slot_wal_keep_size` on primary instances to avoid disk exhaustion caused by stale or disconnected logical slots.

Services MUST ALWAYS define an explicit `max_slot_wal_keep_size` on primary instances to avoid disk exhaustion caused by stale or disconnected logical slots.

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 set `logical_decoding_work_mem` within bounds (minimum 64MB, maximum 1GB depending on instance RAM) to isolate logical decoding allocations from `shared_buffers`.

Engineers MUST ALWAYS set `logical_decoding_work_mem` within bounds (minimum 64MB, maximum 1GB depending on instance RAM) to isolate logical decoding allocations from `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

Components NEVER execute raw DDL drops on logical replication slots without inspecting `pg_replication_slots.conflicting` and issuing proper graceful subscriber detach procedures.

Components NEVER execute raw DDL drops on logical replication slots without inspecting `pg_replication_slots.conflicting` and issuing proper graceful subscriber detach procedures.

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

Enforces PostgreSQL 17 failover-enabled logical replication slot configurations and validates synchronized standby slots to prevent replication invalidation upon node promotion. Guarantees memory safety by decoupling logical decoding allocations from shared_buffers, tuning logical_decoding_work_mem to prevent disk spilling, and setting max_slot_wal_keep_size boundaries. 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 failover-disabled logical slots and unbounded logical memory allocation leading to failover data loss and shared_buffers eviction storms) 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