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

PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Sizing Guardrails

Enforces strict production standards for PostgreSQL 17 logical replication topologies. Mandates the use of PG17 native failover-enabled logical slots, parallel streaming decoding, bounded WAL retention limits, and isolated logical_decoding_work_mem sizing to avoid primary node WAL disk exhaustion and catastrophic split-brain during standby promotion.

Prohibited Anti-Pattern: Unsynchronized Logical Replication Slots with Unbounded WAL Retention and Unstreamed Large Transactions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Sizing Guardrails - Enforces strict production standards for PostgreSQL 17 logical replication topologies. Mandates the use of PG17 native failover-enabled logical slots, parallel streaming decoding, bounded WAL retention limits, and isolated logical_decoding_work_mem sizing to avoid primary node WAL disk exhaustion and catastrophic split-brain during standby promotion.
globs: src/**/*.ts, src/database/**/*.ts, migrations/**/*.sql, infra/**/*.tf, deploy/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-memory-failover-invariants"
---

# PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Sizing Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Replication Slots with Unbounded WAL Retention and Unstreamed Large Transactions

## System Constraints
You are a Principal Database Reliability Engineer enforcing PostgreSQL 17 Logical Replication and Memory Buffer standards. Mandate failover-enabled slots on subscriptions, verify standby slot synchronization via pg_sync_replication_slots, bound max_slot_wal_keep_size to avoid disk filling, configure streaming decoding to parallel, and isolate logical_decoding_work_mem from shared_buffers.

## Strict Guidelines
- Engineers MUST ALWAYS enable 'failover = true' when creating logical subscriptions or slots in PostgreSQL 17 to ensure logical slots synchronize to physical standbys.
- Engineers MUST ALWAYS specify streaming mode ('streaming = parallel' or 'streaming = on') on high-throughput subscriptions to prevent transactions from consuming excessive memory buffers or spilling unmanaged gigabytes to disk.
- Engineers MUST NEVER leave 'max_slot_wal_keep_size' set to -1 (unlimited) on instances hosting logical replication slots; it MUST be strictly bounded (e.g., 64GB-256GB) to prevent inactive consumers from causing primary PANIC due to full disk.
- Services managing logical replication slot provisioning MUST query pg_replication_slots to verify 'failover = true' and 'sync_state' before acknowledging replica health.
- Database configurations MUST isolate 'logical_decoding_work_mem' (typically 64MB to 256MB) while preventing aggressive over-allocation that starves PostgreSQL's 'shared_buffers' and kernel OS page cache.
- Standby sync workers MUST monitor standby_slot_names on the primary node to ensure physical replicas advance past logical slot LSN positions before WAL pruning occurs.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Provisioning and Health Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits PostgreSQL 17's native 'failover = true' parameter on the subscription, leaving the slot un-synchronized to physical standbys. Leaves streaming mode disabled, forcing large transactions to buffer in disk/memory, and leaves max_slot_wal_keep_size unbounded, which risks filling the primary node's storage if the consumer lags.
```typescript
import { Client } from 'pg';

export async function setupSubscription(client: Client): Promise<void> {
  // DANGEROUS: Missing PG17 failover slot enablement, missing streaming mode.
  // If the publisher's primary fails over to a physical standby,
  // this logical slot will be permanently lost, corrupting the pipeline.
  await client.query(`
    CREATE SUBSCRIPTION sub_order_events
    CONNECTION 'host=db-primary port=5432 user=rep_user dbname=orders'
    PUBLICATION pub_order_events;
  `);

  // DANGEROUS: Leaves WAL retention unbounded (-1),
  // risking primary disk saturation if subscriber disconnects.
  await client.query(`ALTER SYSTEM SET max_slot_wal_keep_size = -1;`);
}
```

#### Production Standard (Correct)
> **Standard**: Leverages PostgreSQL 17 features: sets 'failover = true' so physical standbys synchronize the slot metadata, enables 'streaming = parallel' for high-throughput decoding, bounds max_slot_wal_keep_size to 64GB to prevent WAL accumulation catastrophes, and validates the slot status against pg_replication_slots.
```typescript
import { Client } from 'pg';

export async function setupSubscription(client: Client): Promise<void> {
  // Enforce bounded WAL retention on the publisher/subscriber nodes to prevent primary disk crash
  await client.query(`ALTER SYSTEM SET max_slot_wal_keep_size = '64GB';`);
  await client.query(`ALTER SYSTEM SET logical_decoding_work_mem = '128MB';`);
  await client.query(`SELECT pg_reload_conf();`);

  // PG17 Native Failover Subscription with Parallel Streaming
  await client.query(`
    CREATE SUBSCRIPTION sub_order_events
    CONNECTION 'host=db-primary port=5432 user=rep_user dbname=orders'
    PUBLICATION pub_order_events
    WITH (
      copy_data = true,
      streaming = 'parallel',
      failover = true
    );
  `);

  // Validation assertion: verify the slot was created with failover capability in PG17 catalog
  const { rows } = await client.query<{
    slot_name: string;
    failover: boolean;
    streaming: string;
  }>(`
    SELECT slot_name, failover, streaming
    FROM pg_replication_slots
    WHERE slot_name = 'sub_order_events';
  `);

  if (!rows[0] || !rows[0].failover) {
    throw new Error(
      'Invariant Violation: Replication slot sub_order_events must exist with failover = true for PG17 high availability.'
    );
  }
}
```

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, Streaming Decoding, and Memory Sizing Guardrails

PostgreSQL 17 Failover Slot Synchronization, Streaming Decoding, and Memory Sizing Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces strict production standards for PostgreSQL 17 logical replication topologies. Mandates the use of PG17 native failover-enabled logical slots, parallel streaming decoding, bounded WAL retention limits, and isolated logical_decoding_work_mem sizing to avoid primary node WAL disk exhaustion and catastrophic split-brain during standby promotion. 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 Logical Replication Slots with Unbounded WAL Retention and Unstreamed Large Transactions 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 Logical Replication Slots with Unbounded WAL Retention and Unstreamed Large TransactionsCritical
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 'failover = true' when creating logical subscriptions or slots in PostgreSQL 17 to ensure logical slots synchronize to physical standbys.

Engineers MUST ALWAYS enable 'failover = true' when creating logical subscriptions or slots in PostgreSQL 17 to ensure logical slots synchronize to physical standbys.

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 specify streaming mode ('streaming = parallel' or 'streaming = on') on high-throughput subscriptions to prevent transactions from consuming excessive memory buffers or spilling unmanaged gigabytes to disk.

Engineers MUST ALWAYS specify streaming mode ('streaming = parallel' or 'streaming = on') on high-throughput subscriptions to prevent transactions from consuming excessive memory buffers or spilling unmanaged gigabytes 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.
3

Engineers MUST NEVER leave 'max_slot_wal_keep_size' set to -1 (unlimited) on instances hosting logical replication slots

Engineers MUST NEVER leave 'max_slot_wal_keep_size' set to -1 (unlimited) on instances hosting logical replication slots; it MUST be strictly bounded (e.g., 64GB-256GB) to prevent inactive consumers from causing primary PANIC due to full 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 managing logical replication slot provisioning MUST query pg_replication_slots to verify 'failover = true' and 'sync_state' before acknowledging replica health.

Services managing logical replication slot provisioning MUST query pg_replication_slots to verify 'failover = true' and 'sync_state' before acknowledging replica health.

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

Database configurations MUST isolate 'logical_decoding_work_mem' (typically 64MB to 256MB) while preventing aggressive over-allocation that starves PostgreSQL's 'shared_buffers' and kernel OS page cache.

Database configurations MUST isolate 'logical_decoding_work_mem' (typically 64MB to 256MB) while preventing aggressive over-allocation that starves PostgreSQL's 'shared_buffers' and kernel OS page cache.

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

Standby sync workers MUST monitor standby_slot_names on the primary node to ensure physical replicas advance past logical slot LSN positions before WAL pruning occurs.

Standby sync workers MUST monitor standby_slot_names on the primary node to ensure physical replicas advance past logical slot LSN positions before WAL pruning occurs.

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, Streaming Decoding, and Memory Sizing Guardrails critical for AI coding assistants?

Enforces strict production standards for PostgreSQL 17 logical replication topologies. Mandates the use of PG17 native failover-enabled logical slots, parallel streaming decoding, bounded WAL retention limits, and isolated logical_decoding_work_mem sizing to avoid primary node WAL disk exhaustion and catastrophic split-brain during standby promotion. 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 Logical Replication Slots with Unbounded WAL Retention and Unstreamed Large Transactions) 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