pglogical 2

repository·REL2_x_STABLE·Indexed 22 days ago

https://github.com/2ndquadrant/pglogical

A logical streaming replication extension for PostgreSQL that uses a publish/subscribe model. It enables selective, per-database, and per-table data replication, supporting use cases such as major version upgrades, data merging from multiple upstream servers, and cascading replication. It requires PostgreSQL 9.4 or newer and provides features for row filtering, conflict resolution (including last/first update wins), and batch insert optimization.

Tokens
9.6K
Snippets
12
Records
50
Agent score
79%

What's inside pglogical

  1. What is pglogical 2?

    REL2_x_STABLE

    pglogical 2 is a PostgreSQL extension that provides logical streaming replication using a publish/subscribe model. It allows for selective replication of tables, rows, or columns, and supports use cases such as major version upgrades, full database replication, and data merging from multiple upstream servers.

    Core Concepts

    • Nodes: PostgreSQL database instances.
    • Providers and Subscribers: The roles taken by Nodes in the replication stream.
    • Replication Set: A collection of tables to be replicated.

    Architectural Model

    • Per-database level: Unlike physical streaming replication which works at the server level, pglogical operates on a per-database basis.
    • One-to-Many: One Provider can feed multiple Subscribers without additional disk write overhead.
    • Many-to-One: One Subscriber can merge changes from several origins and handle conflicts via configurable resolution.
    • Cascading: Implemented via changeset forwarding.
  2. Constraints and Conflict Resolution

    REL2_x_STABLE

    When using multiple upstreams or allowing local writes on the downstream, follow these rules for constraints:

    1. Single Unique Index: Only one UNIQUE index should be present on downstream replicated tables to allow for conflict resolution. If a row satisfies the PRIMARY KEY but violates a UNIQUE constraint, replication will error and stop.
    2. Constraint Strictness: Downstream constraints must not be more restrictive than those on the upstream(s).
    3. No Deferrable Indexes: pglogical does not support index-based constraints defined as DEFERRABLE. Attempting to apply changes to a table with deferrable indexes will result in the following error: ERROR: pglogical doesn't support index rechecks needed for deferrable indexes
  3. Manage relation metadata caching in pglogical_output

    REL2_x_STABLE

    To ensure data integrity when table structures differ, pglogical_output sends relation metadata. The downstream client is responsible for caching this metadata.

    Caching Rules for Downstream Clients:

    • Mandatory Caching: The downstream must always cache relation metadata when received.
    • Replacement: If a new metadata message for an existing relation arrives, it must replace the old entry in the cache.
    • Purging: The downstream may only purge metadata from its cache after receiving a specific purge message for that relation from the upstream.
    • Syncing: The downstream cache is a 'slave cache' that follows the upstream's management. The downstream informs the upstream of its supported maximum cache size during the startup phase.

    Note: Purge messages from the upstream are notifications that the upstream no longer expects the downstream to retain that entry; the downstream does not have to purge immediately.

  4. How pglogical_output handles metadata and filtering

    REL2_x_STABLE

    Unlike simple JSON decoders (like wal2json), pglogical_output is a comprehensive replication component that manages:

    • Format Negotiation: Negotiating the communication protocol between client and server.
    • Sender-side Filtering: Using pluggable hooks to filter data (e.g., replication origin filtering) before it is sent.
    • Binary Protocol: Using a custom binary protocol for speed and compactness, avoiding the overhead of JSON encoding/decoding and allowing efficient raw binary datum transfer.
    • Column Metadata: Sending column names (and potentially type metadata) before each row that first refers to a relation. This ensures that even if table attnos (attribute numbers) differ between upstream and downstream due to DDL changes, data is mapped to the correct columns.

    pglogical_output is designed as a reusable component for other solutions rather than a standalone extension with its own SQL catalogs.

  5. Requirements for Table Replication (PK and Identity)

    REL2_x_STABLE

    To replicate UPDATE and DELETE operations, tables must have a PRIMARY KEY or a valid replica identity.

    A valid replica identity must be an index that is:

    • Unique
    • Not partial
    • Not deferrable
    • Composed only of columns marked NOT NULL

    Note: REPLICA IDENTITY FULL is not currently supported.

  6. Replication limitations and requirements for pglogical_output

    REL2_x_STABLE

    When using the pglogical_output plugin, be aware of the following technical constraints:

    • Transaction Ordering: Logical decoding serializes transactions in commit order. pglogical_output cannot replay interleaved concurrent transactions, which may cause latency if large transactions queue up behind smaller ones.
    • Replica Identity: To replicate INSERT or UPDATE operations, the target table must have a PRIMARY KEY or a non-partial, columns-only UNIQUE index. This provides the REPLICA IDENTITY required to identify which tuple to update.
    • UNLOGGED Tables: UNLOGGED tables are not written to WAL and therefore cannot be replicated via logical or physical replication. Use trigger-based solutions if these must be replicated.
    • Update Payload: Logical decoding does not track 'dirty' vs 'clean' fields. In UPDATE operations, unchanged fields are typically sent in the payload unless they are variable-length TOASTable types large enough to be stored out-of-line.
  7. Requirements for using pglogical 2

    REL2_x_STABLE

    To use pglogical, ensure your environment meets the following criteria:

    Version Requirements

    • PostgreSQL: Provider and subscriber nodes must run PostgreSQL 9.4 or newer.
    • Conflict Detection/Filtering: PostgreSQL 9.5+ is required for replication origin filtering and conflict detection.
    • Postgres-XL: Subscribers can be Postgres-XL 9.5+.

    Extension and Schema Requirements

    • Installation: The pglogical extension must be installed and initialized on both provider and subscriber using CREATE EXTENSION pglogical;.
    • Schema Matching: Tables on the provider and subscriber must have the same names and reside in the same schema.
    • Column Matching: Tables must have the same columns and data types. CHECK and NOT NULL constraints on the subscriber must be the same as or more permissive (weaker) than those on the provider.
    • Primary Keys: Tables must have identical PRIMARY KEYs. It is not recommended to add additional UNIQUE constraints other than the PRIMARY KEY.
  8. Understanding apply_delay and TimeZone changes

    REL2_x_STABLE

    The apply_delay setting controls the delay in applying changes at the subscriber.

    • Daylight Savings Time (DST): apply_delay accounts for TimeZone changes. If a DST switch occurs after the subscription is created, the intended interval remains consistent in practice.
    • Operational Caution: It is not recommended to run heavy workloads during the time of a DST switch, as pglogical replication may require approximately 5 minutes to recover and stabilize.
  9. Administrative Privileges and Permissions

    REL2_x_STABLE

    Administration of pglogical requires superuser privileges. The extension must be installed by a superuser, and no privileges on its schema, catalogs, or functions are granted to other roles. Consequently, functions managing nodes, subscriptions, and replication sets can only be executed by a superuser.

    Note on Subscriber Permissions: Applying changes on the subscriber does not require superuser privileges. To run subscriptions with the permissions of a regular role instead of a superuser, use the pglogical.subscription_owner parameter.

  10. Behavior of Column Filters

    REL2_x_STABLE

    Column filters allow you to restrict replication to specific columns. Note the following behaviors:

    • System Columns: You cannot filter on system columns such as oid or xmin.
    • OIDs: Column filtering works correctly on tables that have OIDs enabled.
    • Dropped Columns: If a column being filtered on is dropped at the provider, it is removed from the column filter (verify this using pglogical.show_repset_table_info()). At the subscriber, the column remains. In this state, INSERT operations will still replicate, but UPDATE and DELETE operations will not.
    • Added Columns: Adding a new column at the provider does not automatically include it in the existing column filter.
  11. How the pglogical output plugin works

    REL2_x_STABLE

    The pglogical output plugin is a logical decoding plugin designed to extract a change stream from a PostgreSQL database and transmit it to a client over a network using an efficient protocol.

    Key Characteristics:

    • Scope: Replicates a single database (or a subset of tables/origins), not the entire PostgreSQL instance.
    • Efficiency: Only changed rows are sent; it excludes index changes, vacuum activity, etc.
    • Reliability: Uses PostgreSQL replication slots to ensure the stream is crash-safe. If a client disconnects, the server accumulates changes in a queue, allowing the client to resume from the last processed message upon reconnection.
    • Compatibility: Unlike physical streaming replication, the logical change stream is compatible across different PostgreSQL versions and can be consumed by non-PostgreSQL clients.
    • Resource Note: Because it uses replication slots, server-side resources (like WAL files) are consumed to maintain the queue even when no client is connected.
  12. Configure changeset forwarding modes in pglogical_output

    REL2_x_STABLE

    The pglogical_output plugin supports two modes for cascading replication between PostgreSQL servers:

    1. Forward everything: Transactions are replicated regardless of their origin. This is the only option available when running on PostgreSQL 9.4. All rows from transactions are sent.
    2. Filtered forwarding: Transactions are replicated unless a client-supplied transaction filter hook specifies to skip them. Row changes are replicated unless a client-supplied row filter hook specifies to skip them.

    On PostgreSQL 9.5 or newer, the server enables changeset origin information and sets forward_changeset_origins to true in the startup reply message. Origin messages are sent after the BEGIN for each transaction (except for transactions originating directly on the immediate upstream).