This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-failover-slot-sync-guardrail

Postgres 17 Logical Replication Slot Synchronization and Outbox Consumer Guardrail

Enforces failover-safe logical replication slot synchronization introduced in PostgreSQL 17 to prevent message re-ingestion, double processing, and consumer drift across High Availability (HA) switchovers. Mandates `failover = true` on logical slots, configuration of `synchronized_standby_slots` on the primary, and explicit LSN confirmation barriers before publishing outbox payloads.

Prohibited Anti-Pattern: Unsynchronized Logical Slots Causing Replay Storms and Duplicate Outbox Events Post-HA Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Slot Synchronization and Outbox Consumer Guardrail - Enforces failover-safe logical replication slot synchronization introduced in PostgreSQL 17 to prevent message re-ingestion, double processing, and consumer drift across High Availability (HA) switchovers. Mandates `failover = true` on logical slots, configuration of `synchronized_standby_slots` on the primary, and explicit LSN confirmation barriers before publishing outbox payloads.
globs: src/**/*.ts, src/database/**/*.ts, src/outbox/**/*.ts, migrations/**/*.sql, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-sync-guardrail"
---

# Postgres 17 Logical Replication Slot Synchronization and Outbox Consumer Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots Causing Replay Storms and Duplicate Outbox Events Post-HA Failover

## System Constraints
You are a Principal Database Architect and Distributed Systems Engineer enforcing Postgres 17 Failover Slot Synchronization invariants. Your objective is to eliminate split-brain consumers, duplicate event streaming, and outbox publisher drift during HA failover events. Ensure that all transactional outbox setups and Change Data Capture (CDC) pipelines strictly verify physical replication slot sync, pass `failover: true` during slot creation, and account for standby catch-up lag prior to message acknowledgment.

## Strict Guidelines
- Engineers MUST ALWAYS configure `failover: true` when provisioning logical replication slots on Postgres 17+ (e.g., via `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)`).
- Engineers MUST configure `synchronized_standby_slots` on the primary instance to reference all physical standby nodes holding failover slots.
- Services MUST NOT read from or advance logical slots on newly promoted standbys until validating that `pg_replication_slots.sync_state` transitions from 's' (syncing) to 'i' (ideal/idle/independent).
- Code SHOULD verify the local slot confirmed flush LSN matches or exceeds the pre-failover publisher high-water mark before acknowledging events to external brokers.
- Components NEVER assume standard WAL consumer idempotency keys replace physical slot synchronization, as slot rewinds under non-synchronized standbys cause massive replay cascades.

## Bad vs Good Implementations
### Configuring Postgres 17 Failover-Safe Replication Slot and Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical slot without the Postgres 17 `failover` parameter causes the slot to remain local to the primary. During an HA failover, the newly promoted primary lacks this slot, forcing operators to recreate it from a lower LSN and triggering unbounded duplicate event delivery across the outbox infrastructure.
```typescript
import { Client } from 'pg';

export async function initConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Pre-PG17 syntax or missing failover parameter;
  // standby will discard slot or leave it un-synchronized upon failover,
  // causing a full replay of WAL or immediate consumer crash.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly invokes `pg_create_logical_replication_slot` with `failover = true`. This instructs Postgres 17 to mirror slot progression to physical standbys specified in `synchronized_standby_slots`, ensuring seamless replication continuity without rewinds upon HA switchover.
```typescript
import { Client } from 'pg';

export async function initConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Invariant: Postgres 17 introduced the 5th boolean parameter 'failover'.
  // 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]
  );

  // Validate slot attributes and physical sync readiness
  const { rows } = await client.query(
    `SELECT slot_name, failover, synced 
     FROM pg_replication_slots 
     WHERE slot_name = $1;`,
    [slotName]
  );

  if (!rows[0]?.failover) {
    throw new Error(`Failed to initialize slot ${slotName} with failover support.`);
  }
}
```

### HA Promotion Pre-Flight Check for CDC / Outbox Consumers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HA switchover happens, consuming from an un-promoted standby or a promoted standby whose sync worker has not stabilized the slot state can cause replication crashes or duplicate data streaming due to unaligned confirmed flush LSNs.
```typescript
import { Client } from 'pg';

export async function resumeLogicalConsumption(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Blindly starts consumption on a newly promoted replica without
  // checking if slot synchronization has stabilized or if the node is still in recovery.
  const streamQuery = `START_REPLICATION SLOT ${slotName} LOGICAL 0/0`;
  await client.query(streamQuery);
}
```

#### Production Standard (Correct)
> **Standard**: Validates that the database has exited recovery, verifies that the slot was properly migrated via Postgres 17 slot sync (`synced` transitions to false once local on the promoted primary), and streams starting explicitly from the validated `confirmed_flush_lsn`.
```typescript
import { Client } from 'pg';

export async function resumeLogicalConsumption(client: Client, slotName: string): Promise<void> {
  // Ensure node is no longer in recovery
  const recoveryRes = await client.query('SELECT pg_is_in_recovery() AS in_recovery;');
  if (recoveryRes.rows[0].in_recovery) {
    throw new Error('Target node is still in standby recovery mode. Cannot initiate consumer stream.');
  }

  // Validate slot existence, failover status, and confirmed flush LSN
  const slotRes = await client.query(
    `SELECT slot_name, failover, synced, confirmed_flush_lsn 
     FROM pg_replication_slots 
     WHERE slot_name = $1;`,
    [slotName]
  );

  const slot = slotRes.rows[0];
  if (!slot) {
    throw new Error(`Replication slot ${slotName} not found on promoted primary.`);
  }

  if (slot.synced) {
    throw new Error(`Slot ${slotName} is still marked as synced. Slot synchronization must complete before promotion.`);
  }

  const streamQuery = `START_REPLICATION SLOT ${slotName} LOGICAL ${slot.confirmed_flush_lsn}`;
  await client.query(streamQuery);
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Logical Replication Slot Synchronization and Outbox Consumer Guardrail

Postgres 17 Logical Replication Slot Synchronization and Outbox Consumer Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces failover-safe logical replication slot synchronization introduced in PostgreSQL 17 to prevent message re-ingestion, double processing, and consumer drift across High Availability (HA) switchovers. Mandates `failover = true` on logical slots, configuration of `synchronized_standby_slots` on the primary, and explicit LSN confirmation barriers before publishing outbox payloads. 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 Slots Causing Replay Storms and Duplicate Outbox Events Post-HA Failover 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 Slots Causing Replay Storms and Duplicate Outbox Events Post-HA FailoverCritical
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 configure `failover

Engineers MUST ALWAYS configure `failover: true` when provisioning logical replication slots on Postgres 17+ (e.g., via `pg_create_logical_replication_slot(slot_name, plugin, 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 configure `synchronized_standby_slots` on the primary instance to reference all physical standby nodes holding failover slots.

Engineers MUST configure `synchronized_standby_slots` on the primary instance to reference all physical standby nodes holding failover 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.
3

Services MUST NOT read from or advance logical slots on newly promoted standbys until validating that `pg_replication_slots.sync_state` transitions from 's' (syncing) to 'i' (ideal/idle/independent).

Services MUST NOT read from or advance logical slots on newly promoted standbys until validating that `pg_replication_slots.sync_state` transitions from 's' (syncing) to 'i' (ideal/idle/independent).

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

Code SHOULD verify the local slot confirmed flush LSN matches or exceeds the pre-failover publisher high-water mark before acknowledging events to external brokers.

Code SHOULD verify the local slot confirmed flush LSN matches or exceeds the pre-failover publisher high-water mark before acknowledging events to external brokers.

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 assume standard WAL consumer idempotency keys replace physical slot synchronization, as slot rewinds under non-synchronized standbys cause massive replay cascades.

Components NEVER assume standard WAL consumer idempotency keys replace physical slot synchronization, as slot rewinds under non-synchronized standbys cause massive replay cascades.

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 Postgres 17 Logical Replication Slot Synchronization and Outbox Consumer Guardrail critical for AI coding assistants?

Enforces failover-safe logical replication slot synchronization introduced in PostgreSQL 17 to prevent message re-ingestion, double processing, and consumer drift across High Availability (HA) switchovers. Mandates `failover = true` on logical slots, configuration of `synchronized_standby_slots` on the primary, and explicit LSN confirmation barriers before publishing outbox payloads. 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 Slots Causing Replay Storms and Duplicate Outbox Events Post-HA Failover) 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

Postgres