This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-pg-createsubscriber-cutover-standard-postgres-17-pg-c-230

PostgreSQL 17 pg_createsubscriber Safe Standby Cutover Standard

Mandates deterministic pre-flight checks, LSN sync verification, replica identity assertions, and atomic slot validation when converting physical standbys into logical subscribers using PostgreSQL 17 pg_createsubscriber. Prevents silent timeline drift, replication divergence, and transaction loss during migration from streaming replication to logical replication.

Prohibited Anti-Pattern: Blind pg_createsubscriber Execution Without LSN Lag Zeroing and Replica Identity Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 pg_createsubscriber Safe Standby Cutover Standard - Mandates deterministic pre-flight checks, LSN sync verification, replica identity assertions, and atomic slot validation when converting physical standbys into logical subscribers using PostgreSQL 17 pg_createsubscriber. Prevents silent timeline drift, replication divergence, and transaction loss during migration from streaming replication to logical replication.
globs: src/**/*.{ts,js,py,sh}, scripts/**/*.{ts,js,py,sh}, infra/**/*.{ts,js,py,tf}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-pg-createsubscriber-cutover-standard-postgres-17-pg-c-230"
---

# PostgreSQL 17 pg_createsubscriber Safe Standby Cutover Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Blind pg_createsubscriber Execution Without LSN Lag Zeroing and Replica Identity Validation

## System Constraints
You are a Principal Database Reliability Engineer enforcing PostgreSQL 17 pg_createsubscriber Logical Standby Cutover standards. Convert physical streaming standbys into autonomous logical subscriber replicas with zero transaction loss, strict LSN boundary verification, publication table replica identity assertions, and fail-safe rollback barriers.

## Strict Guidelines
- Engineers MUST ALWAYS verify that 'wal_level = logical' on the source primary and that 'max_replication_slots' and 'max_logical_replication_workers' are configured appropriately prior to initiating cutover.
- Engineers MUST ALWAYS verify that every table designated for replication possesses a valid REPLICA IDENTITY (PRIMARY KEY or REPLICA IDENTITY FULL) to prevent replication termination on subsequent UPDATE/DELETE operations.
- Engineers MUST ensure replication lag is exactly zero bytes ('pg_wal_lsn_diff(pg_current_wal_lsn(), pg_last_wal_replay_lsn()) == 0') before shutting down the standby for conversion.
- Engineers MUST cleanly stop the target standby instance using 'pg_ctl stop -m fast' before invoking 'pg_createsubscriber'; the utility cannot safely mutate a running cluster's control and data files.
- Engineers MUST NOT proceed with pg_createsubscriber if uncommitted prepared transactions exist in 'pg_prepared_xacts' on either the primary or the target standby node.
- Code SHOULD verify subscription activation by polling 'pg_stat_subscription' and 'pg_subscription_rel' for state 'r' (ready) on all replicated relations before declaring cutover success.
- Services MUST retain the original physical replication slot configuration until the logical subscription establishes a valid remote replication origin LSN to ensure a safe rollback path.

## Bad vs Good Implementations
### TypeScript Standby Cutover Orchestrator with Deterministic Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to verify wal_level, prepared transactions, or replica identities on target tables. Standby is not cleanly stopped, and replication lag is not verified to be zero, risking silent timeline divergence and permanent replication slot corruption.
```typescript
import { execSync } from 'child_process';
import { Client } from 'pg';

// ANTI-PATTERN: Naively calling pg_createsubscriber without pre-flight validation,
// LSN lag zeroing, replica identity verification, or standby shutdown management.
export async function cutoverToSubscriber(primaryConn: string, standbyDataDir: string, dbName: string) {
  console.log('Initiating standby cutover...');
  
  // DANGEROUS: Running pg_createsubscriber directly against a live or unsynced standby
  // will corrupt replica state or fail if lag > 0 or uncommitted prepared transactions exist.
  execSync(`pg_createsubscriber -D ${standbyDataDir} -P "${primaryConn}" -d ${dbName} --publication=pub_prod --subscription=sub_prod`, {
    stdio: 'inherit'
  });

  console.log('Cutover completed.');
}
```

#### Production Standard (Correct)
> **Standard**: Implements comprehensive pre-flight verification: checks wal_level=logical, verifies zero prepared transactions, audits tables for valid primary keys/replica identities, validates zero LSN lag diff, stops the standby node cleanly before running pg_createsubscriber, and restarts the node safely.
```typescript
import { execSync } from 'child_process';
import { Client } from 'pg';

interface CutoverConfig {
  primaryConnString: string;
  standbyConnString: string;
  standbyDataDir: string;
  databaseName: string;
  publicationName: string;
  subscriptionName: string;
}

export async function executeSafeStandbyCutover(config: CutoverConfig): Promise<void> {
  const primary = new Client({ connectionString: config.primaryConnString });
  const standby = new Client({ connectionString: config.standbyConnString });
  await primary.connect();
  await standby.connect();

  try {
    // 1. Verify primary wal_level is set to logical
    const walRes = await primary.query<{ wal_level: string }>("SHOW wal_level;");
    if (walRes.rows[0]?.wal_level !== 'logical') {
      throw new Error("Pre-flight failed: Publisher 'wal_level' must be 'logical'.");
    }

    // 2. Ensure no pending prepared 2PC transactions exist
    const prepRes = await primary.query<{ count: string }>("SELECT count(*) FROM pg_prepared_xacts;");
    if (parseInt(prepRes.rows[0]?.count ?? '0', 10) > 0) {
      throw new Error('Pre-flight failed: Pending prepared transactions detected.');
    }

    // 3. Ensure all non-system tables have a valid replica identity
    const identRes = await primary.query<{
      relname: string;
      relreplident: string;
    }>(
      `SELECT c.relname, c.relreplident
       FROM pg_class c
       JOIN pg_namespace n ON n.oid = c.relnamespace
       WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
         AND c.relkind = 'r'
         AND c.relreplident = 'd'
         AND NOT EXISTS (
           SELECT 1 FROM pg_index i 
           WHERE i.indrelid = c.oid AND i.indisprimary
         );`
    );
    if (identRes.rows.length > 0) {
      const invalidTables = identRes.rows.map(r => r.relname).join(', ');
      throw new Error(`Pre-flight failed: Tables lack valid REPLICA IDENTITY: ${invalidTables}`);
    }

    // 4. Zero-lag synchronization assertion
    const lsnRes = await primary.query<{ current_lsn: string }>('SELECT pg_current_wal_lsn() as current_lsn;');
    const targetLsn = lsnRes.rows[0].current_lsn;
    
    const syncRes = await standby.query<{ lag_bytes: string }>(
      'SELECT pg_wal_lsn_diff($1::pg_lsn, pg_last_wal_replay_lsn()) as lag_bytes;',
      [targetLsn]
    );
    if (BigInt(syncRes.rows[0]?.lag_bytes ?? '1') !== 0n) {
      throw new Error(`Standby lag is not zero against LSN ${targetLsn}. Wait for sync before cutover.`);
    }
  } finally {
    await standby.end();
    await primary.end();
  }

  // 5. Cleanly stop standby before invoking pg_createsubscriber
  execSync(`pg_ctl -D ${config.standbyDataDir} -m fast stop`, { stdio: 'pipe' });

  // 6. Execute PostgreSQL 17 pg_createsubscriber utility
  execSync(
    `pg_createsubscriber -D ${config.standbyDataDir} \
      -P "${config.primaryConnString}" \
      -d ${config.databaseName} \
      --publication=${config.publicationName} \
      --subscription=${config.subscriptionName} \
      --verbose`,
    { stdio: 'inherit' }
  );

  // 7. Restart the newly converted subscriber instance
  execSync(`pg_ctl -D ${config.standbyDataDir} -l logfile start`, { stdio: 'pipe' });
}
```

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 pg_createsubscriber Safe Standby Cutover Standard

PostgreSQL 17 pg_createsubscriber Safe Standby Cutover Standard defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic pre-flight checks, LSN sync verification, replica identity assertions, and atomic slot validation when converting physical standbys into logical subscribers using PostgreSQL 17 pg_createsubscriber. Prevents silent timeline drift, replication divergence, and transaction loss during migration from streaming replication to logical replication. 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: Blind pg_createsubscriber Execution Without LSN Lag Zeroing and Replica Identity Validation 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 DriftBlind pg_createsubscriber Execution Without LSN Lag Zeroing and Replica Identity ValidationCritical
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 verify that 'wal_level = logical' on the source primary and that 'max_replication_slots' and 'max_logical_replication_workers' are configured appropriately prior to initiating cutover.

Engineers MUST ALWAYS verify that 'wal_level = logical' on the source primary and that 'max_replication_slots' and 'max_logical_replication_workers' are configured appropriately prior to initiating cutover.

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 verify that every table designated for replication possesses a valid REPLICA IDENTITY (PRIMARY KEY or REPLICA IDENTITY FULL) to prevent replication termination on subsequent UPDATE/DELETE operations.

Engineers MUST ALWAYS verify that every table designated for replication possesses a valid REPLICA IDENTITY (PRIMARY KEY or REPLICA IDENTITY FULL) to prevent replication termination on subsequent UPDATE/DELETE operations.

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 ensure replication lag is exactly zero bytes ('pg_wal_lsn_diff(pg_current_wal_lsn(), pg_last_wal_replay_lsn()) == 0') before shutting down the standby for conversion.

Engineers MUST ensure replication lag is exactly zero bytes ('pg_wal_lsn_diff(pg_current_wal_lsn(), pg_last_wal_replay_lsn()) == 0') before shutting down the standby for conversion.

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 cleanly stop the target standby instance using 'pg_ctl stop -m fast' before invoking 'pg_createsubscriber'

Engineers MUST cleanly stop the target standby instance using 'pg_ctl stop -m fast' before invoking 'pg_createsubscriber'; the utility cannot safely mutate a running cluster's control and data files.

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

Engineers MUST NOT proceed with pg_createsubscriber if uncommitted prepared transactions exist in 'pg_prepared_xacts' on either the primary or the target standby node.

Engineers MUST NOT proceed with pg_createsubscriber if uncommitted prepared transactions exist in 'pg_prepared_xacts' on either the primary or the target standby node.

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

Code SHOULD verify subscription activation by polling 'pg_stat_subscription' and 'pg_subscription_rel' for state 'r' (ready) on all replicated relations before declaring cutover success.

Code SHOULD verify subscription activation by polling 'pg_stat_subscription' and 'pg_subscription_rel' for state 'r' (ready) on all replicated relations before declaring cutover success.

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.
7

Services MUST retain the original physical replication slot configuration until the logical subscription establishes a valid remote replication origin LSN to ensure a safe rollback path.

Services MUST retain the original physical replication slot configuration until the logical subscription establishes a valid remote replication origin LSN to ensure a safe rollback path.

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 pg_createsubscriber Safe Standby Cutover Standard critical for AI coding assistants?

Mandates deterministic pre-flight checks, LSN sync verification, replica identity assertions, and atomic slot validation when converting physical standbys into logical subscribers using PostgreSQL 17 pg_createsubscriber. Prevents silent timeline drift, replication divergence, and transaction loss during migration from streaming replication to logical replication. 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 (Blind pg_createsubscriber Execution Without LSN Lag Zeroing and Replica Identity Validation) 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