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

Implementation:2ndQuadrant Pglogical Apply Work

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

Overview

Core apply worker main loop and entry point that connects to the provider, reads the replication stream via libpq, decodes protocol messages, dispatches changes to apply functions, and manages transaction boundaries and replication origin tracking.

Description

The pglogical_apply_main() function is the background worker entry point for the apply worker. It attaches to a shared memory worker slot, loads the subscription configuration, selects the apply API (heap or SPI) based on GUCs, sets session_replication_role = replica, connects to the provider's replication slot, and enters the main apply loop.

The apply_work() function is the main loop. It uses WaitLatchOrSocket to wait for data on the replication connection, reads messages via PQgetCopyData, and dispatches them:

  • B (BEGIN): Start a transaction, set replication origin session
  • R (REL): Cache relation metadata
  • I (INSERT): Call apply_api.do_insert
  • U (UPDATE): Call apply_api.do_update
  • D (DELETE): Call apply_api.do_delete
  • C (COMMIT): Commit transaction, advance replication origin, send feedback

The apply API dispatch table (apply_api) is a static struct initialized with heap functions by default, or SPI functions if pglogical.use_spi = true.

Usage

This is an internal background worker function. Users do not call it directly, but should understand it when:

  • Debugging apply worker crashes or hangs
  • Understanding the message processing pipeline
  • Tuning apply worker behavior via GUCs
  • Troubleshooting replication lag

Code Reference

Source Location

  • Repository: pglogical
  • File: pglogical_apply.c
  • Lines: L1919-2052 (pglogical_apply_main); L1337-1527 (apply_work); L105-114 (apply_api dispatch)

Signature

void pglogical_apply_main(Datum main_arg);

void apply_work(PGconn *streamConn);

/* Apply API dispatch table (static): */
static PGLogicalApplyFunctions apply_api = {
    .on_begin    = pglogical_apply_heap_begin,
    .on_commit   = pglogical_apply_heap_commit,
    .do_insert   = pglogical_apply_heap_insert,
    .do_update   = pglogical_apply_heap_update,
    .do_delete   = pglogical_apply_heap_delete,
    .can_multi_insert     = pglogical_apply_heap_can_mi,
    .multi_insert_add_tuple = pglogical_apply_heap_mi_add_tuple,
    .multi_insert_finish   = pglogical_apply_heap_mi_finish
};

Import

/* Internal background worker entry point.
   Registered by pglogical_worker_register() and spawned by PostgreSQL. */

I/O Contract

Inputs

Name Type Required Description
main_arg Datum Yes Worker slot index (DatumGetInt32)
streamConn PGconn* Yes apply_work: replication connection to provider
subscription catalog Yes Loaded from shared memory slot ID

Outputs

Name Type Description
applied changes database rows INSERT/UPDATE/DELETE applied to subscriber tables
replication origin origin session Advanced to remote commit LSN after each transaction
standby feedback protocol msg Sent to provider with flush/apply positions
lsn_mapping tracking entries Flush position tracking for restart safety

Usage Examples

Apply Loop (Internal)

// Abstract apply loop (NOT real implementation)
void apply_work(PGconn *streamConn) {
    while (!got_SIGTERM) {
        // Wait for data on replication connection
        WaitLatchOrSocket(&MyProc->procLatch,
                          WL_SOCKET_READABLE | WL_LATCH_SET | WL_TIMEOUT, fd, 1000L);

        // Read message
        copybuf = PQgetCopyData(streamConn, NULL, 1);
        if (copybuf == NULL) continue;

        switch (copybuf[0]) {
            case 'B':  // BEGIN
                apply_api.on_begin();
                set_replorigin_session(commit_lsn, commit_time);
                break;
            case 'I':  // INSERT
                rel = pglogical_read_insert(in, lockmode, &newtup);
                apply_api.do_insert(rel, &newtup);
                break;
            case 'U':  // UPDATE
                rel = pglogical_read_update(in, lockmode, &hasold, &oldtup, &newtup);
                apply_api.do_update(rel, &oldtup, &newtup);
                break;
            case 'D':  // DELETE
                rel = pglogical_read_delete(in, lockmode, &oldtup);
                apply_api.do_delete(rel, &oldtup);
                break;
            case 'C':  // COMMIT
                apply_api.on_commit();
                replorigin_advance(origin_id, end_lsn, ...);
                send_feedback(end_lsn);
                break;
        }
    }
}

Configuring Apply Worker

-- GUCs affecting apply worker behavior:
-- pglogical.use_spi = false       (use heap API for conflict resolution)
-- pglogical.batch_inserts = true  (enable multi-insert batching)
-- pglogical.conflict_resolution = 'last_update_wins'
-- pglogical.synchronous_commit = off

Related Pages

Implements Principle

Uses Heuristic

Requires Environment

Page Connections

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