Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Principle:2ndQuadrant Pglogical Change Application

From Leeroopedia
Knowledge Sources
Domains Database, Replication
Last Updated 2026-10-13 00:00 GMT

Overview

Process of applying decoded row-level changes (INSERT, UPDATE, DELETE) to the subscriber database using either direct heap manipulation or SQL statement execution via the Server Programming Interface.

Description

Change application is the subscriber-side counterpart of logical decoding. After the apply worker decodes protocol messages from the provider's replication stream, it must apply each row change to the local database. pglogical supports two application backends:

  • Heap API (default): Direct tuple manipulation using PostgreSQL's internal heap access methods. This bypasses SQL parsing, enables conflict detection via index scans, fires triggers, and supports multi-insert batching for throughput. Controlled by pglogical.use_spi = false (default).
  • SPI API (optional): Generates and executes SQL INSERT/UPDATE/DELETE statements via the Server Programming Interface. This is simpler and more compatible but slower, and does not support conflict resolution (requires pglogical.conflict_resolution = error). Controlled by pglogical.use_spi = true.

The apply worker reads messages in a loop using PQgetCopyData, dispatches them to the appropriate apply function (insert/update/delete), handles transaction boundaries (BEGIN/COMMIT), and tracks replication origins for each committed transaction.

Multi-insert batching is an optimization in heap mode: after MIN_MULTI_INSERT_TUPLES (5) consecutive INSERTs to the same table, the apply worker switches to batch mode, accumulating tuples and flushing them in a single heap_multi_insert call.

Usage

Use heap API (default) when:

  • Conflict resolution is needed (any mode other than error)
  • Maximum throughput is required
  • Trigger firing and index updates are needed

Use SPI API when:

  • Debugging apply behavior (SQL statements are visible in logs)
  • Compatibility with restricted environments where heap access is unavailable
  • Conflict resolution is not needed (pglogical.conflict_resolution = error)

Theoretical Basis

Apply loop:

while not SIGTERM:
    message = PQgetCopyData(streamConn)
    switch message.type:
        case 'B': begin_transaction()
        case 'I': do_insert(relation, new_tuple)
        case 'U': do_update(relation, old_key, new_tuple)
        case 'D': do_delete(relation, old_key)
        case 'C': commit_transaction()
        case 'R': cache_relation_metadata()

Heap API apply flow (INSERT):

Failed to parse (syntax error): {\displaystyle \text{decode tuple} \to \text{find conflict (index scan)} \to \text{resolve conflict} \to \text{heap\_insert} \to \text{fire triggers} \to \text{update indexes} }

SPI API apply flow (INSERT):

Failed to parse (syntax error): {\displaystyle \text{decode tuple} \to \text{build INSERT SQL} \to \text{SPI\_execute\_with\_args} \to \text{executor handles triggers/indexes} }

Multi-insert batching:

When pglogical.batch_inserts = true and heap mode is active, consecutive INSERTs to the same table accumulate. After 5+ tuples, a batch flush via heap_multi_insert replaces individual inserts, reducing per-tuple overhead.

Practical Guide

Selecting Apply Mode

-- In postgresql.conf (default: heap API)
pglogical.use_spi = false       -- Use heap API (default, supports conflict resolution)
pglogical.batch_inserts = true  -- Enable multi-insert batching (heap mode only)

-- Alternative: SPI mode (no conflict resolution)
-- pglogical.use_spi = true
-- pglogical.conflict_resolution = error  -- Required with SPI

Key Considerations

  • Heap API fires BEFORE/AFTER row triggers (replica triggers only)
  • SPI mode cannot do conflict resolution — it errors on any conflict
  • session_replication_role = replica is set, so only replica triggers fire
  • The apply worker runs as a background worker with its own resource owner
  • Relation mapping (remote→local) is cached in the relcache for efficiency

Related Pages

Implemented By

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment