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

Postgres 17 Failover Slot Synchronization Guardrail for CDC Pipelines

Mandates the use of Postgres 17 logical failover replication slots and synchronized standby slot topologies for all streaming Change Data Capture (CDC) architectures. Eliminates WAL retention truncation, stream corruption, and duplicate event storms across Kafka Connect and Debezium during primary-replica failovers.

Prohibited Anti-Pattern: Creating Unsynchronized Logical Replication Slots Vulnerable to WAL Truncation During Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover Slot Synchronization Guardrail for CDC Pipelines - Mandates the use of Postgres 17 logical failover replication slots and synchronized standby slot topologies for all streaming Change Data Capture (CDC) architectures. Eliminates WAL retention truncation, stream corruption, and duplicate event storms across Kafka Connect and Debezium during primary-replica failovers.
globs: src/**/*.{ts,js}, infra/**/*.{tf,yaml,yml}, migrations/**/*.sql, config/**/*.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-cdc-failover-slot-sync"
---

# Postgres 17 Failover Slot Synchronization Guardrail for CDC Pipelines

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Unsynchronized Logical Replication Slots Vulnerable to WAL Truncation During Failover

## System Constraints
You are a Principal Software Architect enforcing Postgres 17 Failover Slot Synchronization standards for mission-critical CDC and event streaming backends. Postgres 17 introduces native logical slot synchronization to physical standbys. Never allow logical slots to be provisioned without failover support enabled or without defining synchronized_standby_slots on the primary. Prevent CDC pipelines (Debezium, Kafka Connect) from data loss, duplicate re-streaming, or invalidation errors (e.g., 58P01 missing WAL) during automated database failovers.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` on PostgreSQL 17+ (`SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, false, true)` or via modern connector drivers).
- Engineers MUST configure `synchronized_standby_slots` on the primary instance to include the physical replication slots of all failover candidate standbys.
- Engineers MUST NOT allow logical replication slots to advance ahead of standbys' received LSN positions, preventing unrecoverable stream divergence when a standby is promoted.
- Physical standby instances MUST enable `sync_replication_slots = true` in postgresql.conf to activate the standby background slot synchronization worker.
- CDC consumer reconnection logic MUST verify `sync_state = 'ready'` or query `pg_replication_slots` on newly promoted primaries before resuming consumer streams.
- Services MUST gracefully back off and avoid dropping or blindly recreating replication slots when a failover is detected, preserving the high-water LSN mark.

## Bad vs Good Implementations
### Configuring Postgres 17 Replication Slot Provisioning & Validation in TypeScript

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical slot without the Postgres 17 `failover` parameter defaults to `failover => false`. The slot will not be mirrored to physical standbys, leading to complete stream failure or data corruption upon node failover.
```typescript
import { Client } from 'pg';

export async function initCdcReplicationSlot(client: Client, slotName: string): Promise<void> {
  // VULNERABLE: Postgres 16- legacy creation without failover=true flag.
  // If primary fails over, the standby does not have this logical slot synchronized.
  // Debezium/Kafka Connect will crash with 58P01 (WAL segment removed) or re-stream from epoch.
  const query = `
    SELECT slot_name, confirmed_flush_lsn
    FROM pg_create_logical_replication_slot($1, 'pgoutput');
  `;
  await client.query(query, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly provisions the slot with `failover => true` and ensures `synchronized_standby_slots` is active. This guarantees the slot's LSN progress is synchronized across standbys, allowing CDC consumers to reconnect seamlessly without message loss or invalidation.
```typescript
import { Client } from 'pg';

export async function initCdcReplicationSlot(client: Client, slotName: string): Promise<void> {
  // 1. Verify PostgreSQL engine version >= 17
  const versionRes = await client.query('SHOW server_version_num;');
  const versionNum = parseInt(versionRes.rows[0].server_version_num, 10);
  if (versionNum < 170000) {
    throw new Error(`Postgres 17+ required for failover slots. Found version_num: ${versionNum}`);
  }

  // 2. Verify synchronized_standby_slots is actively configured on primary
  const syncSlotsRes = await client.query('SHOW synchronized_standby_slots;');
  const syncSlots = syncSlotsRes.rows[0].synchronized_standby_slots;
  if (!syncSlots || syncSlots.trim() === '') {
    throw new Error('CRITICAL: synchronized_standby_slots must be configured on primary for CDC reliability.');
  }

  // 3. Create logical replication slot with failover set to true
  const createSlotQuery = `
    SELECT slot_name, lsn
    FROM pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => 'pgoutput',
      temporary => false,
      twophase => true,
      failover => true
    );
  `;
  await client.query(createSlotQuery, [slotName]);
}
```

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: Postgres 17 Failover Slot Synchronization Guardrail for CDC Pipelines

Postgres 17 Failover Slot Synchronization Guardrail for CDC Pipelines defines an industrial-grade behavioral standard for backend engineering. Mandates the use of Postgres 17 logical failover replication slots and synchronized standby slot topologies for all streaming Change Data Capture (CDC) architectures. Eliminates WAL retention truncation, stream corruption, and duplicate event storms across Kafka Connect and Debezium during primary-replica failovers. 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 Unsynchronized Logical Replication Slots Vulnerable to WAL Truncation During 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 DriftCreating Unsynchronized Logical Replication Slots Vulnerable to WAL Truncation During 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 create logical replication slots with `failover => true` on PostgreSQL 17+ (`SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, false, true)` or via modern connector drivers).

Engineers MUST ALWAYS create logical replication slots with `failover => true` on PostgreSQL 17+ (`SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, false, true)` or via modern connector drivers).

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 include the physical replication slots of all failover candidate standbys.

Engineers MUST configure `synchronized_standby_slots` on the primary instance to include the physical replication slots of all failover candidate 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.
3

Engineers MUST NOT allow logical replication slots to advance ahead of standbys' received LSN positions, preventing unrecoverable stream divergence when a standby is promoted.

Engineers MUST NOT allow logical replication slots to advance ahead of standbys' received LSN positions, preventing unrecoverable stream divergence when a standby is promoted.

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

Physical standby instances MUST enable `sync_replication_slots = true` in postgresql.conf to activate the standby background slot synchronization worker.

Physical standby instances MUST enable `sync_replication_slots = true` in postgresql.conf to activate the standby background slot synchronization worker.

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

CDC consumer reconnection logic MUST verify `sync_state = 'ready'` or query `pg_replication_slots` on newly promoted primaries before resuming consumer streams.

CDC consumer reconnection logic MUST verify `sync_state = 'ready'` or query `pg_replication_slots` on newly promoted primaries before resuming consumer streams.

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

Services MUST gracefully back off and avoid dropping or blindly recreating replication slots when a failover is detected, preserving the high-water LSN mark.

Services MUST gracefully back off and avoid dropping or blindly recreating replication slots when a failover is detected, preserving the high-water LSN mark.

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 Failover Slot Synchronization Guardrail for CDC Pipelines critical for AI coding assistants?

Mandates the use of Postgres 17 logical failover replication slots and synchronized standby slot topologies for all streaming Change Data Capture (CDC) architectures. Eliminates WAL retention truncation, stream corruption, and duplicate event storms across Kafka Connect and Debezium during primary-replica failovers. 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 Unsynchronized Logical Replication Slots Vulnerable to WAL Truncation During 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