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

Postgres 17 Logical Replication Sequence Alignment and Failover Guardrail

Postgres 17 logical replication replicates DML changes but completely omits continuous sequence state transitions. During high-throughput cross-region failovers with parallel apply workers, promoted subscriber nodes maintain stale sequence values, inevitably triggering silent duplicate key collisions on auto-incrementing surrogate keys unless explicit synchronization barriers and deterministic sequence reservation blocks are enforced.

Prohibited Anti-Pattern: Unsynchronized Sequence Failover Leading to Primary Key Duplicate Value Collisions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Sequence Alignment and Failover Guardrail - Postgres 17 logical replication replicates DML changes but completely omits continuous sequence state transitions. During high-throughput cross-region failovers with parallel apply workers, promoted subscriber nodes maintain stale sequence values, inevitably triggering silent duplicate key collisions on auto-incrementing surrogate keys unless explicit synchronization barriers and deterministic sequence reservation blocks are enforced.
globs: src/database/**/*.ts, src/infra/**/*.ts, src/migrations/**/*.sql, src/services/failover/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-sequence-alignment-invariant"
---

# Postgres 17 Logical Replication Sequence Alignment and Failover Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Sequence Failover Leading to Primary Key Duplicate Value Collisions

## System Constraints
You are a Principal Database Reliability Engineer and Distributed Systems Architect enforcing the Postgres 17 Logical Replication Sequence Alignment Invariant. Mandate that logical replication setups strictly avoid uncoordinated sequence consumption across regions. Require deterministic sequence padding, systematic synchronization queries prior to subscriber promotion, or the adoption of non-colliding surrogate key strategies (e.g., UUIDv7 or composite node-offset sequences). Disallow any automated promotion workflow that does not explicitly execute transactional sequence state reconciliation across all schema catalogs.

## Strict Guidelines
- Engineers MUST ALWAYS synchronize sequence counters via explicit `SELECT setval(seq, (SELECT max(col) FROM tbl) + PADDING)` procedures prior to promoting a logical replication subscriber to primary.
- Engineers MUST NOT rely on Postgres 17 native logical replication or parallel apply workers to propagate sequence increments or `nextval()` calls automatically.
- Code SHOULD enforce UUIDv7, ULID, or distributed Snowflake generators over standard serial/identity BIGINT sequences for tables replicated cross-region to eliminate single-point sequence divergence.
- Services MUST execute a zero-write lock or wait for `pg_replication_origin_progress()` drain before promoting the subscriber and realigning sequence thresholds during planned switchovers.
- Failover orchestrators NEVER route write traffic to a promoted subscriber until sequence verification queries confirm all local sequence `last_value` counters exceed current maximum primary values plus safety buffers.

## Bad vs Good Implementations
### Unsafe Native Failover vs. Deterministic Sequence Realignment Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: PostgreSQL 17 logical replication does not stream sequence counter increments. Dropping the subscription and pointing write traffic to the subscriber immediately causes primary key collisions on the first write because the subscriber's sequence values are pinned to the initial snapshot value.
```typescript
import { Client } from 'pg';

export async function promoteSubscriberUnsafe(subscriberClient: Client): Promise<void> {
  // Anti-Pattern: Promoting logical subscriber without sequence synchronization.
  // Logical replication in PG17 does NOT replicate nextval() sequence mutations.
  await subscriberClient.query('ALTER SUBSCRIPTION regional_sub DISABLE;');
  await subscriberClient.query('ALTER SUBSCRIPTION regional_sub SET (slot_name = NONE);');
  await subscriberClient.query('DROP SUBSCRIPTION regional_sub;');
  
  // Any subsequent INSERT into tables with BIGINT GENERATED ALWAYS AS IDENTITY
  // or SERIAL will reuse old sequence counters and throw duplicate key violations (23505).
  console.log('Subscriber promoted. Ready for write traffic.');
}
```

#### Production Standard (Correct)
> **Standard**: Discovers all system-catalog-backed identity and serial sequences, extracts the current maximum column value committed via the parallel apply workers, and resets `setval` with an intentional padding buffer within a unified promotion boundary before admitting inbound transactions.
```typescript
import { Client } from 'pg';

interface SequenceAlignmentConfig {
  paddingBuffer: bigint;
}

export async function promoteSubscriberWithSequenceBarrier(
  subscriberClient: Client,
  config: SequenceAlignmentConfig = { paddingBuffer: 100000n }
): Promise<void> {
  // 1. Transactionally isolate sequence realignment during promotion barrier
  await subscriberClient.query('BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;');

  try {
    // Detach replication subscription
    await subscriberClient.query('ALTER SUBSCRIPTION regional_sub DISABLE;');
    await subscriberClient.query('ALTER SUBSCRIPTION regional_sub SET (slot_name = NONE);');
    await subscriberClient.query('DROP SUBSCRIPTION regional_sub;');

    // 2. Discover all identity/serial sequences tied to schema tables
    const sequenceQuery = `
      SELECT 
        s.relname AS sequence_name,
        n.nspname AS schema_name,
        t.relname AS table_name,
        a.attname AS column_name
      FROM pg_class s
      JOIN pg_namespace n ON n.oid = s.relnamespace
      JOIN pg_depend d ON d.objid = s.oid AND d.classid = 'pg_class'::regclass
      JOIN pg_class t ON t.oid = d.refobjid
      JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.refobjsubid
      WHERE s.relkind = 'S'
        AND n.nspname NOT IN ('pg_catalog', 'information_schema');
    `;

    const sequences = await subscriberClient.query(sequenceQuery);

    // 3. Realign each sequence beyond the current maximum existing ID + safety buffer
    for (const row of sequences.rows) {
      const fqTable = `"${row.schema_name}"."${row.table_name}"`;
      const fqSeq = `"${row.schema_name}"."${row.sequence_name}"`;
      const col = `"${row.column_name}"`;

      const maxQuery = `SELECT COALESCE(MAX(${col}), 0)::bigint AS current_max FROM ${fqTable};`;
      const { rows: maxRows } = await subscriberClient.query(maxQuery);
      const currentMax = BigInt(maxRows[0].current_max);
      const newTarget = currentMax + config.paddingBuffer;

      await subscriberClient.query(
        'SELECT setval($1::regclass, $2::bigint, true);',
        [fqSeq, newTarget.toString()]
      );
    }

    await subscriberClient.query('COMMIT;');
  } catch (error) {
    await subscriberClient.query('ROLLBACK;');
    throw new Error(`Subscriber promotion halted: Sequence alignment failed: ${error}`);
  }
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Logical Replication Sequence Alignment and Failover Guardrail

Postgres 17 Logical Replication Sequence Alignment and Failover Guardrail defines an industrial-grade behavioral standard for backend engineering. Postgres 17 logical replication replicates DML changes but completely omits continuous sequence state transitions. During high-throughput cross-region failovers with parallel apply workers, promoted subscriber nodes maintain stale sequence values, inevitably triggering silent duplicate key collisions on auto-incrementing surrogate keys unless explicit synchronization barriers and deterministic sequence reservation blocks are enforced. 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 Sequence Failover Leading to Primary Key Duplicate Value Collisions 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 Sequence Failover Leading to Primary Key Duplicate Value CollisionsCritical
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 synchronize sequence counters via explicit `SELECT setval(seq, (SELECT max(col) FROM tbl) + PADDING)` procedures prior to promoting a logical replication subscriber to primary.

Engineers MUST ALWAYS synchronize sequence counters via explicit `SELECT setval(seq, (SELECT max(col) FROM tbl) + PADDING)` procedures prior to promoting a logical replication subscriber to primary.

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 rely on Postgres 17 native logical replication or parallel apply workers to propagate sequence increments or `nextval()` calls automatically.

Engineers MUST NOT rely on Postgres 17 native logical replication or parallel apply workers to propagate sequence increments or `nextval()` calls automatically.

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

Code SHOULD enforce UUIDv7, ULID, or distributed Snowflake generators over standard serial/identity BIGINT sequences for tables replicated cross-region to eliminate single-point sequence divergence.

Code SHOULD enforce UUIDv7, ULID, or distributed Snowflake generators over standard serial/identity BIGINT sequences for tables replicated cross-region to eliminate single-point sequence divergence.

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 MUST execute a zero-write lock or wait for `pg_replication_origin_progress()` drain before promoting the subscriber and realigning sequence thresholds during planned switchovers.

Services MUST execute a zero-write lock or wait for `pg_replication_origin_progress()` drain before promoting the subscriber and realigning sequence thresholds during planned switchovers.

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

Failover orchestrators NEVER route write traffic to a promoted subscriber until sequence verification queries confirm all local sequence `last_value` counters exceed current maximum primary values plus safety buffers.

Failover orchestrators NEVER route write traffic to a promoted subscriber until sequence verification queries confirm all local sequence `last_value` counters exceed current maximum primary values plus safety 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.
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 Sequence Alignment and Failover Guardrail critical for AI coding assistants?

Postgres 17 logical replication replicates DML changes but completely omits continuous sequence state transitions. During high-throughput cross-region failovers with parallel apply workers, promoted subscriber nodes maintain stale sequence values, inevitably triggering silent duplicate key collisions on auto-incrementing surrogate keys unless explicit synchronization barriers and deterministic sequence reservation blocks are enforced. 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 Sequence Failover Leading to Primary Key Duplicate Value Collisions) 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