Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Choosing pg_tide

Choosing the right messaging infrastructure is one of the most consequential architectural decisions you'll make. This page helps you determine whether pg_tide is the right fit for your project by examining where it excels, where alternatives serve better, and how it compares to other tools you might be considering.


When pg_tide Is a Great Fit

You need reliable event publishing from PostgreSQL

Your application writes to PostgreSQL and needs to notify other systems about those writes — sending emails, updating search indexes, feeding analytics pipelines, triggering downstream workflows. You want guarantees that every committed transaction produces exactly one event: no lost messages, no duplicates, no manual reconciliation.

pg_tide was built specifically for this scenario. The transactional outbox pattern ensures your events are published atomically with your business data. If the transaction commits, the event is guaranteed to be delivered. If it rolls back, the event never existed.

You want to eliminate dual-write bugs

The dual-write problem is pernicious because it's intermittent and silent. Your application might work perfectly 99.9% of the time, but during network hiccups, process restarts, or database failovers, events get lost or duplicated. These bugs are incredibly difficult to detect in testing and even harder to reproduce.

pg_tide eliminates this entire class of bugs by design. There is no dual write — only a single database write that includes both your data and the event. The relay handles delivery separately, retrying indefinitely until downstream systems acknowledge receipt.

You prefer SQL over SDKs

pg_tide is a PostgreSQL extension. Publishing an event is a SELECT tide.outbox_publish(...) call. There's no client library to install, no serialization framework to learn, no connection pooling for a separate broker, no SDK version compatibility to manage. Any language or framework that can talk to PostgreSQL can publish events.

This means your Go service, Python script, dbt model, PL/pgSQL function, and psql session can all publish events using exactly the same API. The outbox is a database table — you can query it, monitor it, and manage it with standard SQL tools.

You're already running PostgreSQL

If PostgreSQL is your primary data store — and for many teams, it is — pg_tide adds messaging capabilities without introducing new infrastructure. No Kafka cluster to operate, no ZooKeeper to babysit, no broker to monitor. The relay binary is a single static executable that reads its configuration from the same database it's delivering messages from.

This dramatically reduces operational overhead. You already know how to back up PostgreSQL, monitor its performance, manage its connections, and failover between replicas. pg_tide inherits all of that operational maturity.

You need an effectively exactly-once application outcome

Many messaging systems provide at-most-once or at-least-once delivery. pg_tide provides atomic outbox writes and at-least-once relay transport. A PostgreSQL inbox adds durable deduplication; with transactional application processing, the destination outcome can be effectively exactly once. Cross-system transport itself remains at least once.

Your throughput fits within PostgreSQL's capacity

Use the measured publish-single and publish-concurrent profiles to determine whether your workload fits. Payload size, transaction shape, PostgreSQL settings, and hardware dominate the result; pg_tide does not publish a universal per-connection rate.


When to Consider Alternatives

You need sub-millisecond propagation latency

pg_tide's relay polls the outbox at a configurable interval (it wakes immediately via pg_notify for new messages, but batching introduces slight delays). For use cases that demand microsecond-level propagation — high-frequency trading signals, real-time game state — a dedicated event streaming platform with direct in-memory writes (like NATS Core or Kafka with acks=0) will provide lower latency.

Measure end-to-end p50/p95/p99 for the selected sink and poll/batch settings. Do not carry a latency number from another environment into a capacity plan.

You have no PostgreSQL in your stack

pg_tide is a PostgreSQL extension — that's the whole point. If your data lives outside PostgreSQL, pg_tide can't help you. Look at:

  • A purpose-built CDC tool — automatic change capture for non-PostgreSQL stores

You're doing pure pub/sub without durability requirements

If you need ephemeral fire-and-forget messaging — real-time typing indicators, presence updates, or live dashboard refreshes — a broker-native pub/sub subscription is lighter and faster. No durability means no outbox, offset tracking, or relay to operate.

Your sustained throughput exceeds PostgreSQL's write capacity

pg_tide's throughput ceiling is fundamentally PostgreSQL's measured publish and relay capacity. If the matching operational profile misses its reviewed budget, a dedicated log-structured system may be a better fit.

However, before concluding that you need more throughput, consider whether you can partition your events across multiple outboxes, which allows parallel relay consumption.

You need automatic schema-change capture

If your use case is "capture every row change in every table automatically, without modifying application code," an automatic CDC tool is better suited. pg_tide requires you to explicitly publish events — you choose what gets published, when, and in what format. This is a strength (explicit > implicit for event contracts), but it requires more application involvement.


The Sweet Spot

pg_tide occupies the space where transactional correctness matters more than raw throughput, and where operational simplicity (no broker cluster, no JVM, no ZooKeeper) outweighs the need for a standalone streaming platform.

Typical use cases that pg_tide handles beautifully:

Use caseWhy pg_tide fits
Order processing pipelinesEvents must not be silently lost; durable destination deduplication is essential
Audit event emissionEvery business action must produce a corresponding audit record
Cross-service synchronizationServices need consistent views of shared data
Webhook delivery with retryUnreliable endpoints need persistent retry with DLQ
Saga / process manager coordinationOrchestrating multi-step workflows across services
CQRS event sourcingProjecting command-side events to query-side read models
Data warehouse loadingReliably streaming changes to analytics infrastructure
Multi-tenant notification deliveryPer-tenant event routing with independent tracking

Detailed Comparison with Alternatives

pg_tide vs. automatic CDC

Aspectpg_tideAutomatic CDC
MechanismApplication explicitly writes to outbox tableCDC captures database changes automatically
Message formatYou control the payload — publish exactly what consumers needMirrors row-level changes (schema-coupled to table structure)
Event granularityPublish semantic events ("order confirmed")Captures physical changes ("row updated in orders table")
InfrastructurePostgreSQL + single relay binaryDatabase-specific capture service and broker
Effectively exactly onceAvailable with inbox dedup and transactional processingRequires destination durability and idempotency
Operational costOne binary, no broker cluster requiredCapture service and broker operations
FlexibilityArbitrary events, decoupled from table schemaAutomatic but tied to schema changes
Application changesMust call outbox_publish()None (captures changes transparently)
LatencyProfile- and sink-dependentReplication-slot lag dependent

Choose pg_tide when you want explicit, semantic events that are decoupled from your table schema and you prefer minimal infrastructure. Choose an automatic CDC tool when you need every database change without modifying application code and accept its operational model.

pg_tide vs. Application-Level Outbox (DIY)

Aspectpg_tideCustom outbox table + homegrown relay
Setup timeCREATE EXTENSION pg_tide; + start relayDesign schema, build polling logic, implement retry, add dedup, build monitoring...
Consumer groupsBuilt-in with offsets, heartbeats, visibility leasesYou build and maintain it
RelayMulti-backend binary with metrics, backpressure, HAYou build and maintain it
Idempotent inboxBuilt-in with DLQ and replayYou build and maintain it
MonitoringPrometheus metrics + SQL views out of the boxYou instrument and maintain it
HA / failoverAdvisory lock coordination, automaticYou design and build it
MaintenanceUpgrade extension + relay binaryMaintain all custom code indefinitely
DestinationsNATS, Kafka, PostgreSQL inbox, WebhooksWhatever you've implemented

Choose pg_tide to avoid reinventing reliable messaging infrastructure. A DIY outbox is deceptively simple to start but grows in complexity quickly as you add retry logic, offset tracking, multiple consumers, monitoring, and failover. Choose DIY only when you have very specific requirements that don't map to pg_tide's model.

pg_tide vs. pg_notify / LISTEN

Aspectpg_tidepg_notify
DurabilityMessages persist until consumedFire-and-forget (lost if no listener is active)
Payload sizeJSONB (up to 1 GB, practically limited by memory)8,000 bytes maximum
RetryBuilt-in with exponential backoff and DLQNone — if you miss it, it's gone
Consumer groupsIndependent offset tracking per consumerNo — every listener sees every notification
Delivery guaranteeAt-least-once (effectively exactly once with transactional inbox processing)At-most-once (zero-once if no listener)
Cross-networkRelay bridges to any external systemOnly in-process PostgreSQL clients
OrderingGuaranteed within an outbox (by ID)Guaranteed within a session
BackpressureConfigurable thresholdNone (notifications queue in memory)

Choose pg_tide when you need durable, reliable delivery with guarantees. Choose pg_notify for lightweight real-time signals where message loss is acceptable — like cache invalidation hints or live UI updates where the client can refresh on reconnect.

pg_tide vs. Writing Directly to Kafka/NATS

Aspectpg_tideDirect broker writes from application
Transactional safetyGuaranteed (same database transaction)Dual-write risk (DB commit + broker publish are independent)
Application complexityOne SQL call per eventBroker client library, connection management, error handling
Operational overheadExtension + lightweight relayBroker cluster management, application-side retries
Throughput ceilingMeasured PostgreSQL publish/relay budgetBroker-native throughput (higher ceiling)
LatencyProfile- and sink-dependentBroker/client dependent
Message loss riskZero (transactional guarantee)Non-zero (crash between DB commit and broker ack)
Duplicate riskHandled by inbox dedupApplication must implement idempotency

Choose pg_tide when transactional correctness is paramount and throughput fits within PostgreSQL's capacity. Choose direct broker writes when you accept the dual-write tradeoff for maximum throughput and minimum latency, or when your application already runs inside the broker ecosystem (e.g., a Kafka Streams application).


Cost Analysis: pg_tide vs. Running Kafka

For teams evaluating pg_tide against a full Kafka deployment, here's a practical comparison of operational costs:

Resourcepg_tideKafka (small production cluster)
Processes to operate1-2 relay instances3+ brokers + ZooKeeper/KRaft + Connect + Schema Registry
Memory footprint~50 MB per relay~6 GB per broker (JVM heap)
DiskShared with PostgreSQLDedicated high-throughput storage per broker
NetworkPostgreSQL connection + sink connectionsInter-broker replication, client connections, ZK communication
On-call complexity"Is PostgreSQL healthy? Is the relay running?"Partition rebalancing, ISR management, disk pressure, GC pauses
Team expertisePostgreSQL DBA + basic opsKafka-specialized operations team

pg_tide's total cost of ownership is often lower for teams whose primary workload is a PostgreSQL-backed application and whose named operational profile fits the reviewed budgets.


Decision Flowchart

Ask yourself these questions in order:

  1. Is PostgreSQL your primary data store? If not → look at a platform-specific CDC tool
  2. Do your events need transactional guarantees? If not → consider direct broker writes or pg_notify
  3. Does the matching operational profile fit its reviewed budgets? If not → consider Kafka/Redpanda
  4. Do you want to minimize operational overhead? If yes → pg_tide
  5. Do you need automatic schema-change capture? If yes → consider a CDC tool (or combine both)

If you answered "yes" to questions 1, 2, 3, and 4 — pg_tide is an excellent fit, subject to a reproducible reference run.


Migration Paths

Coming from pg_notify

If you're currently using pg_notify for event delivery and hitting its limitations (payload size, durability, reliability):

  1. Install pg_tide and create outboxes for your event channels
  2. Replace PERFORM pg_notify(channel, payload) with SELECT tide.outbox_publish(outbox, payload, headers)
  3. Set up relay pipelines to your downstream consumers
  4. Benefit from durability, retry, offset tracking, and destination deduplication

Coming from a DIY outbox table

If you've built a custom outbox pattern:

  1. Install pg_tide alongside your existing tables
  2. Migrate pipeline logic to pg_tide's relay (eliminates your custom polling code)
  3. Use pg_tide's consumer groups instead of custom offset tracking
  4. Add inboxes for receiving-side deduplication
  5. Decommission your custom relay code

Coming from an automatic CDC tool

If you're considering pg_tide as a complement or replacement for automatic CDC:

  • Complement: Keep automatic CDC for bulk table replication and use pg_tide for semantic business events shaped by application logic.
  • Replace: If automatic CDC is only being used for outbox-style events, pg_tide provides that capability with less infrastructure.

pg_tide

Transactional outbox, idempotent inbox, and relay pipelines for PostgreSQL 18.

pg_tide gives your PostgreSQL database a built-in messaging backbone. Publish events within your existing transactions — no dual-writes, no distributed transactions, no message brokers required at the database layer.

When you're ready to deliver to PostgreSQL, NATS, Kafka, or HTTPS, the pg-tide relay binary bridges the gap with at-least-once transport and stable event identities. A PostgreSQL inbox can provide an effectively exactly-once application outcome through durable deduplication.


The Problem pg_tide Solves

Most applications eventually need to publish events to other systems. A customer places an order — and the warehouse needs to know, the analytics pipeline needs to know, the email service needs to send a confirmation. The naive approach is deceptively simple: save the order to your database, then publish an event to your message broker.

But what happens when the broker publish fails after the database commit? Or when your application crashes between the two operations? You get silent data loss — the order exists but nobody downstream knows about it. This is the dual-write problem, and it's one of the most common sources of data inconsistency in distributed systems.

pg_tide eliminates this entire class of bugs by implementing the transactional outbox pattern as a PostgreSQL extension. Your application writes both the business data and the event in a single database transaction. They succeed or fail together — atomically, consistently, and durably. A separate relay process then delivers committed events to downstream systems, retrying indefinitely until delivery succeeds.


How It Works

┌─────────────────────────────────────────────────────────────┐
│                    PostgreSQL 18                              │
│                                                              │
│  Your Application                                            │
│       │                                                      │
│       ├──▶ INSERT INTO orders (...)  ─┐                      │
│       │                               ├── Same transaction   │
│       └──▶ SELECT tide.outbox_publish ─┘                     │
│                        │                                     │
│            tide.tide_outbox_messages                          │
│                        │                                     │
└────────────────────────┼─────────────────────────────────────┘
                         │  pg_notify wakes relay
                         ▼
┌──────────────────────────────────────────────────────────────┐
│                   pg-tide relay binary                         │
│                                                               │
│  Polls outbox ──▶ Delivers to sink ──▶ Commits offset         │
└──────────────────────────────────────────────────────────────┘
                         │
                         ▼
          PostgreSQL · NATS · Kafka · Webhooks

Key Features

FeatureWhat it does
Transactional OutboxPublish messages within a database transaction. No 2PC, no dual-writes, no data loss.
Idempotent InboxDurable deduplication via unique constraints; effectively exactly-once processing when application work is transactional.
Consumer GroupsKafka-style offset tracking with heartbeats, visibility leases, and independent progress per consumer.
Relay BinaryStandalone pg-tide process that bridges outboxes/inboxes with external systems.
Focused deliveryPostgreSQL inbox, NATS JetStream, Apache Kafka, and HTTPS webhooks.
Hot ReloadPipeline config lives in PostgreSQL. Changes apply without relay restart.
HA ReadyAdvisory lock coordination provides automatic failover across relay instances.

At a Glance

-- Create an outbox (one-time setup)
SELECT tide.outbox_create('orders', p_retention_hours := 48);

-- Publish within your business transaction
BEGIN;
  INSERT INTO orders (id, total) VALUES (42, 99.99);
  SELECT tide.outbox_publish('orders',
    '{"order_id": 42, "total": 99.99}'::jsonb,
    '{"event_type": "order.created"}'::jsonb
  );
COMMIT;

-- Configure a relay pipeline
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-nats',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', '{"url": "tls://nats.example:4222", "subject": "orders.events"}'::jsonb
  )
);

-- Start the relay — messages flow automatically
-- pg-tide run --postgres-url "postgres://user:pass@localhost:5432/mydb"

Who Is This For?

pg_tide is built for:

  • Backend engineers building applications on PostgreSQL who need reliable event publishing
  • Platform teams providing messaging infrastructure without the operational burden of a full streaming platform
  • DBAs who want messaging capabilities that integrate naturally with their existing PostgreSQL operational practices

If PostgreSQL is your source of truth and you need events to flow reliably to other systems, pg_tide is designed for you.


Glossary

Key terms used throughout this documentation:

TermMeaning
OutboxA named message stream stored in PostgreSQL. Messages are published to an outbox within a transaction.
InboxA named receiving table with durable deduplication. External messages are written here with at-least-once transport and can be processed transactionally.
RelayThe pg-tide binary that bridges outboxes/inboxes with external systems.
PipelineA configured connection from a PostgreSQL outbox to a retained sink.
Consumer GroupA named entity that tracks reading progress through an outbox independently.
OffsetThe ID of the last message successfully processed by a consumer group.
SinkThe destination system in a forward pipeline (e.g., NATS, Kafka).
SourceThe PostgreSQL outbox that supplies relay messages.
DLQ (Dead-Letter Queue)Messages that have exhausted retry attempts. Stored in the inbox for investigation and replay.
Advisory LockA PostgreSQL lock mechanism used to coordinate pipeline ownership across relay instances.
Relay Group IDAn identifier that namespaces advisory locks, allowing multiple relay deployments to coexist.
Visibility LeaseA time-limited reservation on a batch of messages, preventing double-processing.
Dedup KeyA unique identifier (event_id) used by the inbox to detect and discard duplicate deliveries.
Hot ReloadThe relay's ability to pick up pipeline config changes from the database without restart.

Documentation Guide

This documentation is organized to match your learning journey:

  1. Evaluate — decide if pg_tide is right for your use case
  2. Getting Started — install and build your first pipeline
  3. Concepts — understand the mechanics in depth
  4. SQL Reference — complete API documentation
  5. Relay Guide — configure and operate the relay binary
  6. Tutorials — guided walkthroughs of common patterns
  7. Operations — production deployment and maintenance
  8. Integrations — platform-specific guidance

License

pg_tide is released under the Apache-2.0 license.

Installation

pg_tide has two components to install: the PostgreSQL extension (SQL functions and catalog tables) and the relay binary (the pg-tide process that bridges messages to external systems).


Prerequisites

  • PostgreSQL 18 or later
  • Superuser or CREATE EXTENSION privileges on your target database

Installing the Extension

From Source (pgrx)

On macOS, the repository Cargo configuration supplies the linker flag required for PostgreSQL symbols that are resolved when the extension is loaded.

# Install cargo-pgrx if you haven't already
cargo install cargo-pgrx --version "=0.18.0" --locked
cargo pgrx init --pg18 $(which pg_config)

# Build and install
cd pg-tide-ext
cargo pgrx install --release

Enable the Extension

CREATE EXTENSION pg_tide;

This creates the tide schema with all catalog tables, views, and functions.


Installing the Relay Binary

From GitHub Releases

Download the latest release for your platform from the releases page:

# Linux (amd64)
curl -LO https://github.com/trickle-labs/pg-tide/releases/latest/download/pg-tide-x86_64-unknown-linux-gnu.tar.gz
tar xzf pg-tide-x86_64-unknown-linux-gnu.tar.gz
sudo mv pg-tide /usr/local/bin/

# macOS (Apple Silicon)
curl -LO https://github.com/trickle-labs/pg-tide/releases/latest/download/pg-tide-aarch64-apple-darwin.tar.gz
tar xzf pg-tide-aarch64-apple-darwin.tar.gz
sudo mv pg-tide /usr/local/bin/

From Source (Cargo)

cargo install --git https://github.com/trickle-labs/pg-tide pg-tide-relay

Docker

docker pull ghcr.io/trickle-labs/pg-tide:latest

Verify Installation

# Check relay version
pg-tide --version

# Check extension is installed
psql -c "SELECT * FROM pg_extension WHERE extname = 'pg_tide';"

Next Steps

Your First Pipeline

This guide walks you through setting up pg_tide from scratch and building a complete message pipeline. By the end, you'll have an outbox publishing order events and a relay delivering them to NATS JetStream — with monitoring, per-pipeline offset tracking, and at-least-once delivery (with stable deduplication identities) all working together.

We'll go step by step, explaining what's happening at each stage so you understand not just what to do, but why each piece matters.


Prerequisites

Before starting, make sure you have:

  • PostgreSQL 18 running and accessible (local or remote)
  • NATS server running locally (we'll use this as our message sink)
  • pg-tide relay binary installed (see Installation)

If you just want to kick the tires quickly, here's a Docker Compose file that sets up everything:

# docker-compose.yml — complete pg_tide development environment
services:
  postgres:
    image: postgres:18
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: app
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

  nats:
    image: nats:latest
    ports:
      - "4222:4222"   # Client connections
      - "8222:8222"   # Monitoring

  pg-tide-relay:
    image: ghcr.io/trickle-labs/pg-tide:latest
    depends_on:
      - postgres
      - nats
    environment:
      PG_TIDE_POSTGRES_URL: "postgres://postgres:postgres@postgres:5432/app"
      PG_TIDE_LOG_FORMAT: "json"
      PG_TIDE_LOG_LEVEL: "info"
    ports:
      - "9090:9090"   # Metrics + health

volumes:
  pgdata:

Start it with docker compose up -d, then connect to PostgreSQL with:

psql "postgres://postgres:postgres@localhost:5432/app"

Step 1: Install the Extension

The pg_tide extension creates the tide schema with all the catalog tables, views, and functions you'll need:

CREATE EXTENSION IF NOT EXISTS pg_tide;

Let's verify it's installed correctly:

SELECT extname, extversion FROM pg_extension WHERE extname = 'pg_tide';

The output shows the current installed version:

 extname | extversion
---------+-------------------
 pg_tide | <installed-version>

Behind the scenes, this created:

  • The tide schema
  • Configuration tables for outboxes, inboxes, consumer groups, and relay pipelines
  • The shared tide.tide_outbox_messages table where all outbox messages live
  • Offset-aware views like tide.outbox_retention_status and tide.relay_pipeline_lag for monitoring
  • SQL functions like tide.outbox_publish() for the API

Step 2: Create an Outbox

An outbox is a named message stream. You might have one outbox for order events, another for user events, another for inventory changes — each is logically separate but physically stored in the same table (discriminated by name).

Let's create an outbox for order events:

SELECT tide.outbox_create_if_not_exists('orders',
  p_retention_hours := 48,
  p_inline_threshold := 10000
);

What do these parameters mean?

  • 'orders' — the name of our outbox. This is how you'll refer to it when publishing and when configuring relay pipelines.
  • p_retention_hours := 48 — consumed messages are kept for 48 hours before cleanup. This gives you time to investigate issues and replay if needed.
  • p_inline_threshold := 10000 — retained compatibility/configuration metadata. Native publishing does not reject transactions based on pending row count; reserve disk and alert on exact lag when a sink is unavailable.

Verify the outbox exists:

SELECT * FROM tide.tide_outbox_config;
 outbox_name | retention_hours | inline_threshold | enabled |         created_at
-------------+-----------------+------------------+---------+----------------------------
 orders      |              48 |            10000 | t       | 2025-01-15 10:00:00.000+00

Step 3: Publish Your First Messages

Now let's simulate what your application would do — publishing events within business transactions. The key insight is that the event publish is inside the same transaction as the business logic:

-- Create a simple orders table for this tutorial
CREATE TABLE IF NOT EXISTS orders (
    id SERIAL PRIMARY KEY,
    customer_id TEXT NOT NULL,
    total NUMERIC(10,2) NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    created_at TIMESTAMPTZ DEFAULT now()
);

-- Now publish an event atomically with the business operation
BEGIN;
  INSERT INTO orders (id, customer_id, total, status)
  VALUES (1, 'cust-alice', 149.99, 'confirmed');

  SELECT tide.outbox_publish('orders',
    '{"order_id": 1, "customer_id": "cust-alice", "total": 149.99, "status": "confirmed"}'::jsonb,
    '{"event_type": "order.confirmed", "source": "tutorial"}'::jsonb
  );
COMMIT;

Let's publish a few more events to make things interesting:

BEGIN;
  INSERT INTO orders (id, customer_id, total, status)
  VALUES (2, 'cust-bob', 42.00, 'confirmed');

  SELECT tide.outbox_publish('orders',
    '{"order_id": 2, "customer_id": "cust-bob", "total": 42.00, "status": "confirmed"}'::jsonb,
    '{"event_type": "order.confirmed", "source": "tutorial"}'::jsonb
  );
COMMIT;

BEGIN;
  INSERT INTO orders (id, customer_id, total, status)
  VALUES (3, 'cust-charlie', 299.95, 'confirmed');

  SELECT tide.outbox_publish('orders',
    '{"order_id": 3, "customer_id": "cust-charlie", "total": 299.95, "status": "confirmed"}'::jsonb,
    '{"event_type": "order.confirmed", "source": "tutorial"}'::jsonb
  );
COMMIT;

What just happened: Each transaction atomically wrote the order to the orders table AND the event to the outbox. If any transaction had failed (constraint violation, network error, application crash), both the order and the event would have been rolled back together. No orphaned events, no missing events.


Step 4: Check the Outbox Status

Let's verify our messages are pending (waiting for delivery):

SELECT * FROM tide.outbox_retention_status;
 outbox_name | pending_count |       oldest_at        | max_id
-------------+---------------+------------------------+--------
 orders      |             3 | 2025-01-15 10:01:00+00 |      3

Three messages waiting for the relay to pick them up. You can also get detailed status:

SELECT tide.outbox_status('orders');

This returns a JSONB object with comprehensive information about the outbox's current state.


Step 5: (Optional) Create a Consumer Group

The native relay tracks its own durable offset per relay group, pipeline, and outbox, so it does not require a consumer group. Consumer groups remain available as a legacy/global-consumer surface (for example, for SQL-side tide.poll_outbox() consumers). You can skip to Step 6 for the native pipeline.

If you do want a consumer group, create one like this:

SELECT tide.create_consumer_group('nats-relay', 'orders',
  p_auto_offset_reset := 'earliest'
);

'earliest' processes all existing messages; 'latest' skips to only future messages.


Step 6: Configure the Relay Pipeline

Now we tell pg_tide how to deliver messages from the orders outbox to NATS. The native relay polls the shared tide.tide_outbox_messages table directly and tracks a durable offset per relay group, pipeline, and outbox (ADR-011) — no consumer group is required:

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-nats',       -- pipeline name (unique identifier)
    'outbox', 'orders',             -- source outbox
    'sink_type', 'nats',            -- sink type
    'config', jsonb_build_object(   -- sink-specific configuration
      'url', 'tls://nats.example:4222',
      'subject_template', 'orders.{event_type}'
    )
  )
);

Notice the subject template: 'orders.{event_type}'. The NATS sink substitutes {event_type} with the value from the message's event_type header (a missing or non-string header falls back to the literal event). Our messages have "event_type": "order.confirmed", so they'll be published to the NATS subject orders.order.confirmed.

This is powerful — different event types from the same outbox can be routed to different NATS subjects without any relay-side logic.


Step 7: Start the Relay

If you're using the Docker Compose setup, the relay is already running. Otherwise, start it manually:

pg-tide run --postgres-url "postgres://postgres:postgres@localhost:5432/app"

You'll see log output like:

INFO  pg_tide_relay: Starting pg-tide relay v<installed-version>
INFO  pg_tide_relay: Connected to PostgreSQL
INFO  pg_tide_relay: Discovered pipeline: orders-to-nats (forward, nats)
INFO  pg_tide_relay: Acquired advisory lock for pipeline: orders-to-nats
INFO  pg_tide_relay: Pipeline orders-to-nats: processing 3 pending messages
INFO  pg_tide_relay: Pipeline orders-to-nats: published batch [1..3] to nats

What's happening under the hood:

  1. The relay connects to PostgreSQL and reads the pipeline catalog
  2. It discovers orders-to-nats and attempts to acquire an advisory lock for it
  3. It succeeds (it's the only relay instance), so it owns this pipeline
  4. It polls tide.tide_outbox_messages for messages in the orders outbox where id > last_committed_offset
  5. It delivers each message to the configured NATS subject
  6. On success, it commits the offset and marks messages as consumed

Step 8: Verify Delivery

Subscribe to NATS to see the delivered messages (in another terminal):

# Using the nats CLI tool
nats sub "orders.>"

If messages were already delivered (relay started before you subscribed), you can verify from the PostgreSQL side:

-- Check that messages are now consumed
SELECT * FROM tide.outbox_retention_status;
 outbox_name | pending_count | oldest_at | max_id
-------------+---------------+-----------+--------
(0 rows)

No pending messages — they've all been delivered! Check consumer lag:

SELECT * FROM tide.relay_pipeline_lag;
 group_name | outbox_name | consumer_id | committed_offset | lag | last_heartbeat
------------+-------------+-------------+------------------+-----+--------------------
 nats-relay | orders      | relay-0     |                3 |   0 | 2025-01-15 10:02:00

Zero lag — the relay is fully caught up. The committed_offset of 3 means all messages through ID 3 have been delivered.


Step 9: Publish More Messages and Watch Them Flow

Now that the pipeline is running, new messages are delivered in near-real-time. In another terminal, subscribe to NATS:

nats sub "orders.>"

Then publish a new event in psql:

BEGIN;
  INSERT INTO orders (id, customer_id, total, status)
  VALUES (4, 'cust-diana', 75.50, 'confirmed');

  SELECT tide.outbox_publish('orders',
    '{"order_id": 4, "customer_id": "cust-diana", "total": 75.50, "status": "confirmed"}'::jsonb,
    '{"event_type": "order.confirmed"}'::jsonb
  );
COMMIT;

Within milliseconds, you'll see the message appear on the NATS subscription. The flow is:

  1. COMMIT triggers pg_notify('tide_outbox_new', 'orders')
  2. The relay receives the notification and immediately polls for new messages
  3. Message ID 4 is fetched, delivered to NATS, and the offset is committed

Step 10: Monitor with Prometheus

The relay exposes Prometheus metrics at its metrics endpoint:

curl http://localhost:9090/metrics

Key metrics to watch:

# Total messages delivered
pg_tide_relay_messages_published_total{pipeline="orders-to-nats",direction="forward"} 4

# Error count (should be 0)
pg_tide_relay_publish_errors_total{pipeline="orders-to-nats",direction="forward"} 0

# Pipeline health
pg_tide_relay_pipeline_healthy{pipeline="orders-to-nats"} 1

And the health endpoint:

curl http://localhost:9090/health
# Returns 200 OK when all pipelines are healthy

What You've Built

In this tutorial, you've set up a complete transactional outbox pipeline:

  1. The extension provides the schema, tables, and SQL API
  2. The outbox stores events atomically with your business transactions
  3. The consumer group tracks how far the relay has progressed
  4. The pipeline configuration tells the relay where to deliver messages
  5. The relay binary bridges the gap between PostgreSQL and NATS
  6. Monitoring via Prometheus metrics and the consumer lag view

This is the foundational pattern. From here, you can:

  • Add more pipelines to fan out events to multiple systems
  • Create an inbox to receive events from external services
  • Add more relay instances for high availability
  • Configure different destinations (PostgreSQL inbox, Kafka, NATS, and webhooks)

Next Steps

Concept: The Transactional Outbox Pattern

The transactional outbox pattern solves one of the most common problems in distributed systems: how to reliably update a database and publish an event at the same time. Without it, you face the "dual-write problem" — a situation where your database write succeeds but the message publish fails (or vice versa), leaving your system in an inconsistent state.

The Problem

Consider an e-commerce application that needs to save an order and notify the shipping service:

BEGIN;
  INSERT INTO orders (id, status) VALUES ('ORD-001', 'confirmed');
COMMIT;

-- Outside the transaction:
publish_to_kafka('order.confirmed', { order_id: 'ORD-001' });

What happens if the application crashes between the COMMIT and the publish? The order exists in the database, but the shipping service never learns about it. The event is lost.

What if you reverse the order — publish first, then commit? If the COMMIT fails (constraint violation, connection loss), the event was already published for an order that doesn't exist.

There is no safe ordering for two independent systems. This is the dual-write problem.

The Solution

The transactional outbox pattern writes the event to an "outbox" table in the same database transaction as the business data:

BEGIN;
  INSERT INTO orders (id, status) VALUES ('ORD-001', 'confirmed');
  SELECT tide.outbox_publish('order_events', 'orders', '{"order_id": "ORD-001", "status": "confirmed"}');
COMMIT;

Both writes are part of the same ACID transaction. Either both succeed or both fail. There is no inconsistency window.

A separate process (the relay) polls the outbox table and publishes events to external systems. If the relay crashes, it simply resumes from where it left off — the events are safely persisted in PostgreSQL.

Guarantees

The transactional outbox provides:

  1. Atomicity — The business operation and event publication succeed or fail together
  2. Durability — Events survive crashes (they're in PostgreSQL's WAL)
  3. Ordering — Events from the same outbox are delivered in the order they were written
  4. At-least-once delivery — Every committed event will eventually be delivered to the sink

How pg_tide Implements It

Application                  PostgreSQL                    Relay                    Sink
    │                            │                          │                       │
    │─── BEGIN ─────────────────→│                          │                       │
    │─── INSERT INTO orders ────→│                          │                       │
    │─── outbox_publish() ──────→│ (writes to outbox table) │                       │
    │─── COMMIT ────────────────→│                          │                       │
    │                            │                          │                       │
    │                            │←── poll outbox ──────────│                       │
    │                            │─── return rows ─────────→│                       │
    │                            │                          │─── publish ──────────→│
    │                            │                          │←── ack ───────────────│
    │                            │←── mark delivered ───────│                       │

The relay advances through the outbox table sequentially. After successful delivery, it advances its cursor. If it crashes and restarts, it re-reads from the last acknowledged position — potentially re-delivering a few messages (at-least-once), but never losing any.

When to Use This Pattern

Use the transactional outbox when:

  • You need to update a database and publish an event reliably
  • Consistency between your database and event stream matters
  • You can't afford lost events (order notifications, payment confirmations, audit logs)
  • You want to decouple your application from the messaging infrastructure

Comparison with Alternatives

ApproachConsistencyComplexityTrade-offs
Transactional outbox (pg_tide)StrongLowSlight delivery latency (polling interval)
WAL-based CDCEventualMediumCaptures all changes, less control
Dual-write (publish + commit)WeakLowEvents can be lost or orphaned
Saga / 2PCStrongHighComplex failure handling

Further Reading

Concept: The Idempotent Inbox Pattern

The idempotent inbox is the receiving counterpart to the transactional outbox. It durably deduplicates repeated deliveries and can support an effectively exactly-once processing outcome when application work and inbox_mark_processed() share one transaction.

The Problem

In distributed systems, at-least-once delivery is the norm. Messages can be delivered more than once due to:

  • Network timeouts (sender retries after no ack)
  • Consumer crashes (message re-delivered after acknowledgment timeout)
  • Relay restarts (last batch re-delivered)
  • Partition rebalances (offset not committed)

If your service processes the same payment event twice, you might charge the customer twice. If it processes the same order event twice, you might ship duplicate items.

The Solution

The inbox table stores every received message with a unique identifier (deduplication key). Before processing, it checks whether the message has already been seen:

-- The relay writes incoming messages to the inbox
-- Duplicate dedup_keys are silently ignored (idempotent)
INSERT INTO tide.inbox_events (dedup_key, event_type, payload)
VALUES ('evt-123', 'order.created', '{"order_id": "ORD-001"}')
ON CONFLICT (dedup_key) DO NOTHING;

If the same message arrives again (same dedup_key), the INSERT silently does nothing. The message is not processed a second time.

Processing Workflow

1. Message arrives from source (Kafka, NATS, webhook, etc.)
2. Relay writes to inbox (ON CONFLICT DO NOTHING)
3. Application queries inbox for pending messages
4. Application processes the message within a transaction
5. Application marks the message as processed
-- Step 3: Query pending messages
SELECT id, event_type, payload 
FROM tide.inbox_pending('payment_events') 
LIMIT 10;

-- Step 4-5: Process within transaction
BEGIN;
  -- Your business logic here
  INSERT INTO payments (order_id, amount, status) 
  VALUES ('ORD-001', 149.99, 'captured');
  
  -- Mark as processed (atomically with business logic)
  SELECT tide.inbox_mark_processed('payment_events', 42);
COMMIT;

Because the mark-processed call is inside the same transaction as the business logic, either both succeed or both fail. If the transaction rolls back, the message remains pending and will be retried.

Deduplication Keys

The dedup key uniquely identifies a message. Common strategies:

StrategyExampleUse Case
Message ID"evt-abc-123"Source provides unique IDs
Outbox ID"outbox-42"Cross-service pg_tide communication
Composite"order-ORD-001-created"Derived from payload
Kafka offset"topic-0-12345"Kafka partition + offset

pg_tide extracts the dedup key from the native or CloudEvents message key.

Failure Handling

If processing a message fails (business logic error, constraint violation), you have two options:

Retry later:

-- Leave as pending, it will be retried on next poll
-- Optionally record the error for monitoring
SELECT tide.inbox_mark_failed('payment_events', 42, 'Insufficient funds');

Skip permanently:

-- Mark as processed to advance past it
SELECT tide.inbox_mark_processed('payment_events', 42);

Effectively exactly-once processing

The inbox provides a transactional, effectively exactly-once processing outcome (not transport delivery) through this mechanism:

  1. At-least-once delivery: The source may deliver the same message multiple times
  2. Deduplication on write: The inbox's unique constraint prevents duplicate storage
  3. Atomic processing: Business logic + mark-processed in one transaction

The combination makes each unique message eligible for one transactional processing outcome, regardless of how many times the relay delivers it.

When to Use the Inbox

Use the inbox when:

  • You receive events from external systems that may duplicate
  • Processing has side effects (charging money, sending emails, updating state)
  • You need a reliable buffer between message receipt and processing
  • You want to decouple message consumption from message processing

Further Reading

Message Guarantees

pg_tide provides transactional persistence at the PostgreSQL outbox and idempotent processing at the PostgreSQL inbox. The relay delivers each outbox message at least once to the configured destination.

Forward delivery

The relay polls the canonical outbox, publishes a batch, and advances its durable checkpoint only after the destination acknowledges it. A crash between publication and checkpoint commit can therefore produce a duplicate. Native message identities remain stable across retries so supported destinations can apply their own deduplication rules.

Supported outbound destinations are PostgreSQL inbox, NATS JetStream, Apache Kafka, and HTTPS webhook. stdout and file output are diagnostic only.

PostgreSQL inbox

The inbox uses a unique event identity and transactionally records processing state. Applications should process the inbox row and mark it processed in the same transaction when their business operation is transactional.

Failures and replay

Transient destination failures are retried with bounded backoff. Exhausted messages can be sent to the DLQ and replayed after the underlying problem is fixed. Checkpoints are not advanced for a batch that has not been acknowledged.

These guarantees are intentionally at-least-once. pg_tide does not claim exactly-once transport.

Destination boundaries are explicit: PostgreSQL inboxes deduplicate stable event_id values durably, NATS deduplication ends at the stream window, Kafka producer idempotence ends at the producer session, and webhooks require the receiver to deduplicate the stable Idempotency-Key.

Consumption and Relay

The relay is a separate process that reads pipeline configuration from the PostgreSQL catalog. It acquires advisory-lock ownership for each enabled pipeline, polls the canonical outbox, publishes a batch, and records a durable checkpoint.

Forward pipeline

application transaction
        ↓
PostgreSQL outbox → pg-tide relay → inbox, NATS, Kafka, or HTTPS webhook

Create a forward pipeline with tide.relay_set_outbox_v2(). The source is always outbox; sink_type selects one supported destination. stdout and file are available for diagnostics.

Ownership and retries

Only the relay instance holding the pipeline's advisory lock polls it. A second instance waits and takes over after the owner stops. Destination errors use bounded retry and circuit-breaker handling. Messages that exceed the DLQ policy can be replayed after the destination is healthy.

Configuration changes

Catalog updates notify active relay instances. The relay also polls the catalog periodically, so a missed notification does not require a restart.

Outbox API

All outbox functions live in the tide schema.


tide.outbox_create

Create a new named outbox.

SELECT tide.outbox_create(
  p_name              TEXT,
  p_retention_hours   INT  DEFAULT 24,
  p_inline_threshold  INT  DEFAULT 10000
);
ParameterTypeDefaultDescription
p_nameTEXT(required)Unique outbox name
p_retention_hoursINT24Hours to retain consumed messages before cleanup
p_inline_thresholdINT10000Deprecated compatibility value; native publishing does not enforce a pending-row cap

Errors:

  • Raises an error if an outbox with the same name already exists.

Example:

SELECT tide.outbox_create('order-events', 48, 50000);

tide.outbox_publish

Publish a message to a named outbox. Runs within the caller's transaction.

SELECT tide.outbox_publish(
  p_name     TEXT,
  p_payload  JSONB,
  p_headers  JSONB
);
ParameterTypeDescription
p_nameTEXTTarget outbox name
p_payloadJSONBMessage body
p_headersJSONBMetadata (event_type, correlation_id, etc.)

Behavior:

  • Inserts into tide.tide_outbox_messages
  • Fires pg_notify('tide_outbox_new', p_name) to wake the relay
  • Errors if the outbox does not exist or is disabled

Example:

BEGIN;
  INSERT INTO orders (id, total) VALUES (42, 99.99);
  SELECT tide.outbox_publish('order-events',
    '{"order_id": 42, "total": 99.99}'::jsonb,
    '{"event_type": "order.created"}'::jsonb
  );
COMMIT;

tide.outbox_drop

Drop a named outbox and all its messages.

SELECT tide.outbox_drop(
  p_name       TEXT,
  p_if_exists  BOOLEAN DEFAULT false
);
ParameterTypeDefaultDescription
p_nameTEXT(required)Outbox to drop
p_if_existsBOOLEANfalseSuppress error if outbox doesn't exist

Cascades: Removes all messages and consumer groups for this outbox.


tide.outbox_status

Get a status summary for a named outbox.

SELECT tide.outbox_status(p_name TEXT) → JSONB

Returns:

{
  "outbox_name": "orders",
  "pending_messages": 42,
  "retained_messages": 1500,
  "native_safe_offset": 1200,
  "oldest_pending_age_seconds": 3.7,
  "retention_hours": 24
}

Native status and lag are derived from per-pipeline offsets. consumed_at is reported only as deprecated compatibility state.


tide.outbox_sweep

Run one bounded retention batch per selected outbox.

SELECT tide.outbox_sweep(
  p_outbox_name TEXT DEFAULT NULL,
  p_batch_size INTEGER DEFAULT 1000,
  p_dry_run BOOLEAN DEFAULT FALSE
) → JSONB;

p_batch_size must be between 1 and 10,000. Candidates satisfy both the retention cutoff and the minimum checkpoint across all configured native pipelines, consumer groups, and overlapping leases. Disabled pipelines remain participants. Dry-run examines at most p_batch_size + 1 rows and returns has_more without deleting.

The result includes outbox, retention_cutoff, safe_offset, participants, blockers, eligible_in_batch, affected_rows, has_more, highest_deleted_id, duration_ms, and partition_action. A failure is a PostgreSQL error, not a zero-row success.

outbox_truncate_delivered(NULL) is a deprecated compatibility wrapper for one 1,000-row sweep.


tide.outbox_disable

Pause an outbox. Calls to outbox_publish will error while the outbox is disabled.

SELECT tide.outbox_disable(p_name TEXT);

tide.outbox_enable

Resume a previously disabled outbox.

SELECT tide.outbox_enable(p_name TEXT);

Views

tide.outbox_pending

Pending (unconsumed) messages per outbox:

SELECT * FROM tide.outbox_pending;
ColumnTypeDescription
outbox_nameTEXTOutbox name
pending_countBIGINTNumber of unconsumed messages
oldest_atTIMESTAMPTZTimestamp of the oldest pending message
max_idBIGINTHighest retained message ID in this outbox

tide.outbox_retention_status

Offset-aware retention state per outbox: retained row count/bytes, oldest and newest retained timestamps, cutoff, participant count, safe offset, bounded eligible-row preview, blocker names/offsets, cleanup progress, storage layout, and default-partition rows.

tide.relay_pipeline_lag

Exact lag per relay group, pipeline, and outbox. Lag is computed as COUNT(*) WHERE outbox_name = ... AND id > last_change_id; it does not subtract a globally gapped ID from an offset.

Inbox API

All inbox functions live in the tide schema.


tide.inbox_create

Create a named inbox with its message table.

SELECT tide.inbox_create(
  p_name                      TEXT,
  p_schema                    TEXT DEFAULT 'tide',
  p_max_retries               INT  DEFAULT 3,
  p_processed_retention_hours INT  DEFAULT 72,
  p_dlq_retention_hours       INT  DEFAULT 0
);
ParameterTypeDefaultDescription
p_nameTEXT(required)Unique inbox name
p_schemaTEXT'tide'Schema where the inbox table is created
p_max_retriesINT3Max processing attempts before DLQ
p_processed_retention_hoursINT72Hours to keep processed messages
p_dlq_retention_hoursINT0Hours to keep DLQ messages (0 = forever)

Creates: A table {schema}."{name}_inbox" with columns for dedup, retry tracking, and payload storage.

Example:

SELECT tide.inbox_create('payment-webhooks',
  p_max_retries := 5,
  p_processed_retention_hours := 168
);

tide.inbox_drop

Drop a named inbox and its message table.

SELECT tide.inbox_drop(
  p_name       TEXT,
  p_if_exists  BOOLEAN DEFAULT false
);

Cascades: Drops the inbox table and removes the config entry.


tide.inbox_mark_processed

Mark an inbox message as successfully processed.

SELECT tide.inbox_mark_processed(
  p_name      TEXT,
  p_event_id  TEXT
);
ParameterTypeDescription
p_nameTEXTInbox name
p_event_idTEXTThe event_id to mark as processed

Sets processed_at = now() on the matching row. Idempotent — calling it on an already-processed message is a no-op.


tide.inbox_mark_failed

Mark an inbox message as failed. Increments retry_count and stores the error.

SELECT tide.inbox_mark_failed(
  p_name      TEXT,
  p_event_id  TEXT,
  p_error     TEXT
);
ParameterTypeDescription
p_nameTEXTInbox name
p_event_idTEXTThe event_id that failed
p_errorTEXTError message to store

tide.inbox_status

Get status summary for an inbox (or all inboxes).

-- Single inbox
SELECT tide.inbox_status('payment-webhooks') → JSONB

-- All inboxes
SELECT tide.inbox_status() → JSONB

Returns (single inbox):

{
  "inbox_name": "payment-webhooks",
  "pending": 3,
  "dlq_count": 1
}

tide.replay_inbox_messages

Re-queue failed messages for reprocessing. Resets retry_count to 0 and clears last_error.

SELECT tide.replay_inbox_messages(
  p_name       TEXT,
  p_event_ids  TEXT[]
) → BIGINT
ParameterTypeDescription
p_nameTEXTInbox name
p_event_idsTEXT[]Array of event_ids to replay

Returns: Number of messages successfully re-queued.

Example:

SELECT tide.replay_inbox_messages('payment-webhooks',
  ARRAY['evt-003', 'evt-007', 'evt-015']
);

Inbox Table Schema

Each inbox gets a table {schema}."{name}_inbox" with this structure:

ColumnTypeDescription
idBIGINTAuto-generated primary key
event_idTEXTDedup key (UNIQUE)
sourceTEXTWhere the message came from
payloadJSONBMessage body
headersJSONBMetadata
received_atTIMESTAMPTZWhen the message arrived
processed_atTIMESTAMPTZWhen processing completed (NULL = pending)
retry_countINTNumber of failed processing attempts
last_errorTEXTMost recent error message

Relay API

Functions for managing relay pipeline configurations. All live in the tide schema.


tide.relay_set_outbox_v2

Configure a forward relay pipeline (outbox → external sink). Takes a single JSONB config object. The positional relay_set_outbox(...) form was removed in v0.36.0.

SELECT tide.relay_set_outbox_v2(config JSONB);
Config keyTypeDefaultDescription
nameTEXT(required)Unique pipeline name
outboxTEXT(required)Source outbox name (must already exist)
sink_typeTEXT(required)Sink type: inbox, nats, kafka, webhook, stdout, or file
configJSONB{}Sink-specific configuration
wire_formatTEXTnativenative or cloudevents
batch_sizeINT100Messages per relay batch
enabledBOOLEANtrueWhether the pipeline is active

The relay always polls the canonical tide.tide_outbox_messages table.

Upsert behavior: If a pipeline with the same name exists, its configuration is updated.

Example:

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-nats',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', jsonb_build_object(
      'url', 'tls://nats.example:4222',
      'subject_template', 'orders.{event_type}'
    ),
    'batch_size', 200
  )
);

tide.relay_enable

Enable a previously disabled pipeline.

SELECT tide.relay_enable(p_name TEXT);

Fires pg_notify('tide_relay_config', name) to trigger hot-reload in the relay.


tide.relay_disable

Disable a pipeline (stops processing without deleting config).

SELECT tide.relay_disable(p_name TEXT);

tide.relay_delete

Permanently delete a pipeline configuration.

SELECT tide.relay_delete(p_name TEXT);

tide.relay_get_config

Retrieve the full configuration for a pipeline.

SELECT tide.relay_get_config(p_name TEXT) → JSONB

Returns the stored config JSONB for the named pipeline.


tide.relay_list_configs

List all configured relay pipelines.

SELECT tide.relay_list_configs() → JSONB

Returns a JSON array of all pipelines with their direction and enabled status:

[
  {"name": "orders-to-nats", "direction": "outbox", "enabled": true},
  {"name": "webhooks-in", "direction": "inbox", "enabled": true}
]

Consumer Groups API

Functions for managing consumer groups. All live in the tide schema.


tide.create_consumer_group

Create a named consumer group for an outbox.

SELECT tide.create_consumer_group(
  p_name               TEXT,
  p_outbox             TEXT,
  p_auto_offset_reset  TEXT     DEFAULT 'earliest',
  p_if_not_exists      BOOLEAN  DEFAULT false
);
ParameterTypeDefaultDescription
p_nameTEXT(required)Unique group name
p_outboxTEXT(required)Outbox this group consumes from
p_auto_offset_resetTEXT'earliest'earliest, latest, or none
p_if_not_existsBOOLEANfalseSuppress error if already exists

Errors:

  • Outbox must exist
  • Group name must be unique (unless p_if_not_exists = true)
  • p_auto_offset_reset must be one of: earliest, latest, none

tide.drop_consumer_group

Drop a consumer group and all its offset/lease records.

SELECT tide.drop_consumer_group(
  p_name       TEXT,
  p_if_exists  BOOLEAN DEFAULT false
);

tide.commit_offset

Commit a consumer's processing position.

SELECT tide.commit_offset(
  p_group       TEXT,
  p_consumer    TEXT,
  p_last_offset BIGINT
);
ParameterTypeDescription
p_groupTEXTConsumer group name
p_consumerTEXTConsumer identifier (e.g., relay instance ID)
p_last_offsetBIGINTLast successfully processed message ID

Behavior:

  • Upserts into tide.tide_consumer_offsets
  • Updates last_heartbeat to now()
  • Releases any visibility lease held by this consumer

tide.consumer_heartbeat

Update the heartbeat timestamp for a consumer.

SELECT tide.consumer_heartbeat(
  p_group     TEXT,
  p_consumer  TEXT
);

Call this periodically (e.g., every 10 seconds) while processing to signal liveness.


Views

tide.consumer_lag

Per-consumer lag relative to the latest outbox message:

SELECT * FROM tide.consumer_lag;
ColumnTypeDescription
group_nameTEXTConsumer group
outbox_nameTEXTSource outbox
consumer_idTEXTConsumer identifier
committed_offsetBIGINTLast committed position
lagBIGINTMessages behind (max_id - committed_offset)
last_heartbeatTIMESTAMPTZLast heartbeat time

Catalog Tables

pg_tide stores all state in relational tables within the tide schema. This page documents the underlying tables that power the SQL API.


tide.tide_outbox_config

One row per named outbox.

ColumnTypeDescription
outbox_nameTEXT (PK)Unique outbox identifier
retention_hoursINTHours to retain consumed messages
inline_thresholdINTDeprecated compatibility value; not a native pending-row cap
enabledBOOLEANWhether publishing is allowed
created_atTIMESTAMPTZCreation timestamp

tide.tide_outbox_messages

Shared message store for all outboxes.

ColumnTypeDescription
idBIGINT (PK)Auto-incrementing message ID
outbox_nameTEXT (FK)Which outbox this belongs to
payloadJSONBMessage body
headersJSONBMessage metadata
created_atTIMESTAMPTZPublication time
consumed_atTIMESTAMPTZLegacy/global-consumer status; not authoritative for native delivery
consumer_groupTEXTWhich group consumed it

Indexes:

  • idx_tide_outbox_messages_poll — unconditional (outbox_name, id) index for native relay polling
  • cleanup-supporting indexes selected by the operational query plans

The parent remains public when optional ID-range partitions are enabled. Child names are numeric bounds, not logical outbox names.


tide.tide_consumer_groups

Named consumer groups with offset reset policy.

ColumnTypeDescription
group_nameTEXT (PK)Unique group name
outbox_nameTEXT (FK)Outbox being consumed
auto_offset_resetTEXTearliest, latest, or none
created_atTIMESTAMPTZCreation timestamp

tide.tide_consumer_offsets

Per-consumer committed offsets and heartbeats.

ColumnTypeDescription
group_nameTEXT (PK, FK)Consumer group
consumer_idTEXT (PK)Consumer instance identifier
committed_offsetBIGINTLast processed message ID
last_heartbeatTIMESTAMPTZLast liveness signal

tide.tide_consumer_leases

Visibility leases for in-flight message batches.

ColumnTypeDescription
group_nameTEXT (PK, FK)Consumer group
consumer_idTEXT (PK, FK)Consumer instance
lease_startBIGINTFirst message ID in the leased batch
lease_endBIGINTLast message ID in the leased batch
expires_atTIMESTAMPTZWhen the lease expires

tide.tide_inbox_config

Named inbox configurations.

ColumnTypeDescription
inbox_nameTEXT (PK)Unique inbox identifier
inbox_schemaTEXTSchema containing the inbox table
max_retriesINTAttempts before DLQ
processed_retention_hoursINTHours to keep processed messages
dlq_retention_hoursINTHours to keep DLQ messages
created_atTIMESTAMPTZCreation timestamp

tide.relay_outbox_config

Forward relay pipeline definitions.

ColumnTypeDescription
nameTEXT (PK)Unique pipeline name
enabledBOOLEANWhether the pipeline is active
configJSONBFull pipeline config (outbox, sink, params)

Triggers: relay_outbox_config_notify — fires pg_notify('tide_relay_config', ...) on changes.


tide.relay_inbox_config

Reverse relay pipeline definitions.

ColumnTypeDescription
nameTEXT (PK)Unique pipeline name
enabledBOOLEANWhether the pipeline is active
configJSONBFull pipeline config (inbox, source, params)

Triggers: relay_inbox_config_notify — fires pg_notify('tide_relay_config', ...) on changes.


tide.relay_consumer_offsets

Durable per-pipeline offset tracking for the relay binary.

ColumnTypeDescription
relay_group_idTEXT (PK)Relay deployment group
pipeline_idTEXT (PK)Pipeline name
outbox_nameTEXT (PK)Logical outbox scope
last_change_idBIGINTHighest acknowledged message ID
updated_atTIMESTAMPTZLast update timestamp

The primary key is (relay_group_id, pipeline_id, outbox_name). Offset writes are monotonic, so a lower acknowledgment cannot rewind a higher stored value.


tide.outbox_cleanup_state

One row per outbox recording the last successful bounded sweep:

ColumnTypeDescription
outbox_nameTEXT (PK)Logical outbox
last_success_atTIMESTAMPTZLast committed cleanup
last_safe_offsetBIGINTMinimum participant checkpoint used
highest_deleted_idBIGINTHighest deleted message ID
last_batch_rowsBIGINTRows deleted by the last batch
cumulative_rows_deletedBIGINTTotal rows deleted
last_duration_msDOUBLE PRECISIONLast batch duration
last_partition_actionTEXTPartition action or none

The state is updated in the same transaction as deletion or partition removal.

tide.outbox_storage_config

Singleton physical-layout contract:

ColumnTypeDescription
layoutTEXTheap, id_range, or legacy_noncanonical
partition_spanBIGINTID range for future children
premakeINTEGERFuture children to maintain
last_maintenance_atTIMESTAMPTZLast successful provisioning

tide.tide_partition_events

Bounded maintenance audit rows for child creation, default-partition drains, detach/drop decisions, and failures. It contains no payloads.

tide.outbox_retention_status and tide.relay_pipeline_lag

These views expose the offset-aware retention contract and exact per-pipeline lag described in the Outbox API. Prefer them over outbox_pending and consumer_lag for native operational decisions.

Relay Configuration

The pg-tide relay binary is configured through three layers, applied in order of increasing priority:

  1. Default values — sensible defaults built into the binary
  2. TOML config file — specified via --config or PG_TIDE_CONFIG
  3. CLI flags / environment variables — highest precedence

Pipeline configuration (outbox sources, sink destinations, batch sizes) lives in PostgreSQL — not in the TOML file. The relay loads pipeline config from the tide.relay_outbox_config and tide.relay_inbox_config catalog tables at startup and reloads dynamically via LISTEN/NOTIFY.


Quick Start

The only required parameter is the PostgreSQL connection URL:

pg-tide run --postgres-url "postgres://user:pass@localhost:5432/mydb"

For production, use environment variables:

export PG_TIDE_POSTGRES_URL="postgres://relay:${DB_PASSWORD}@pghost:5432/app"
export PG_TIDE_METRICS_ADDR="0.0.0.0:9090"
export PG_TIDE_LOG_FORMAT="json"
export PG_TIDE_GROUP_ID="prod-relay"

pg-tide run

TOML Configuration File

For complex setups, use a TOML file:

# relay.toml
postgres_url = "${ENV:DATABASE_URL}"
metrics_addr = "0.0.0.0:9090"
log_format = "json"
log_level = "info"
discovery_interval_secs = 30
default_batch_size = 100
relay_group_id = "production"
sink_max_inflight = 1000
pg-tide run --config relay.toml

Configuration Reference

ParameterCLI FlagEnvironment VariableDefaultDescription
postgres_url--postgres-urlPG_TIDE_POSTGRES_URL(required)PostgreSQL connection URL
metrics_addr--metrics-addrPG_TIDE_METRICS_ADDR0.0.0.0:9090Prometheus metrics and /livez//readyz bind address
log_format--log-formatPG_TIDE_LOG_FORMATtextLog output format: text or json
log_level--log-levelPG_TIDE_LOG_LEVELinfoLog verbosity: error, warn, info, debug, trace
relay_group_id--relay-group-idPG_TIDE_GROUP_IDdefaultRelay group identifier for advisory lock namespacing
discovery_interval_secs——30Seconds between pipeline discovery polls
default_batch_size——100Default messages per batch when not specified per-pipeline
sink_max_inflight——1000Maximum in-flight messages before upstream polling pauses. 0 = unlimited
max_owned_pipelines--max-pipelinesPG_TIDE_MAX_PIPELINES50Maximum pipelines owned by one relay
max_connections--max-connectionsPG_TIDE_MAX_CONNECTIONS52Maximum coordinator pool connections
sweep_interval_hours--sweep-interval-hoursPG_TIDE_SWEEP_INTERVAL_HOURS24Delivery-receipt cleanup interval
—--drain-timeoutPG_TIDE_DRAIN_TIMEOUT30Seconds to wait for in-flight messages to drain on SIGTERM
—--configPG_TIDE_CONFIG—Path to TOML config file

Environment Variable Substitution

Connection strings in TOML files support ${ENV:VAR_NAME} substitution:

postgres_url = "postgres://${ENV:DB_USER}:${ENV:DB_PASSWORD}@${ENV:DB_HOST}:5432/${ENV:DB_NAME}"

This resolves at relay startup time using the process environment. Unknown variables are left as-is (the relay will report a connection error rather than silently using a broken URL).


Relay Group ID

The relay_group_id parameter is critical for multi-deployment setups. It controls:

  1. Advisory lock namespacing — each relay instance acquires a PostgreSQL advisory lock scoped to its group ID + pipeline name. Only one relay per group can own a given pipeline.
  2. Consumer group offset tracking — progress is tracked per relay group, allowing multiple independent relay deployments to process the same outbox.

Single deployment (default):

pg-tide run --relay-group-id "default"

Multi-region deployment:

# US region — processes orders outbox → US NATS
pg-tide run --relay-group-id "us-east" --postgres-url "..."

# EU region — processes same orders outbox → EU NATS
pg-tide run --relay-group-id "eu-west" --postgres-url "..."

Each group tracks its own offsets independently — the EU relay won't skip messages just because the US relay already processed them.


Pipeline Configuration (in PostgreSQL)

Pipelines are configured via SQL, not via the relay's TOML/CLI config. The relay discovers pipelines from two catalog tables:

Forward Pipelines (Outbox → Sink)

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-nats',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', '{
      "url": "tls://nats.example:4222",
      "subject": "orders.{event_type}"
    }'::jsonb
  )
);

Enabling / Disabling Pipelines

-- Disable a pipeline (relay will stop it on next discovery cycle)
SELECT tide.relay_enable('orders-nats', false);

-- Re-enable
SELECT tide.relay_enable('orders-nats', true);

Pipeline changes are picked up via:

  1. LISTEN/NOTIFY — immediate reaction to config changes
  2. Periodic polling — every discovery_interval_secs as a fallback

Hot Reload

The relay watches for NOTIFY signals on the tide_relay_config_changed channel. When you modify a pipeline via tide.relay_set_outbox_v2(), the trigger fires a notification and the relay reloads within seconds — no restart required.

If LISTEN is interrupted (connection blip), the periodic discovery poll acts as a safety net.


High Availability

Run multiple relay instances with the same relay_group_id:

# Instance 1
pg-tide run --relay-group-id "prod" --postgres-url "..."

# Instance 2 (standby — takes over if instance 1 dies)
pg-tide run --relay-group-id "prod" --postgres-url "..."

Advisory locks ensure only one instance owns each pipeline at a time. If the owning instance dies, its locks are released and another instance acquires them on the next discovery cycle.


Backpressure

The sink_max_inflight parameter controls backpressure behavior:

  • When the number of in-flight (unacknowledged) messages reaches this limit, the relay pauses polling from the outbox
  • Once the sink acknowledges enough messages to drop below the threshold, polling resumes
  • Set to 0 to disable backpressure (not recommended for production)

This prevents the relay from overwhelming a slow sink while still allowing high throughput for fast sinks.


Graceful Shutdown

On SIGTERM:

  1. The relay stops accepting new pipeline ownership
  2. Active pipelines finish their current batch
  3. If batches don't complete within --drain-timeout seconds (default: 30), the relay exits
  4. Unfinished messages will be redelivered when the relay restarts (at-least-once guarantee)

Envelope Encryption (KMS)

pg-tide supports AES-256-GCM envelope encryption via the kms-local feature. Encryption is enabled per-outbox in the tide.outbox_encryption_config catalog table.

KMS Provider Availability

ProviderFeature flagStatusNotes
LocalKeyFilekms-localFully implemented (v0.35.0)AES-256-GCM with key rotation via key_path_previous. Ready for production use in non-cloud environments.

Unsupported providers fail validation or worker construction before the source polls messages. There is no plaintext fallback.

LocalKeyFile Configuration

Configure encryption through the outbox catalog API; do not add a [pipelines] section to the process TOML.

Key files must contain exactly 64 hex characters (32 bytes / 256 bits). Generate a new key: openssl rand -hex 32 > /etc/pg-tide/kms/current.key


Example: Production Configuration

# /etc/pg-tide/relay.toml
postgres_url = "${ENV:DATABASE_URL}"
metrics_addr = "0.0.0.0:9090"
log_format = "json"
log_level = "info"
discovery_interval_secs = 10
default_batch_size = 500
relay_group_id = "production"
sink_max_inflight = 5000
# systemd unit or container entrypoint
PG_TIDE_DRAIN_TIMEOUT=60 pg-tide run --config /etc/pg-tide/relay.toml

CLI reference

The pg-tide binary runs the PostgreSQL outbox relay and provides focused diagnostic and recovery commands.

pg-tide run
pg-tide doctor --postgres-url "$DATABASE_URL"
pg-tide status --postgres-url "$DATABASE_URL"
pg-tide config validate --pipeline orders-nats --postgres-url "$DATABASE_URL"
pg-tide config export --postgres-url "$DATABASE_URL"
pg-tide migrate-config --postgres-url "$DATABASE_URL"
pg-tide maintenance sweep --postgres-url "$DATABASE_URL"
pg-tide replay preview --outbox orders --from-id 100 --to-id 200
pg-tide replay dlq-requeue --pipeline orders-nats --dedup-key orders:42:0

--output json emits the stable v1 envelope for doctor, status, config commands, and maintenance sweep. Exit code 0 means success; a non-zero exit code means the command could not complete.

migrate-config is read-only. It inventories catalog rows that would block a v0.49.0 upgrade and prints PGTIDE_CONFIG_UNSUPPORTED_SURFACE with the supported alternative. Export affected rows before disabling, replacing, or deleting them.

Global options include --postgres-url, --postgres-url-file, --config, --output, --log-level, and --log-format. run also supports --self-test; it checks the installed extension against the embedded lifecycle compatibility policy before reporting readiness.

Error Handling

The pg-tide relay is designed to be resilient in the face of failures. It retries uncommitted batches and never treats an uncertain checkpoint as success. The transport guarantee is at-least-once; downstream durable deduplication is required for an effectively exactly-once outcome.


Error Philosophy

pg_tide's error handling follows a simple principle: transient errors are retried, and permanent errors receive an explicit terminal disposition. Decode, transform, sink, checkpoint, and DLQ failures retain the source checkpoint unless the documented DLQ path succeeds atomically.

The relay distinguishes between:

  • Transient errors — network timeouts, temporary unavailability, connection resets. These will succeed if retried.
  • Permanent errors — malformed payloads, deserialization failures, invalid configuration. These will never succeed regardless of retries.

Retry Strategy

All transient errors trigger exponential backoff retry with jitter:

ParameterValuePurpose
Initial delay100msStart retrying quickly for brief hiccups
Maximum delay30 secondsCap the backoff to avoid minute-long waits
Jitter±20%Prevent thundering herd when multiple relays reconnect simultaneously
Maximum retriesUnlimitedThe relay retries while the source retains the uncommitted batch
Backoff multiplier2×Each retry doubles the delay (100ms → 200ms → 400ms → ...)

The backoff sequence looks like: 100ms, 200ms, 400ms, 800ms, 1.6s, 3.2s, 6.4s, 12.8s, 25.6s, 30s, 30s, 30s...

Jitter randomizes each delay by ±20%, so the actual sequence might be: 85ms, 220ms, 350ms, 900ms, etc. This prevents synchronized retry storms.


Error Categories

Connection errors (PostgreSQL)

Symptoms: Relay logs "PostgreSQL connection failed, retrying" or "postgres error"

What happens:

  1. The relay logs a warning with connection details
  2. Enters reconnection mode with exponential backoff (100ms → 30s)
  3. All pipelines are paused (they can't function without the database)
  4. On reconnect, advisory locks are re-acquired
  5. Pipeline processing resumes from the last committed offset
  6. The source checkpoint remains uncommitted; retry may duplicate a previously acknowledged downstream publish

Common causes:

  • PostgreSQL is restarting or failing over
  • Network partition between relay and database
  • Connection pool exhaustion
  • Authentication failure (password rotation)

Resolution: Usually self-healing. The relay reconnects automatically when PostgreSQL is available again. If the issue is persistent (auth failure), fix the credentials and the relay will reconnect on its next attempt.

Sink errors (delivery failures)

Symptoms: Relay logs "sink publish error" or "sink unhealthy", Prometheus counter pg_tide_relay_publish_errors_total increases.

What happens:

  1. The source checkpoint remains pending; a prior sink success may be retried
  2. The relay retries delivery with exponential backoff until the sink recovers
  3. Prometheus metrics track pg_tide_relay_publish_errors_total{pipeline="..."}
  4. The health endpoint reports unhealthy (503) for affected pipelines
  5. Once the sink recovers, delivery resumes automatically

Common causes:

  • Downstream system (Kafka, NATS, webhook endpoint) is temporarily unavailable
  • Network issues between relay and sink
  • Sink is overloaded and rejecting new messages (backpressure)
  • TLS certificate issues

Resolution: Usually self-healing. Monitor the error rate and investigate if it persists beyond expected maintenance windows.

Unsupported configuration

Symptoms: Relay startup reports PGTIDE_CONFIG_UNSUPPORTED_SURFACE.

What happens: The pipeline is rejected before polling or catalog mutation. Export the configuration, replace the removed source, sink, or wire format with a supported value, and retry.

Payload errors (permanent)

Symptoms: Relay logs "payload decode error" or "unsupported outbox payload version"

What happens:

  1. The error is logged with full context (outbox name, message ID, raw payload excerpt)
  2. The pipeline pauses or routes the complete failed batch to the atomic DLQ
  3. The offset advances only after that terminal disposition is durable
  4. Prometheus tracks the error count

Common causes:

  • Application published malformed JSONB that the relay cannot interpret
  • Message format version mismatch (relay expects v2, message is v1)
  • Corruption (extremely rare)

Resolution: Investigate the specific message. Fix the publishing code if it's generating invalid payloads. For format mismatches, upgrade the relay or add backward-compatible handling.

Configuration errors

Symptoms: Relay logs "config error" or "invalid config for pipeline" at startup or after hot-reload.

What happens:

  1. If the error is in the TOML file, the relay refuses to start
  2. If the error is in a pipeline config (in PostgreSQL), that specific pipeline is skipped
  3. Other pipelines continue to operate normally

Common causes:

  • Missing required config key (e.g., no brokers for Kafka sink)
  • Invalid value (e.g., non-numeric batch_size)
  • Unsupported backend name

Resolution: Fix the configuration. For pipeline configs, update the JSONB in the database and the relay will pick up the correction via hot-reload.


Graceful Shutdown

When the relay receives SIGTERM or SIGINT:

  1. Stop accepting new work — no new batches are fetched from the outbox
  2. Drain in-flight messages — wait for currently-delivering batches to complete (up to a drain timeout)
  3. Commit final offsets — record the last successfully delivered position
  4. Release the worker's ownership session — only after the worker exits
  5. Close connections — cleanly disconnect from PostgreSQL and sinks
  6. Exit with code 0 — signal success to the process manager

The drain timeout prevents the relay from hanging indefinitely if a sink is unresponsive during shutdown. Messages that weren't committed will be re-delivered by the next relay instance (and deduplicated by the inbox if applicable).


Dead-Letter Queue (Inbox Side)

For inbox processing, messages that fail are managed through the inbox's built-in retry and failure tracking.

How messages enter the DLQ

  1. Your application reads a message from the inbox and attempts to process it
  2. Processing fails (external API timeout, validation error, business rule violation)
  3. You call tide.inbox_mark_failed(inbox_name, event_id, error_message)
  4. The message's retry_count is incremented and last_error is recorded
  5. After max_retries failures, the message is effectively dead-lettered

Querying the DLQ

-- Find all dead-lettered messages in an inbox
SELECT event_id, payload, retry_count, last_error, received_at
FROM tide."my-inbox_inbox"
WHERE processed_at IS NULL
  AND retry_count >= 5  -- assuming max_retries = 5
ORDER BY received_at;

Investigating failures

-- Group DLQ messages by error pattern
SELECT
  left(last_error, 50) AS error_pattern,
  count(*) AS message_count,
  min(received_at) AS earliest,
  max(received_at) AS latest
FROM tide."my-inbox_inbox"
WHERE processed_at IS NULL AND retry_count >= 5
GROUP BY left(last_error, 50)
ORDER BY message_count DESC;

Replaying messages

After fixing the underlying issue, replay specific messages or all DLQ messages:

-- Replay specific messages
SELECT tide.replay_inbox_messages('my-inbox',
  ARRAY['evt-001', 'evt-002', 'evt-003']);

-- Replay all DLQ messages for an inbox
SELECT tide.replay_inbox_messages('my-inbox',
  (SELECT array_agg(event_id)
   FROM tide."my-inbox_inbox"
   WHERE processed_at IS NULL AND retry_count >= 5)
);

Replaying resets retry_count to 0, making messages eligible for normal processing again.


Extension Error Reference

Errors raised by pg_tide SQL functions:

Error messageRaised byWhat it means
outbox already exists: {name}outbox_createAn outbox with this name already exists. Use p_if_not_exists := true to suppress.
outbox not found: {name}outbox_publish, outbox_drop, outbox_status, outbox_enable/disableNo outbox with this name exists. Create it first with outbox_create.
inbox already exists: {name}inbox_createAn inbox with this name already exists.
inbox not found: {name}inbox_drop, inbox_mark_processed/failed, inbox_statusNo inbox with this name exists.
relay pipeline not found: {name}relay_enable/disable/delete/get_configNo pipeline with this name in the catalog.
invalid argument: {details}VariousA parameter value is invalid (e.g., negative retention_hours).
SPI error: {details}VariousInternal database error during SPI execution.

Handling extension errors in PL/pgSQL

DO $$
BEGIN
  PERFORM tide.outbox_publish('maybe-missing', '{}'::jsonb, '{}'::jsonb);
EXCEPTION
  WHEN OTHERS THEN
    RAISE NOTICE 'Publish failed: %', SQLERRM;
    -- Handle gracefully: log, retry, or use a fallback
END $$;

Relay Error Reference

Errors logged by the pg-tide relay binary:

ErrorCategoryWhat it meansSelf-healing?
postgres errorConnectionDatabase communication failure✓ (reconnects)
postgres connection failedConnectionCannot reach PostgreSQL✓ (retries)
config errorConfigurationInvalid TOML or missing field✗ (fix config)
invalid config for pipelineConfigurationPipeline JSONB validation failure✗ (fix SQL config)
pipeline not foundConfigurationReferenced pipeline doesn't exist✗ (create pipeline)
missing required config keyConfigurationA required backend config key is missing✗ (fix SQL config)
unsupported outbox payload versionPayloadMessage format version mismatch✗ (upgrade relay or fix publisher)
payload decode errorPayloadCannot deserialize message✗ (fix publisher)
sink publish errorDeliverySink rejected or timed out✓ (retries)
sink unhealthyDeliverySink not accepting connections✓ (retries)
source poll errorIngestionSource read failure✓ (retries)
channel closedInternalInternal communication channel dropped✓ (relay recovers)

Monitoring Errors

Prometheus metrics for error tracking

# Total delivery errors by pipeline (should be 0 in steady state)
rate(pg_tide_relay_publish_errors_total[5m])

# Unhealthy pipelines (immediate alert)
pg_tide_relay_pipeline_healthy == 0

# Error rate as a percentage of total deliveries
rate(pg_tide_relay_publish_errors_total[5m])
  / rate(pg_tide_relay_messages_published_total[5m])

Alerting rules

- alert: PgTideDeliveryErrors
  expr: rate(pg_tide_relay_publish_errors_total[5m]) > 0
  for: 2m
  labels:
    severity: warning
  annotations:
    summary: "Delivery errors on pipeline {{ $labels.pipeline }}"
    description: "The relay is experiencing delivery failures. Check sink availability."

- alert: PgTidePipelineDown
  expr: pg_tide_relay_pipeline_healthy == 0
  for: 1m
  labels:
    severity: critical
  annotations:
    summary: "Pipeline {{ $labels.pipeline }} is unhealthy"
    description: "Immediate investigation required. Messages are accumulating."

Log-based monitoring

With structured JSON logging (--log-format json), you can filter and alert on error logs:

{"level":"error","pipeline":"orders-to-kafka","error":"sink publish error: BrokerNotAvailable","msg":"delivery failed, will retry","timestamp":"2025-01-15T10:30:00Z"}

Key fields to monitor:

  • level=error — any error-level log indicates a problem
  • pipeline — identifies which pipeline is affected
  • error — the specific error message for diagnosis

Monitoring

Scrape /metrics from the relay. Use /livez for Kubernetes liveness and /readyz for readiness; /health is a legacy compatibility endpoint and must not be used for both probes.

EndpointPurpose
GET /metricsPrometheus exposition
GET /livezProcess liveness
GET /readyzPipeline/readiness state

The metric contract uses names such as pg_tide_relay_pipeline_healthy, pg_tide_relay_consumer_lag, pg_tide_relay_publish_errors_total, pg_tide_relay_retry_state, and pg_tide_relay_dlq_depth. Do not substitute unprefixed names or infer health from missing series.

Install the core dashboard and alert rules from pg-tide/dashboards/; the PostgreSQL detail dashboard is separate and optional. For incidents start with pg-tide doctor --output json and pg-tide status --output json, then follow the runbook index.

Prometheus metrics

The relay exposes /metrics, /livez, and /readyz on the configured metrics address (default 0.0.0.0:9090). /livez answers whether the process is alive; /readyz answers whether it can serve owned pipelines. A pipeline failure must remove a pod from service, not cause a restart loop.

Core metrics

All relay metrics use the pg_tide_relay_ prefix. Labels are only documented where emitted by the relay (pipeline, direction, and metric-specific labels).

MetricMeaning
pg_tide_relay_messages_published_totalSuccessful sink publishes
pg_tide_relay_messages_consumed_totalMessages read from sources
pg_tide_relay_publish_errors_totalFailed publish attempts
pg_tide_relay_pipeline_healthy1 when pipeline is healthy, 0 otherwise
pg_tide_relay_consumer_lagPending source messages
pg_tide_relay_delivery_latency_secondsDelivery latency histogram
pg_tide_relay_retry_stateCurrent retry/backoff state
pg_tide_relay_dlq_depthUnresolved DLQ entries
pg_tide_relay_owned_pipelinesPipelines owned by this relay
pg_tide_relay_owned_async_tasksDirectly owned long-lived relay tasks; kind is fixed-cardinality
pg_tide_relay_pool_connectionsPool connections by state

See pg-tide/dashboards/relay-health.json for the core dashboard and pg-tide/dashboards/alerts.yaml for actionable thresholds. No-data is unknown, never healthy. Use the operations runbooks for incident response.

sum by (pipeline) (rate(pg_tide_relay_messages_published_total[5m]))
pg_tide_relay_consumer_lag
histogram_quantile(0.99, sum by (le,pipeline) (rate(pg_tide_relay_delivery_latency_seconds_bucket[5m])))

Destinations Overview

The relay delivers PostgreSQL outbox messages to the supported destinations below. All deliveries are at-least-once and advance the source checkpoint only after the destination acknowledges the batch.

DestinationUse case
PostgreSQL InboxIdempotent cross-service delivery inside PostgreSQL
NATS JetStreamLow-latency durable messaging
Apache KafkaPartitioned event streaming
HTTPS WebhookDelivery to an external HTTP service
stdout and fileLocal diagnostics and debugging

Configure every destination with tide.relay_set_outbox_v2() and select the destination with sink_type. Use secret references for credentials and URLs; the relay never writes resolved secret values to logs or metric labels.

See the connector compatibility matrix for tested versions, profiles, and evidence.

PostgreSQL Inbox

The PostgreSQL Inbox sink delivers outbox messages to a pg_tide inbox on the relay database or on another PostgreSQL database. This enables cross-service messaging entirely within PostgreSQL with at-least-once delivery and durable event_id deduplication.

When to Use This Sink

Choose the PostgreSQL Inbox sink when you need direct database-to-database messaging. Messages flow from outbox in Database A to inbox in Database B with at-least-once transport and durable event_id deduplication.

Configuration

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-warehouse',
    'outbox', 'orders',
    'sink_type', 'inbox',
    'config', '{
        "postgres_url": "${env:WAREHOUSE_DB_URL}",
        "inbox": "incoming_orders",
        "batch_size": 100
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
sink_typestring—Must be "inbox"
postgres_urlstringrelay databaseOptional PostgreSQL URL for a remote target database
inboxstring—Target inbox name (must exist on the selected database)
batch_sizeint100Messages per batch insert

Delivery Guarantees

The inbox sink provides durable destination deduplication. Each message's dedup_key is used as the inbox identifier; if the same message is delivered twice after a relay restart, the inbox's UNIQUE constraint rejects the duplicate. The transport remains at-least-once; application processing can use the unique event_id constraint to make repeated deliveries harmless.

Troubleshooting

  • "Inbox not found" — Create the inbox on the target database: SELECT tide.inbox_create('incoming_orders')
  • "Connection refused" — Verify the target database URL is reachable from the relay
  • "Duplicate key violation" — This should normally be absorbed by the inbox's ON CONFLICT DO NOTHING path; inspect schema and permissions if it surfaces as an error.

Further Reading

NATS JetStream

The NATS sink publishes native pg_tide JSON or CloudEvents from the PostgreSQL outbox to a JetStream subject. It is outbound only.

{
  "source_type": "outbox",
  "source": {"outbox": "orders"},
  "sink_type": "nats",
  "sink": {
    "url": "tls://nats:4222",
    "subject": "orders.events"
  },
  "wire_format": "native"
}

Production NATS connections use tls:// and verify the server certificate. For a local plaintext broker only, set allow_insecure: true; the relay logs that development override explicitly.

Use subject_template when the subject should include outbox metadata. JetStream acknowledgments and the stable outbox identity provide at-least-once delivery. Nats-Msg-Id suppresses a retry only while the stream's configured duplicate window is active; a retry after that window may appear twice.

Apache Kafka

The Kafka sink publishes native pg_tide JSON or CloudEvents from the PostgreSQL outbox. It is outbound only and uses Kafka producer acknowledgments.

{
  "source_type": "outbox",
  "source": {"outbox": "orders"},
  "sink_type": "kafka",
  "sink": {
    "brokers": "kafka:9092",
    "topic": "orders"
  },
  "wire_format": "native"
}

Use topic_template instead of topic when the topic is derived from message metadata. Configure TLS and SASL through the Kafka client connection settings. The sink preserves at-least-once delivery; consumers should use the stable outbox identity for deduplication. Producer idempotence is session-bounded, so a restart after broker acknowledgment can produce a consumer-visible duplicate.

HTTPS webhook

The webhook sink publishes native pg_tide JSON or CloudEvents to an HTTPS endpoint. It is outbound only and rejects private or link-local destinations by default.

{
  "source_type": "outbox",
  "source": {"outbox": "orders"},
  "sink_type": "webhook",
  "sink": {
    "url": "https://events.example.test/pg-tide",
    "timeout_secs": 30,
    "ssrf_protection": true,
    "signing_secret": "${env:WEBHOOK_SECRET}"
  },
  "wire_format": "cloudevents"
}

HTTPS is required unless allow_http is explicitly enabled for local development. Retries are bounded and successful 2xx responses acknowledge the batch. Retries carry the same Idempotency-Key; one effect requires receiver- side deduplication. Configure HMAC signing when the receiver needs request authentication.

Diagnostic stdout and file output

stdout and file are small diagnostic sinks. They are useful for local inspection and smoke tests, not production delivery guarantees.

{
  "source_type": "outbox",
  "source": {"outbox": "orders"},
  "sink_type": "stdout",
  "sink": {"format": "jsonl"}
}

For file output, provide a path:

{
  "sink_type": "file",
  "sink": {"path": "/var/log/pg-tide/orders.jsonl", "format": "jsonl"}
}

Supported formats are jsonl and pretty.

Deployment

This page covers everything you need to deploy pg_tide in production: from a single-machine setup to highly-available Kubernetes deployments. pg_tide has two components to deploy — the PostgreSQL extension and the relay binary — and both are designed to be operationally simple.


Components Overview

ComponentWhat it isWhere it runsState
pg_tide extensionSQL functions + catalog tablesInside your PostgreSQL databaseAll state in PostgreSQL tables
pg-tide relayStandalone binary that bridges messagesAnywhere with network access to PostgreSQL + sinksStateless — all state in PostgreSQL

The relay binary is completely stateless. You can kill it, restart it, replace it, scale it up or down — it always recovers from the last committed offset stored in PostgreSQL. This makes deployment and upgrades straightforward.


Extension Deployment

Install the extension on your PostgreSQL 18 server:

CREATE EXTENSION pg_tide;

The extension creates the tide schema with all required tables, views, triggers, and functions. It requires no background workers, no shared memory, and no file system access — making it compatible with:

  • All managed PostgreSQL services (RDS, Cloud SQL, Azure Database, Supabase, Neon)
  • Connection poolers (PgBouncer, PgCat, Pgpool-II)
  • CloudNativePG and other Kubernetes operators
  • Standard replication setups (streaming, logical)

Permissions

The extension can be installed by any user with CREATE privilege on the database. No superuser required. After installation, grant appropriate permissions:

-- Application users can publish to outboxes
GRANT USAGE ON SCHEMA tide TO app_user;
GRANT EXECUTE ON FUNCTION tide.outbox_publish(text, jsonb, jsonb) TO app_user;

-- Relay user needs read/write access to message tables
CREATE ROLE pg_tide_relay LOGIN PASSWORD 'strong-password';
GRANT USAGE ON SCHEMA tide TO pg_tide_relay;
GRANT SELECT, UPDATE ON tide.tide_outbox_messages TO pg_tide_relay;
GRANT SELECT ON tide.tide_outbox_config TO pg_tide_relay;
GRANT SELECT ON tide.relay_outbox_config TO pg_tide_relay;
GRANT SELECT ON tide.relay_inbox_config TO pg_tide_relay;
GRANT SELECT, INSERT, UPDATE ON tide.tide_consumer_offsets TO pg_tide_relay;
GRANT SELECT, INSERT, UPDATE, DELETE ON tide.tide_consumer_leases TO pg_tide_relay;
GRANT SELECT, INSERT, UPDATE ON tide.relay_consumer_offsets TO pg_tide_relay;

Standalone Binary Deployment

The simplest deployment: download the relay binary and run it directly.

Download and install

# Linux (amd64)
curl -LO https://github.com/trickle-labs/pg-tide/releases/latest/download/pg-tide-x86_64-unknown-linux-gnu.tar.gz
tar xzf pg-tide-x86_64-unknown-linux-gnu.tar.gz
sudo mv pg-tide /usr/local/bin/

# macOS (Apple Silicon)
curl -LO https://github.com/trickle-labs/pg-tide/releases/latest/download/pg-tide-aarch64-apple-darwin.tar.gz
tar xzf pg-tide-aarch64-apple-darwin.tar.gz
sudo mv pg-tide /usr/local/bin/

Run the relay

pg-tide \
  --postgres-url "postgres://pg_tide_relay:pass@db.internal:5432/app" \
  --relay-group-id production \
  --log-format json \
  --metrics-addr 0.0.0.0:9090

Systemd service (Linux)

For production Linux deployments, run the relay as a systemd service:

# /etc/systemd/system/pg-tide-relay.service
[Unit]
Description=pg-tide relay
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
Type=simple
User=pgtide
Group=pgtide
ExecStart=/usr/local/bin/pg-tide \
  --config /etc/pg-tide/relay.toml
Restart=always
RestartSec=5
# Security hardening
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes

[Install]
WantedBy=multi-user.target
sudo systemctl enable pg-tide-relay
sudo systemctl start pg-tide-relay

Docker Deployment

The official Docker image is lightweight (~20 MB, Alpine-based) and runs as a non-root user.

Quick start

docker run -d \
  --name pg-tide-relay \
  -e PG_TIDE_POSTGRES_URL="postgres://user:pass@host.docker.internal:5432/mydb" \
  -e PG_TIDE_LOG_FORMAT="json" \
  -e PG_TIDE_GROUP_ID="production" \
  -p 9090:9090 \
  ghcr.io/trickle-labs/pg-tide:latest

Image details

PropertyValue
BaseAlpine 3.21
Size~20 MB
Userpgtide (UID 1000)
Entrypointpg-tide
Exposed Port9090 (metrics + health)

Environment variables

All relay configuration can be passed via environment variables:

VariableDescriptionRequired
PG_TIDE_POSTGRES_URLPostgreSQL connection stringYes
PG_TIDE_METRICS_ADDRMetrics endpoint (default: 0.0.0.0:9090)No
PG_TIDE_LOG_FORMATtext or jsonNo
PG_TIDE_LOG_LEVELerror, warn, info, debug, traceNo
PG_TIDE_GROUP_IDRelay group ID for HA coordinationNo

Docker Compose (complete development environment)

This sets up PostgreSQL with pg_tide, a NATS server, and the relay — everything you need for local development:

# docker-compose.yml
services:
  postgres:
    image: postgres:18
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: app
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5

  nats:
    image: nats:latest
    ports:
      - "4222:4222"
      - "8222:8222"

  pg-tide-relay:
    image: ghcr.io/trickle-labs/pg-tide:latest
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      PG_TIDE_POSTGRES_URL: "postgres://postgres:postgres@postgres:5432/app"
      PG_TIDE_LOG_FORMAT: "json"
      PG_TIDE_LOG_LEVEL: "info"
    ports:
      - "9090:9090"
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://localhost:9090/health"]
      interval: 10s
      timeout: 5s
      retries: 3

volumes:
  pgdata:

Building a custom image

If you need to bundle the extension with PostgreSQL:

FROM postgres:18

# Copy compiled extension files
COPY pg_tide.so      /usr/lib/postgresql/18/lib/
COPY pg_tide.control /usr/share/postgresql/18/extension/
COPY sql/pg_tide--0.1.0.sql /usr/share/postgresql/18/extension/

Kubernetes Deployment

For Kubernetes deployments, the relay runs as a standard Deployment with health checks, Prometheus metrics scraping, and optional horizontal scaling for HA.

Basic deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: pg-tide-relay
  labels:
    app: pg-tide-relay
spec:
  replicas: 2  # HA: advisory locks prevent duplicate processing
  selector:
    matchLabels:
      app: pg-tide-relay
  template:
    metadata:
      labels:
        app: pg-tide-relay
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "9090"
        prometheus.io/path: "/metrics"
    spec:
      containers:
        - name: relay
          image: ghcr.io/trickle-labs/pg-tide:0.1.0
          env:
            - name: PG_TIDE_POSTGRES_URL
              valueFrom:
                secretKeyRef:
                  name: pg-tide-secrets
                  key: postgres-url
            - name: PG_TIDE_LOG_FORMAT
              value: "json"
            - name: PG_TIDE_GROUP_ID
              value: "production"
          ports:
            - containerPort: 9090
              name: metrics
          livenessProbe:
            httpGet:
              path: /health
              port: 9090
            initialDelaySeconds: 5
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /health
              port: 9090
            initialDelaySeconds: 3
            periodSeconds: 5
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              cpu: 500m
              memory: 128Mi
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        readOnlyRootFilesystem: true
        allowPrivilegeEscalation: false

Secret

apiVersion: v1
kind: Secret
metadata:
  name: pg-tide-secrets
type: Opaque
stringData:
  postgres-url: "postgres://pg_tide_relay:secret@pg-cluster-rw:5432/app?sslmode=require"

Service (for metrics scraping)

apiVersion: v1
kind: Service
metadata:
  name: pg-tide-relay
  labels:
    app: pg-tide-relay
spec:
  selector:
    app: pg-tide-relay
  ports:
    - port: 9090
      targetPort: 9090
      name: metrics

CloudNativePG integration

If you use CloudNativePG, deploy the relay as a sidecar alongside your PostgreSQL pods. The relay connects to localhost:5432 via the CNPG-generated app secret:

spec:
  sidecars:
    - name: pg-tide-relay
      image: ghcr.io/trickle-labs/pg-tide:0.1.0
      env:
        - name: PG_TIDE_POSTGRES_URL
          valueFrom:
            secretKeyRef:
              name: my-cluster-app
              key: uri

See CloudNativePG Integration for the complete setup.

Helm chart

The project includes a Helm chart at examples/helm/pg-tide/:

helm install pg-tide-relay ./examples/helm/pg-tide \
  --set relay.postgresUrl="postgres://..." \
  --set relay.groupId="production" \
  --set relay.replicas=2

High Availability

Running multiple relay instances with the same relay_group_id provides automatic failover:

# Instance A — acquires locks for pipelines 1, 3, 5
pg-tide run --relay-group-id production --postgres-url ...

# Instance B — acquires locks for pipelines 2, 4, 6
pg-tide run --relay-group-id production --postgres-url ...

# If Instance A crashes, Instance B acquires pipelines 1, 3, 5 within seconds

How it works:

  1. Each relay instance attempts to acquire a PostgreSQL advisory lock for each pipeline
  2. Only one instance can hold each lock — the lock owner processes that pipeline
  3. If the owner crashes, its PostgreSQL session ends, locks are released
  4. Other instances detect the released locks and acquire them on their next discovery cycle (every 30s by default, or immediately via LISTEN/NOTIFY)

Important: More replicas means faster failover, not more parallelism per pipeline. Each pipeline is always processed by exactly one relay instance.


Resource Requirements

The relay is lightweight and predictable in its resource usage:

ResourceTypical usageNotes
CPU~50m per active pipelineScales with message volume and sink latency
Memory20-50 MB base + message bufferBuffer grows with batch_size × average message size
NetworkPostgreSQL connection + sink connections1 persistent PG connection + 1 LISTEN channel per instance
DiskNoneCompletely stateless — all state in PostgreSQL

For capacity planning: a relay instance handling 10 active pipelines at 1,000 messages/second total typically uses ~100m CPU and ~64 MB memory.


Pre-Deployment Checklist

Before going live, verify each item:

  • PostgreSQL 18 with pg_tide extension installed and verified
  • Relay binary or Docker image available and version-pinned
  • Pipeline configurations created in the database
  • Consumer groups created for each forward pipeline
  • Relay database user created with minimal privileges (see permissions above)
  • TLS enabled for PostgreSQL connection (sslmode=require)
  • Monitoring configured (Prometheus scrape target + alerting rules)
  • Health check configured in load balancer / orchestrator
  • At least 2 relay instances for HA (same relay_group_id)
  • Log aggregation configured (structured JSON logs recommended)
  • Backup strategy verified (standard PostgreSQL backups cover all pg_tide state)

Zero-Downtime Upgrades

Upgrading the relay binary requires no downtime:

  1. Deploy new relay instances alongside old ones (same relay_group_id)
  2. New instances start and wait for advisory locks
  3. Gracefully stop old instances (SIGTERM)
  4. Old instances drain in-flight messages, commit final offsets, release locks
  5. New instances acquire the released locks and resume processing
  6. Committed events use at-least-once transport: loss is not silent, and duplicates remain possible until the destination deduplicates the stable ID

For Kubernetes rolling updates, this happens automatically:

kubectl set image deployment/pg-tide-relay relay=ghcr.io/trickle-labs/pg-tide:0.2.0

For the extension itself:

-- Check current version
SELECT extversion FROM pg_extension WHERE extname = 'pg_tide';

-- Upgrade (runs migration SQL automatically)
ALTER EXTENSION pg_tide UPDATE TO '0.2.0';

Always upgrade the extension before upgrading the relay binary.

Capacity planning

pg_tide does not publish a universal messages-per-second number. Capacity is the result of payload size, PostgreSQL settings, batch size, pipeline count, sink acknowledgment behavior, and hardware. The v0.53 reference profiles and reviewed budgets live in benchmarks/operational/. The reference fingerprint is documented in benchmarks/reference-environment.md. The committed baseline is environment-specific evidence, not a universal guarantee.

Profiles and evidence

The required profiles are:

ProfilePayloadPipelinesMeasures
publish-single1 KiB JSON1matched transaction overhead and WAL
publish-concurrent1 KiB JSON1p50/p95/p99 publish overhead
relay-core1 KiB JSON1throughput, latency, CPU, RSS, offsets
relay-large16/64 KiB JSON1payload scaling and claim-check guidance
pipeline-density1 KiB JSON1/10/50idle and active worker cost
outage-recovery1 KiB JSON1backlog growth and drain slope
retention1 KiB JSON2 consumerssafe watermark, sweep, WAL, vacuum
ha-interruption1 KiB JSON1, 2 relaysowner-loss delivery interruption
small-message-high-rate1 KiB distribution1sustained event and byte rate
large-message-bounded-rate16/64 KiB distribution1byte rate, memory, WAL, storage
slow-destination1 KiB1 webhookbackpressure and bounded resources
intermittent-destination1 KiB1 webhookdeterministic retry and recovery
dlq-heavy1 KiB1DLQ depth, replay, and terminal identity
checkpoint-heavy1 KiB1batch-one checkpoint cost
sustained-backlog-recovery1 KiB1net catch-up headroom
mixed-four-destination1 KiB4PostgreSQL inbox, NATS, Kafka, webhook
graceful-shutdown-under-load1 KiB1shutdown and restart correctness

Every result records the commit, environment, PostgreSQL/NATS versions, payload, batch, poll interval, pipeline count, warmup, duration, and exact published/acknowledged/checkpointed identities. Never substitute the Criterion or direct-insert microbenchmarks for these profiles.

Sizing formulas

Let r be application messages/second, s the measured total bytes per retained message (heap plus indexes), and w the outage window in seconds:

outage disk reservation = r × w × s
steady retained storage = r × retention_seconds × s
network bytes/second = r × measured encoded payload bytes
recovery seconds = backlog / (acknowledged_rate - application_rate)

Use the measured values from the matching profile and destination boundary, not values from a different payload or sink. Reserve additional space for WAL, vacuum headroom, backups, and conversion's temporary copy. A sink outage accumulates committed rows; relay backoff protects the sink but does not reject application transactions.

Message sizes and claim-check

The reference matrix tests 1, 16, and 64 KiB JSON. Measure larger payloads before adopting them. Native large-object claim-check can reduce row and index growth for large payloads, but the large object is retained until the outbox row is safely cleaned; it is not an independent retention policy. Verify cleanup permissions and large-object storage in the same outage reservation.

PostgreSQL cost and vacuum

Inspect the measured relation and WAL deltas with:

SELECT pg_size_pretty(pg_relation_size('tide.tide_outbox_messages')),
       pg_size_pretty(pg_indexes_size('tide.tide_outbox_messages')),
       pg_size_pretty(pg_total_relation_size('tide.tide_outbox_messages'));

SELECT wal_bytes, stats_reset
FROM pg_stat_wal;

SELECT relname, n_live_tup, n_dead_tup, last_autovacuum,
       autovacuum_count, vacuum_count
FROM pg_stat_user_tables
WHERE schemaname = 'tide';

Use per-table autovacuum storage parameters for high-churn installations, derived from the retention profile rather than copied as universal settings:

ALTER TABLE tide.tide_outbox_messages SET (
  autovacuum_vacuum_scale_factor = 0.01,
  autovacuum_analyze_scale_factor = 0.01,
  autovacuum_vacuum_cost_limit = 2000
);

Bounded sweeps are preferred to one large delete: they cap lock duration and WAL per transaction and give autovacuum regular work. Check n_dead_tup / greatest(n_live_tup, 1), relation growth after vacuum, and pg_stat_statements query counts. If dead tuples or total bytes grow after delivery and cleanup have stabilized, vacuum is behind or the retention contract is blocked.

Partitioning

Heap storage is sufficient when measured retained rows, vacuum, and index growth fit the disk reservation and query-plan budgets. Choose ID-range partitioning when retained ID ranges make maintenance or vacuum too expensive, not because a generic throughput threshold says so. The shared parent remains tide.tide_outbox_messages; children are numeric RANGE (id) partitions. Choose the span from measured retained IDs and maintenance duration, keeping the child count bounded by retained ranges plus the premade and default children. The default span is 10,000,000 IDs and premake count is two.

Verify the canonical query and pruning with:

EXPLAIN (FORMAT JSON)
SELECT id, outbox_name, payload
FROM tide.tide_outbox_messages
WHERE outbox_name = 'orders' AND id > 1000
ORDER BY id
LIMIT 100;

Conversion is a blocking maintenance-window copy. Run its dry-run preflight, reserve temporary disk, drain relays, and keep a rollback plan. The old per-outbox/time-partition procedure is not supported.

Pipeline density and HA

Ten or fifty pipelines are separate measured profiles, not a linear capacity promise. Compare idle worker RSS, catalog discovery queries, active throughput, and offset writes against the budget. Run at least two relays for HA and size the interruption budget from the measured owner-loss-to-resumed-delivery interval.

Conservative worked examples

Use the accepted v1 result for the named profile and keep the smallest rounded capacity choice after the stated headroom:

  1. NATS outage: relay-core retained bytes/event × application rate × outage seconds, plus 30% WAL and vacuum headroom.
  2. Kafka: large-message-bounded-rate encoded destination bytes/second × required rate, plus 30% broker and relay headroom. Encoded bytes are not JSON payload bytes.
  3. PostgreSQL inbox: mixed-four-destination destination row/index bytes/event × retained events, plus cleanup and dead-tuple headroom.
  4. Webhook: slow-destination acknowledged rate must exceed application rate; reserve disk for measured backlog during the slow window.
  5. Four destinations: size each destination independently and use the slowest sustained rate, then add relay, network, retention, and destination costs.
  6. Fifty pipelines: use the pipeline-density 50-pipeline instance for idle memory, tasks, connections, discovery, and metric-series headroom.
  7. DLQ: use dlq-heavy terminal-failure row size × bounded replay set, and reserve storage until replay and cleanup complete.

Alerts

Alert on:

  • exact lag from tide.relay_pipeline_lag;
  • blocked participants and safe offset from tide.outbox_retention_status;
  • default-partition rows and storage-layout mismatch;
  • WAL rate, dead-tuple ratio, and relation growth;
  • disk remaining after the configured outage reservation.

Do not use a fixed lag or throughput threshold copied from another environment.

Maintenance

pg_tide state is in PostgreSQL. Back up the complete database together with the application tables whose transactions publish outbox rows.

Backup and upgrade

pg_dump --format=custom --file=pg_tide_backup.dump "$DATABASE_URL"
pg_restore --clean --if-exists --dbname="$DATABASE_URL" pg_tide_backup.dump

Before an extension upgrade, take a backup and stop old relay binaries. Apply the versioned migration, deploy the matching relay, then verify offsets and delivery. Relay rollback to v0.50.0 is supported while the v0.51.0 extension remains installed; extension rollback uses PITR or the pre-upgrade backup.

Bounded outbox cleanup

Use the bounded API rather than an unbounded delete:

SELECT tide.outbox_sweep(
  p_outbox_name := NULL,
  p_batch_size := 1000,
  p_dry_run := TRUE
);

p_batch_size accepts 1–10,000. One call handles at most one batch per selected outbox, locks candidates with FOR UPDATE SKIP LOCKED, and returns participants, blockers, retention cutoff, safe offset, affected rows, has_more, highest deleted ID, duration, and partition action. Dry-run examines at most batch_size + 1 candidates; it does not count the entire table.

The safe offset is the minimum checkpoint across every configured native pipeline, relay group, consumer group, and overlapping lease. A disabled pipeline still blocks cleanup. Both retention age and safe offset are required. consumed_at and delivery receipts are not cleanup authority.

Automation should call outbox_sweep(). The deprecated outbox_truncate_delivered() wrapper performs one 1,000-row sweep:

SELECT tide.outbox_truncate_delivered();

For pg_cron, keep each transaction bounded:

SELECT cron.schedule(
  'pg-tide-outbox-sweep',
  '*/5 * * * *',
  $$SELECT tide.outbox_sweep(NULL, 1000, false)$$
);

For Kubernetes, invoke pg-tide sweep --batch-size 1000 --max-batches 10 from a CronJob. Use --dry-run first. The command reports blockers and progress per outbox and exits non-zero if any outbox fails; a database error is never reported as zero rows.

Rewind and retirement

Delete a pipeline or consumer group only when its replay history is no longer needed. Disabling pauses delivery and intentionally preserves retention protection. Rewind requires the normal authorization, confirmation, ownership drain, and audit checks, and additionally refuses a target below the highest deleted message ID. The exact retained boundary is allowed.

SELECT outbox_name, safe_offset, highest_deleted_id, blockers
FROM tide.outbox_retention_status
ORDER BY outbox_name;

Vacuum, WAL, and storage

Bounded deletes limit lock time and WAL bursts and give autovacuum regular work. Inspect dead tuples, vacuum timestamps, relation sizes, and WAL deltas:

SELECT relname, n_live_tup, n_dead_tup, last_autovacuum,
       autovacuum_count
FROM pg_stat_user_tables
WHERE schemaname = 'tide';

SELECT wal_bytes, stats_reset FROM pg_stat_wal;

Set per-table autovacuum parameters from the measured retention profile:

ALTER TABLE tide.tide_outbox_messages SET (
  autovacuum_vacuum_scale_factor = 0.01,
  autovacuum_analyze_scale_factor = 0.01
);

Reserve disk for retained rows, WAL, vacuum headroom, and the configured sink outage. A sink outage accumulates committed rows. Relay backoff/rate limiting protects the sink but does not reject application transactions, and inline_threshold is not a native pending-row cap.

Partition maintenance

Inspect tide.outbox_storage_config and tide.outbox_retention_status before maintenance. The canonical parent remains tide.tide_outbox_messages; optional children are ID-range partitions. Run tide.outbox_maintain_partitions(2, false) after checking its dry-run output. Whole-child removal is allowed only when every logical outbox row in the child passes its own age, participant offset, and active-lease predicates. Otherwise bounded row cleanup continues.

Heap-to-ID-range conversion is a blocking maintenance-window operation and requires explicit confirmation. It is not live conversion and must not be run while relays or publishers are active.

Health queries

Use the v0.43 status surfaces:

SELECT * FROM tide.outbox_retention_status;
SELECT * FROM tide.relay_pipeline_lag;
SELECT * FROM tide.outbox_cleanup_state;

Alert on stale cleanup, blockers, default-partition rows, storage-layout mismatch, growing exact lag, dead-tuple ratio, WAL rate, and disk remaining after the outage reservation.

Monitoring Cookbook

Practical recipes for monitoring pg_tide in production. Each recipe addresses a specific operational concern with ready-to-use PromQL queries, alert rules, and dashboard configurations.

Recipe: Basic Health Monitoring

Goal: Know immediately when something is wrong.

Alerts

groups:
  - name: pg-tide-health
    rules:
      - alert: PgTidePipelineUnhealthy
        expr: pg_tide_relay_pipeline_healthy == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Pipeline {{ $labels.pipeline }} is unhealthy (circuit breaker open)"

      - alert: PgTideNoActivity
        expr: rate(pg_tide_relay_messages_published_total[10m]) == 0
        for: 15m
        labels:
          severity: warning
        annotations:
          summary: "Pipeline {{ $labels.pipeline }} has published zero messages for 15 minutes"

Dashboard Panel

# Traffic light: 1 = green, 0 = red
pg_tide_relay_pipeline_healthy

Recipe: Throughput Monitoring

Goal: Understand message flow rates and detect anomalies.

Key Queries

# Messages published per second (per pipeline)
rate(pg_tide_relay_messages_published_total[5m])

# Total throughput across all pipelines
sum(rate(pg_tide_relay_messages_published_total[5m]))

# Publish success ratio
1 - (rate(pg_tide_relay_publish_errors_total[5m]) / rate(pg_tide_relay_messages_consumed_total[5m]))

Alert: Throughput Drop

- alert: PgTideThroughputDrop
  expr: |
    rate(pg_tide_relay_messages_published_total[5m])
    < 0.5 * rate(pg_tide_relay_messages_published_total[1h] offset 1d)
  for: 10m
  labels:
    severity: warning
  annotations:
    summary: "Pipeline {{ $labels.pipeline }} throughput dropped >50% vs yesterday"

Recipe: Latency Monitoring

Goal: Ensure messages are delivered within acceptable time bounds.

Key Queries

# P50 delivery latency
histogram_quantile(0.5, rate(pg_tide_relay_delivery_latency_seconds_bucket[5m]))

# P99 delivery latency
histogram_quantile(0.99, rate(pg_tide_relay_delivery_latency_seconds_bucket[5m]))

# Percentage of messages delivered within 1 second
sum(rate(pg_tide_relay_delivery_latency_seconds_bucket{le="1.0"}[5m]))
/ sum(rate(pg_tide_delivery_latency_seconds_count[5m]))

Alert: High Latency

- alert: PgTideHighLatency
  expr: histogram_quantile(0.99, rate(pg_tide_relay_delivery_latency_seconds_bucket[5m])) > 5
  for: 5m
  labels:
    severity: warning
  annotations:
    summary: "Pipeline {{ $labels.pipeline }} P99 latency exceeds 5 seconds"

Recipe: Pipeline Lag and Retention Monitoring

Goal: Detect growing backlogs before they become critical.

Key Queries

# Exact lag is exported from tide.relay_pipeline_lag through PostgreSQL exporter.
# Use labels for relay group, pipeline, and outbox.
pg_tide_relay_consumer_lag

# Lag growth rate (positive = growing, negative = draining)
deriv(pg_tide_relay_consumer_lag[5m])

# Estimated time to drain at current rate
pg_tide_relay_consumer_lag / rate(pg_tide_relay_messages_published_total[5m])

Alert: Growing Lag

- alert: PgTideGrowingLag
  expr: deriv(pg_tide_relay_consumer_lag[10m]) > 0
  for: 10m
  labels:
    severity: warning
  annotations:
    summary: "Pipeline {{ $labels.pipeline }} lag is growing"

- alert: PgTideCleanupBlocked
  expr: pg_tide_relay_consumer_lag > 0
  for: 5m
  labels:
    severity: critical
  annotations:
    summary: "Outbox {{ $labels.outbox }} retention is blocked"

Use tide.outbox_retention_status for the blocker name, participant offset, retention cutoff, retained bytes, and default-partition rows. Choose alert thresholds from the outage reservation and measured reference profile, not a fixed message count.

Recipe: Error Rate Monitoring

Goal: Detect delivery problems early.

Key Queries

# Errors per second
rate(pg_tide_relay_publish_errors_total[5m])

# Error ratio (errors / total consumed)
rate(pg_tide_relay_publish_errors_total[5m]) / rate(pg_tide_relay_messages_consumed_total[5m])

Alert: Error Spike

- alert: PgTideErrorSpike
  expr: rate(pg_tide_relay_publish_errors_total[5m]) > 1
  for: 5m
  labels:
    severity: warning
  annotations:
    summary: "Pipeline {{ $labels.pipeline }} has sustained errors: {{ $value }}/s"

Recipe: Dead Letter Queue Monitoring

Goal: Track messages that failed permanently and need attention.

SQL Query (for custom exporter or pg_stat_monitor)

-- Unresolved DLQ entries by pipeline
SELECT pipeline_name, count(*) as unresolved
FROM tide.relay_dlq
WHERE resolved_at IS NULL
GROUP BY pipeline_name;

Alert (via SQL-based exporter)

- alert: PgTideDLQGrowing
  expr: pg_tide_relay_dlq_depth > 0
  for: 30m
  labels:
    severity: warning
  annotations:
    summary: "Pipeline {{ $labels.pipeline }} has {{ $value }} unresolved DLQ entries"

Recipe: Resource Monitoring

Goal: Ensure relay processes have adequate resources.

Key Queries (standard node/container metrics)

# CPU usage per relay pod
rate(container_cpu_usage_seconds_total{container="pg-tide"}[5m])

# Memory usage per relay pod
container_memory_working_set_bytes{container="pg-tide"}

# PostgreSQL active connections from relay
pg_stat_activity_count{application_name="pg-tide"}

Runbook Reference

AlertFirst ResponseEscalation
PipelineUnhealthyCheck sink availability, review error logsRestart relay if stuck
ThroughputDropCheck source (outbox empty?), check sink (slow?)Scale relay instances
HighLatencyCheck batch size, check sink response timeIncrease batch size or add instances
GrowingLagCheck relay health, check for slow transformsIncrease batch size, add instances
ErrorSpikeCheck DLQ for error details, check sink logsFix root cause, replay DLQ
DLQGrowingInspect DLQ entries, identify error patternFix issue, replay messages

Further Reading


Inbox Fleet Status Performance Contract (v0.33.0)

tide.inbox_status(NULL) (fleet mode) returns a summary row for every configured inbox. Internally it executes a dynamic UNION ALL query across all inbox message tables — one round-trip per call, but the query grows with the number of inboxes (O(n) SQL length, not O(n) round-trips since v0.32.0).

Guidelines:

Use caseRecommendation
Grafana dashboard panel✅ OK — set panel refresh to ≥ 60 s
Monitoring script (cron / runbook)✅ OK — run on demand
pg-tide status --inbox-summary CLI✅ OK — run ad-hoc
Per-message application loop❌ Use tide.inbox_status('inbox_name') per-inbox instead
High-frequency polling (< 5 s)❌ Use Prometheus metrics or per-inbox queries

The per-inbox variant tide.inbox_status('my_inbox') is always O(1) and safe to call at any frequency.

CLI usage:

# Include inbox fleet summary in pg-tide status output:
pg-tide status --postgres-url "$PG_URL" --inbox-summary

Runbook: Backup and Restore

This runbook covers the v0.51.0 recovery boundary. PostgreSQL state can be restored; an external destination is not rolled back with it.

Logical backup

Take globals and a complete custom-format database dump before an extension update:

pg_dumpall --globals-only --no-role-passwords > globals.sql
pg_dump --format=custom --file=pg-tide.dump "$PG_TIDE_POSTGRES_URL"

Restore roles first, then restore the database into a clean PostgreSQL 18 cluster with the same pg_tide extension artifact installed. Verify the extension version, owners, grants, sequences, inbox tables, checkpoints, and DLQ rows before starting the relay.

psql --file=globals.sql postgres
createdb restored
pg_restore --exit-on-error --dbname=restored pg-tide.dump

Start the relay only after pg-tide doctor reports a compatible extension. New events must continue from the restored source frontier; a checkpoint committed after the restore point must not be recreated manually.

Physical backup and PITR

Use PostgreSQL base backups and archived WAL for physical recovery. Restore the cluster to the required recovery point, verify pg_extension.extversion, and let new relay processes reacquire ownership. Leases, advisory locks, and heartbeats are transient and must not be treated as restored authority.

Restoring before a checkpoint commit may redeliver an event. This is allowed at-least-once behavior. The event identity remains stable and the destination must apply its documented deduplication rule. pg_tide does not claim to roll back NATS, Kafka, or webhook effects.

Choosing the recovery action

  • Use relay rollback only to run v0.50.0 against a v0.51.0 extension.
  • Use an exact reverse extension migration only where the lifecycle policy marks the step reversible.
  • Use database restore or PITR for the irreversible v0.50.0 → v0.51.0 boundary.

Never repair pg_extension or tide tables by hand.

Operations runbooks

Use the canonical commands first. They are read-only unless explicitly stated:

pg-tide doctor --output json
pg-tide status --output json
pg-tide config validate --output json
Symptom / alertRunbook sectionFirst commandEvidence
Relay will not startRelay will not startpg-tide doctor --output jsondoctor envelope and pod logs
Pipeline not discoveredPipeline is not discoveredpg-tide status --output jsonstatus ownership/config result
Lag alertPipeline has lagpg-tide status --output jsonlag, retry, latency trends
Publish errorsSink authentication failurepg-tide doctor --output jsonredacted connector check
Bounded connector failuresSink authentication failure and the connector runbookspg-tide status --output jsoncode, retry class, and connector metric
DLQ alertDLQ is growingpg-tide status --output jsonunresolved depth and write rate
Ownership unclearAdvisory lock is stuckpg-tide doctor --output jsonPostgreSQL session evidence
PostgreSQL failoverPostgreSQL failover occurredpg-tide status --output jsonprimary, owner, checkpoint
Retention blockedRetention is not cleaning uppg-tide maintenance sweep --dry-runsweep report
Disk growthDisk usage is growingpg-tide status --output jsonmeasured storage breakdown
Upgrade failureUpgrade failedpg-tide doctor --output jsonmigration/job and version matrix
DuplicatesDuplicate messagespg-tide status --output jsonstable event IDs and ownership

Relay will not start

Run doctor --output json; do not bypass validation. Check parse/unknown-key errors, missing URL or secret, TLS/authentication, extension compatibility, role grants, enabled pipeline validation, and port binding. Fix the reported component and rerun doctor. Keep relay stopped on validation failure. If migration state is uncertain, preserve logs and backup evidence and escalate before rollback.

Pipeline is not discovered

Check group, tenant, direction, enabled state, catalog visibility/grants, structural config, compiled connector feature, reconcile delay, and current owner with status and doctor. Do not insert or update catalog rows directly. Correct configuration through the supported SQL API, then wait for reconciliation and verify ownership.

Pipeline has lag

Compare arrival, publish, consumer lag, delivery latency, retry state, pool waiting, ownership, and cleanup/storage trends. A single threshold cannot identify the cause. Reduce source pressure or correct the sink; scale only after confirming ownership distribution and configured batch/concurrency bounds. Capture before/after status evidence.

Sink authentication failure

Verify secret-reference existence, file ownership/mode, certificate hostname and expiry, destination authorization, and connector configuration. Use the redacted doctor probe; never print secrets or disable TLS verification. Rotate credentials, then verify publish recovery and error-rate resolution.

DLQ is growing

Separate unresolved depth from write rate and classify errors using payload-safe inspection. Confirm DLQ persistence is healthy, check idempotency and duplicate effects, and use the supported replay preview/execute flow. Verify replay does not mutate the live checkpoint unexpectedly.

Advisory lock is stuck or ownership is unclear

Treat owner, stale, and unknown as different states. Inspect PostgreSQL sessions and heartbeat evidence; drain safely and terminate only the identified stale session through the documented operational procedure. Failover releases session locks. Do not delete status rows or unlock arbitrary sessions.

PostgreSQL failover occurred

Confirm the new primary, connectivity/TLS, extension availability, and relay readiness. Verify old ownership sessions are gone, then observe advisory-lock reacquisition, checkpoints, lag drain, and expected at-least-once duplicates. Escalate immediately if two owners appear.

Retention is not cleaning up

Run the public sweep dry-run and inspect participant blockers, disabled pipelines, checkpoints, active leases, cleanup freshness, partition blockers, and rewind implications. Apply bounded cleanup through public maintenance APIs; never delete rows manually.

Disk usage is growing

Break usage into retained messages, DLQ, indexes/dead tuples, WAL, partitions, logs, and container filesystem. Use capacity guidance and measured evidence before changing retention. Apply bounded cleanup and escalate if WAL or filesystem growth is unrelated to message retention.

Upgrade failed

Classify failure: before migration, during migration, after extension/before relay, mixed relay rollout, relay replacement, CNPG job, or rollback. Preserve backup and job logs. Continue publishing only when the compatibility matrix says it is safe; otherwise pause relay, use the documented reverse migration only when eligible, or restore/PITR. Never assume bootstrap hooks migrated an existing cluster.

Duplicate messages are observed

Use stable event identity to distinguish expected publish-ack/checkpoint ambiguity, ownership transfer, replay/rewind, and destination duplication. Confirm only one owner at a time. At-least-once delivery means duplicates can be expected; do not claim recovery can eliminate all duplicates.

Runbook: Relay Upgrade

Applies to: pg-tide relay binary (pg-tide run)
Scope: Rolling upgrade procedure for high-availability deployments with multiple relay instances.


Overview

The pg-tide relay keeps durable source offsets in PostgreSQL. Pipeline ownership is coordinated via worker-held PostgreSQL advisory-lock sessions. The v0.51.0 rolling runtime window is explicitly bounded: v0.50.0 and v0.51.0 relays may mix, while v0.49.0 and earlier relays must stop before the extension crosses the supported floor-to-target migration chain.


Pre-Upgrade Checklist

  1. Read the CHANGELOG for the target version — note any new required configuration keys or deprecated flags.
  2. Back up the database (or confirm PITR is current).
  3. Confirm current relay health:
    pg-tide status --postgres-url "$PG_TIDE_POSTGRES_URL"
    pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL"
    
  4. Stop all pre-v0.50.0 relays before upgrading the extension. Back up the database, then run:
    ALTER EXTENSION pg_tide UPDATE;
    
    Do not start an older relay after the migration. Start only a relay covered by the v0.50.0/v0.51.0 compatibility window after verification.

v0.51.0 relay and extension window

Upgrade v0.50.0 relays to v0.51.0 first, then update the extension through PostgreSQL's packaged adjacent migration:

ALTER EXTENSION pg_tide UPDATE TO '0.51.0';

The v0.51.0 relay checks pg_extension.extversion before it creates a coordinator or polls. It rejects versions outside its declared window with PGTIDE_EXTENSION_VERSION_INCOMPATIBLE. There is no bypass flag.

If the relay must be rolled back, run the released v0.50.0 relay while leaving the v0.51.0 extension installed. Do not downgrade the extension for this procedure; use the backup/PITR runbook for the irreversible extension boundary.


v0.47.0 Stop-Upgrade-Start Procedure

  1. Disable or stop every v0.44.0 relay and verify its ownership sessions are gone.
  2. Back up PostgreSQL and apply the extension migration.
  3. Deploy v0.47.0 relays.
  4. Verify scoped offsets, ownership, health, and duplicate handling.

An in-flight batch whose sink succeeded before shutdown may be redelivered with the same stable identity. This is expected at-least-once transport behavior.

Rolling Upgrade Procedure (Kubernetes)

1. Update the Deployment Image Tag

kubectl set image deployment/pg-tide \
   pg-tide=ghcr.io/trickle-labs/pg-tide:0.47.0

Or update image.tag in values.yaml and run helm upgrade:

helm upgrade pg-tide oci://ghcr.io/trickle-labs/helm/pg-tide \
   --set image.tag=0.47.0 \
  --reuse-values

2. Watch the Rollout

kubectl rollout status deployment/pg-tide

Kubernetes replaces pods one at a time (controlled by maxUnavailable and maxSurge). As each old pod is terminated:

  1. PostgreSQL advisory locks held by the old pod are released automatically when the connection closes (within ~1 s of pod termination).
  2. The new pod's coordinator reconciles and reacquires the released pipelines.
  3. Messages may be re-delivered (at-least-once) for any batch that was in-flight at the time of the old pod's termination.

3. Verify Post-Upgrade

# All pods should be running the new version:
kubectl get pods -l app.kubernetes.io/name=pg-tide -o json \
  | jq '.items[].spec.containers[].image'

# Pipeline ownership should be fully restored:
pg-tide status --postgres-url "$PG_TIDE_POSTGRES_URL"

Rolling Upgrade Procedure (Docker / Systemd)

For single-instance or manual deployments:

  1. For versions before v0.47.0, do not start the new relay alongside the old one. Stop all old instances first, then deploy the new image.

    docker run -d --name pg-tide-new \
      -e PG_TIDE_POSTGRES_URL="$PG_TIDE_POSTGRES_URL" \
    ghcr.io/trickle-labs/pg-tide:0.47.0
    
  2. Verify the new relay is healthy and has acquired pipelines:

    docker logs pg-tide-new | grep "acquired lock"
    pg-tide status --postgres-url "$PG_TIDE_POSTGRES_URL"
    
  3. Stop the old relay (graceful drain):

    docker stop --time 60 pg-tide-old
    

    The --time 60 gives the old relay up to 60 seconds to finish in-flight batches before hard-stopping.

  4. Clean up:

    docker rm pg-tide-old
    docker rename pg-tide-new pg-tide
    

Configuration Changes Between Versions

New Required Configuration Keys

Check the CHANGELOG for any new required keys. The relay will fail to start with a clear error message if a required key is missing.

Deprecated Flags

Deprecated flags continue to work until the next major version. A WARN-level log entry is emitted at startup if a deprecated flag is present.

Environment Variable Changes

Old (pre-0.17.0)NewNotes
PG_TIDE_RELAY_POSTGRES_URLPG_TIDE_POSTGRES_URLOld name no longer recognised
Pre-v0.17 legacy env varPG_TIDE_POSTGRES_URLSee CHANGELOG v0.17.0 for details

Rollback

If the new relay is unhealthy after the upgrade:

  1. Start the old relay binary (advisory locks auto-transfer back).
  2. Stop the new relay.
  3. Investigate logs from the new relay for the root cause.

Rollback across the v0.45.0 lock/offset contract is not automatic. Keep the database backup and follow the release-specific rollback procedure; do not run mixed relay versions against the migrated catalog.


HA Considerations

  • Minimum two relay instances are recommended for production to ensure zero-downtime upgrades.
  • maxUnavailable: 0 in the Kubernetes PodDisruptionBudget ensures at least one relay is always running during node drains.
  • The Helm chart defaults (helm/pg-tide/values.yaml) set replicaCount: 1 by default; use at least two replicas for HA and enable a PodDisruptionBudget.

See Also

Stability guarantees

The v0.47.0 policy is a public-beta contract freeze, not a v1.0.0 GA promise. It freezes documented, production-supported behavior and keeps preview, experimental, diagnostic, and internal surfaces outside the v1 guarantee.

Frozen public surfaces

The release candidate freezes documented PostgreSQL 18 SQL APIs, the supported pipeline configuration subset, core Prometheus metrics and health endpoints, versioned CLI machine-readable output, native pg_tide and CloudEvents envelopes, and the direction-aware support matrix.

Each surface has normative documentation and executable or machine-checkable evidence. Ownership, maturity, versions, profiles, and evidence come from connectors.toml, not compilation alone.

Compatibility rules

Removing or renaming a documented field, endpoint, function, metric family, envelope field, supported connector, or supported version is breaking. So are changes to types, requiredness, defaults, status semantics, acknowledgement boundaries, deduplication identity, or documented meaning.

Additive optional fields, bounded metric families, separate endpoints, and new compatible service versions require compatibility review and documented defaults. Security and correctness fixes may change behavior when they preserve the documented safety invariant and include migration guidance. Internal Rust layout, log wording, migration statement order, and undocumented configuration remain outside the guarantee.

Explicit exclusions

There is no v1 guarantee for PostgreSQL versions other than 18, inbound connectors, preview-only integrations, or internal tooling, a stable Rust/plugin ABI, arbitrary source-to-sink combinations, or exactly-once transport. See the support policy and production-supported definition.

Security

Security considerations for pg_tide deployments.


Extension Security

Schema Isolation

All pg_tide objects live in the tide schema. The extension is marked trusted = true and superuser = false — it can be installed by any user with CREATE privilege on the database.

No Elevated Privileges

The extension uses no:

  • Background workers
  • Shared memory
  • File system access
  • Network connections
  • unrestricted SECURITY DEFINER functions

Administrative and maintenance functions use a fixed search_path = pg_catalog, tide, qualify protected objects, authorize session_user, and revoke PUBLIC execution. The v0.44 migration grants only the canonical group roles.

Catalog Table Access

Install the canonical roles with deploy/postgres/pg_tide_roles.sql. Do not grant direct catalog access to application logins:

GRANT tide_publisher TO app_login;
SELECT tide.outbox_grant_publish('orders', 'app_login');

Relay Security

Connection String Protection

Never embed passwords in config files committed to version control. Use environment variables:

postgres_url = "postgres://${env:PG_USER}:${env:PG_PASSWORD}@${env:PG_HOST}:5432/mydb"

File references use ${file:/absolute/path} and are checked for ownership, permissions, type, and size. Resolved values are never serialized or logged. Secret references are resolved only at the final connector boundary; malformed, unknown, missing, or unsafe references fail closed.

Least-Privilege Database User

The relay login receives membership in the non-login tide_relay group. The provisioning script never creates login roles or passwords.

Network Security

  • The relay's metrics endpoint (default :9090) should not be exposed publicly
  • Use TLS for PostgreSQL connections in production (sslmode=require)
  • Use TLS for sink connections (NATS TLS, Kafka SSL, HTTPS webhooks)
  • HTTP clients use HTTPS, disable automatic redirects, and ignore ambient HTTP_PROXY/HTTPS_PROXY settings. Development exceptions must be explicit connector configuration.
  • URL validation rejects loopback, private, link-local, metadata, mapped, documentation, multicast, and other special-use addresses.

Encryption Provider Scope

LocalKeyFile is the only supported v0.44.0 encryption provider. AWS KMS, GCP KMS, and Vault Transit names remain unavailable/experimental and are not included in the production connector profile.

Docker Security

The official Docker image runs as non-root user pgtide (UID 1000):

USER pgtide

No capabilities are required. Use securityContext in Kubernetes:

securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false

Payload Security

Sensitive Data

Avoid publishing sensitive data (PII, credentials) in outbox payloads. If you must, encrypt at the application layer before calling outbox_publish().

Input Validation

pg_tide accepts any valid JSONB as payload. Validate payloads at the application level before publishing. The extension does not perform content validation.


Reporting Vulnerabilities

Report security issues to: security@trickle-labs.com

Do not open public GitHub issues for security vulnerabilities.

Security Guide

This guide covers security best practices for deploying pg_tide in production, including secret management, network security, authentication, and access control.

Secret Management

Environment Variable Substitution

pg_tide supports the strict ${env:VARIABLE_NAME} syntax in pipeline configurations. ${ENV:VARIABLE_NAME} is accepted for one compatibility release with a deprecation warning. Malformed, nested, unknown, or unresolved references fail validation.

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'my-pipeline',
    'outbox', 'events',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "${env:KAFKA_BROKERS}",
        "sasl_username": "${env:KAFKA_USER}",
        "sasl_password": "${env:KAFKA_PASS}"
    }'::jsonb
  )
);

The catalog stores the ${env:...} tokens, not the resolved values. The relay resolves them at startup.

File-Based Secrets

For secrets stored on disk (Kubernetes mounted secrets, vault agent files):

{
  "password": "${file:/run/secrets/db-password}"
}

The path must be absolute. The relay opens it without following symlinks and requires a regular file owned by the relay user with no group/world permission bits and a bounded size. Unsafe files fail closed.

Best Practices

  • Never hardcode secrets in pipeline configurations
  • Use ${env:NAME} or ${file:/absolute/path} references
  • Rotate secrets regularly — update the environment/file and the relay picks up new values on restart
  • Use separate credentials per pipeline when possible (principle of least privilege)
  • Resolved values are never written to catalog JSON, history, status, metrics, templates, logs, or error output

Database Access Control

Principle of Least Privilege

Provision the canonical non-login group roles after installing or upgrading the extension:

psql -f deploy/postgres/pg_tide_roles.sql "$DATABASE_URL"

The script creates only NOLOGIN group roles: tide_admin, tide_publisher, tide_relay, tide_operator, and tide_reader. Grant those groups to existing login roles according to the least-privilege matrix. Existing pg_tide_admin is retained as a deprecated compatibility alias and inherits tide_admin; it is not created on fresh installations.

tide_publisher membership is not enough to publish. The caller also needs an explicit row in the outbox publisher ACL. Reader and operator surfaces expose sanitized status only; raw configuration, history, payloads, and secret-bearing catalogs remain unavailable.

Connection Security

Always use TLS for PostgreSQL connections:

pg-tide --postgres-url "postgres://relay:pass@db:5432/mydb?sslmode=require"

For strict certificate verification:

pg-tide --postgres-url "postgres://relay:pass@db:5432/mydb?sslmode=verify-full&sslrootcert=/certs/ca.pem"

Network Security

Relay Process

The relay exposes two network endpoints:

  • Metrics endpoint (default :9090) — Prometheus metrics and health check
  • Webhook receiver (if configured) — Incoming webhooks

Secure them:

  • Bind metrics to internal network only: --metrics-addr "10.0.0.0:9090"
  • Use network policies (Kubernetes) to restrict access
  • Never expose metrics to the public internet

Sink Connections

  • Use TLS for all sink connections (Kafka, NATS, HTTP, cloud services)
  • Use SASL/mTLS for Kafka when available
  • Verify certificates — don't disable TLS verification in production
  • Use private endpoints for cloud services (AWS PrivateLink, GCP Private Service Connect)

Kubernetes Network Policies

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: pg-tide-relay
spec:
  podSelector:
    matchLabels:
      app: pg-tide-relay
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: prometheus
      ports:
        - port: 9090
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: postgres
      ports:
        - port: 5432
    - to:  # Allow outbound to sinks
        - namespaceSelector: {}

Webhook Security

Outgoing Webhooks

Sign outgoing webhooks so recipients can verify authenticity:

{
  "sink_type": "webhook",
  "url": "https://partner.example.com/events",
  "signature": {
    "scheme": "hmac-sha256",
    "secret": "${env:WEBHOOK_SECRET}",
    "header": "X-Signature-256"
  }
}

Incoming Webhooks

Always verify incoming webhook signatures:

{
  "source_type": "webhook",
  "signature_scheme": "stripe",
  "signature_secret": "${env:STRIPE_WEBHOOK_SECRET}"
}

Reject unsigned requests. See Webhook Signatures.

Audit Trail

pg_tide maintains a natural audit trail:

  • Every published event has a sequential ID, timestamp, and stream table
  • The DLQ records all delivery failures with error details
  • Relay logs show all pipeline activity

For compliance, ensure:

  • Relay logs are shipped to a centralized logging system
  • DLQ entries are reviewed within your SLA
  • Outbox tables have appropriate retention policies

Common Vulnerabilities to Avoid

RiskMitigation
Secrets in catalogUse ${env:...} substitution
Unencrypted connectionsEnforce sslmode=require or verify-full
Open metrics endpointBind to internal network, use network policies
Excessive permissionsUse dedicated roles with minimal grants
Unsigned webhooksAlways configure signature verification
Stale credentialsImplement secret rotation procedures

Further Reading

pg_tide threat model

This model covers the v0.52.0 production profiles: core and core-kafka. It covers the PostgreSQL 18 extension, PostgreSQL inbox, NATS JetStream, Apache Kafka, and HTTPS webhook destinations. stdout and file are diagnostic sinks only.

IDAsset and trust boundaryAttacker capabilityPreventionDetectionRecoveryResidual limitOwner and contactEvidenceCode or runbook
T01Publisher identity at application to extensionBorrow an application login or role membershipsession_user, canonical roles, outbox ACLBounded authorization errorRevoke role and ACLA superuser can bypass database ACLsDatabase owner; @groveprivilege-model-prpg-tide-ext/src/outbox.rs
T02Pipeline catalog at operator to relayModify JSON config or enable an unauthorized pipelineExact role grants and bounded admin APIAudit/config failureRestore reviewed config and disable pipelineDatabase owner compromise is outside scopeRelay owner; @groveprivilege-model-prdocs/src/sql-reference/relay-api.md
T03Relay credentials at secret reference to runtimeRead a reference, file, process, or error pathReference-only fields, strict files, SecretStringCanary scan and secret-file failuresRotate credential and quarantine evidenceHost root can read process memoryRelay owner; @grovesecret-canary-prpg-tide-relay/src/secret.rs
T04Event payload at source to relaySubmit oversized, malformed, or malicious JSONSchema, size bounds, typed envelopes, redactionValidation and bounded decode errorsPreserve source event and replay after correctionPayload semantics remain application-ownedRelay owner; @groverelay-unit-pr, relay-integration-prpg-tide-relay/src/envelope.rs
T05Webhook request at relay to destinationTarget private, metadata, or loopback addressURL, DNS, address, redirect, and proxy policySSRF refusal and zero-request assertionRemove endpoint; retain checkpointA trusted DNS or firewall compromise is outside scopeRelay owner; @grovenetwork-security-core-prpg-tide-relay/src/http_util.rs, webhook runbook
T06DNS and redirect answers at relay to destinationReturn mixed, rebinding, or private answersValidate every answer, pin answers, disable redirectsPolicy refusal and request receipt checkRemove endpoint and inspect DNS controlDNS authority compromise can still deny servicePlatform owner; @grovenetwork-security-core-prpg-tide-relay/src/http_util.rs
T07Destination identity at relay to networkPresent an untrusted, expired, or wrong-host certificateVerified TLS defaults and explicit noisy overridesTLS refusal code and warningInstall the expected CA/certificaterequire intentionally gives encryption-only development behaviorPlatform owner; @grovenetwork-security-core-pr, network-security-kafka-prpg-tide-relay/src/pg_tls.rs
T08Checkpoint state at relay to catalogRewind or advance an offset directlyMonotonic offset API and exact grantsRewind refusal and state comparisonRestore last trusted stateA superuser can mutate catalog stateRelay owner; @groveprivilege-model-pr, delivery-model-prcrash-recovery runbook
T09Receipts and DLQ at relay to catalogDelete, forge, or replay terminal stateRole matrix and transactional terminal stateState and audit checksReconcile from source eventsSource retention limits recoveryRelay owner; @groveprivilege-model-pr, replay-recovery-prDLQ/replay runbook
T10Replay operation at operator to sourceReplay arbitrary or unbounded eventsBounded replay authorization and stable IDsRefusal code and operation logRevoke operation accessAuthorized operators can intentionally replayOperations owner; @groveprivilege-model-pr, replay-recovery-prpg-tide-relay/src/cmd/replay.rs
T11Secret-bearing output at relay to operatorInspect logs, metrics, status, history, or evidenceMasking and sanitized connector errorsPositive-control canary scanRotate values and remove exposed evidenceExternal libraries may still leak unknown textRelay owner; @grovesecret-canary-prpg-tide-relay/src/config/mod.rs
T12Dependency graph at build input to artifactAdd or reach a vulnerable or unlicensed crateLocked graphs, advisory, source, and license policySupply-chain gateBlock and rebuild from reviewed commitNew advisories require refreshed feedsRelease owner; @grovesupply-chain-prscripts/check_supply_chain.py
T13CI release inputs at producer to verifierReplace an artifact, tag, digest, or provenance claimImmutable subjects and separate read-only verifierSignature/SBOM/provenance mismatchWithdraw and rebuildCI provider compromise is outside scopeRelease owner; @groveartifact-policy-pr, artifact-verification-releaserelease-evidence runbook
T14Runtime artifact at build input to containerShip a shell, package manager, key, fixture, or unexpected binaryPath allowlist, modes, content and image policyInventory failureWithdraw and rebuild imageBase-image compromise is outside scopeRelease owner; @groveartifact-policy-prscripts/check_release_artifacts.py
T15Extension function privilege at SQL caller to ownerInvoke a definer function through PUBLIC or unsafe grantsFixed owner, exact execute ACL, locked pathPrivilege inventoryRevoke execute and apply migrationSuperuser control remains authoritativeDatabase owner; @groveprivilege-model-prsql/pg_tide--0.51.0--0.52.0.sql
T16Function name resolution at caller search pathShadow catalog or extension objectspg_catalog, tide search path for definersClean-room function inventoryLock settings and retry migrationNon-definer caller search paths are not a security boundaryDatabase owner; @groveprivilege-model-prpg-tide-ext/src/outbox.rs
T17Restore and rollback state at lifecycle boundaryMix unsupported extension and relay versionsLifecycle matrix, migration transaction, rollback limitsCompatibility refusalRestore matching database and relay pairPhysical restore is required after an irreversible upgradeRelease owner; @grovelifecycle-contract-pr, lifecycle-adjacent-prrelay-upgrade runbook

The model excludes compromise of a PostgreSQL superuser, relay-host root, destination administrator, or infrastructure firewall. Those actors can bypass controls outside pg_tide; the controls still reduce the effect of lesser compromise.

Dependency and Release Artifact Policy

Production profiles are audited independently from experimental profiles. core and core-kafka must pass without advisory ignores. An experimental exception is valid only when it is unreachable from production artifacts, owned, dated, and unexpired in supply-chain/advisory-exceptions.toml.

Dependencies, Rust, GitHub Actions, downloaded tools, and container base images are reviewed weekly and pinned immutably. Critical and high-severity advisories are triaged immediately; an exception has a removal condition and cannot be a permanent release policy.

Every released archive and final image digest receives a matching signature, SBOM, and build-provenance attestation. Release verification must compare the artifact digest to the SBOM and provenance subject before publication.

Unsupported or unimplemented connector/provider dependencies are removed from production profiles rather than hidden behind a successful-looking fallback. LocalKeyFile is the only supported encryption provider in v0.44.0; cloud KMS names are unavailable/experimental and fail before polling.

Version compatibility

The v0.54.0 lifecycle policy is the machine-readable source of truth: lifecycle-compatibility-v1.json. The checker compares this matrix with packaged migrations, required tests, release controls, examples, evidence, and this page.

Supported lifecycle matrix

ExtensionRelayStatusRequired test
0.51.00.51.0supportedlifecycle-adjacent-pr
0.51.00.52.0supportedlifecycle-compatibility-pr
0.52.00.52.0supportedlifecycle-compatibility-pr
0.52.00.53.0supportedlifecycle-compatibility-pr
0.53.00.53.0supportedlifecycle-compatibility-pr
0.53.00.54.0supportedlifecycle-compatibility-pr
0.54.00.54.0supportedlifecycle-compatibility-pr
0.53.00.52.0rejectedlifecycle-compatibility-pr
0.54.00.53.0rejectedlifecycle-compatibility-pr
<0.53.00.54.0rejectedlifecycle-compatibility-pr
>0.54.00.54.0rejectedlifecycle-compatibility-pr

The supported production extension floor remains v0.47.0. Upgrade through every adjacent migration. For the v0.51.0 to v0.52.0 upgrade, replace relays with v0.52.0 before updating the extension. The v0.51.0 relay cannot run after the extension reaches v0.52.0.

Rollback and recovery

The v0.54.0 extension migration is transactional. If it fails before commit, retry from the committed v0.53.0 state. After commit, restore a v0.53.0 backup or use PITR before rolling the relay back.

PostgreSQL recovery does not roll back NATS, Kafka, or webhook destinations. Restoring before a checkpoint commit may redeliver an accepted event. Delivery remains at-least-once. Stable event identities and destination-side deduplication are required.

Do not edit PostgreSQL system catalogs or tide tables to repair a lifecycle transition. Follow the migration policy and retain the recorded evidence.

v0.x → v1.0.0 Migration Guide

Audience: Operators and application developers upgrading from any v0.x release to v1.0.0 GA.
Last updated: v0.36.0 (positional API forms removed in v0.36.0)

Overview

pg_tide v1.0.0 is the first General Availability release. It includes several breaking changes from the v0.x series that require explicit action before upgrading. This guide covers each breaking change, the upgrade procedure, the rollback procedure, and the feature compatibility matrix.

v0.49.0 focused-surface upgrade

The v0.49.0 extension and relay keep the PostgreSQL outbox path and these destinations: PostgreSQL inbox, NATS JetStream, Apache Kafka, and HTTPS webhook. Native JSON and CloudEvents remain the supported envelopes. stdout and file output are diagnostics only.

Before upgrading, inventory the catalog without changing it:

pg-tide migrate-config --postgres-url "$DATABASE_URL"
pg-tide config export --postgres-url "$DATABASE_URL" > pg-tide-v0.48.0.json

The inventory reports reverse pipelines, pg_trickle sources, removed sinks, and removed wire formats with PGTIDE_CONFIG_UNSUPPORTED_SURFACE and last_version=0.48.0. Export every affected row, then disable, replace, or delete it. The 0.48.0 → 0.49.0 SQL migration aborts before dropping any non-empty unsupported state, so retry the extension update only after the reported rows and state have been handled.

ALTER EXTENSION pg_tide UPDATE TO '0.49.0';

Use tide.relay_set_outbox_v2 with source_type = 'outbox' (or omit the source type) and a retained sink. New PostgreSQL destinations should use sink_type = 'inbox'; pg_outbox remains a compatibility alias.

If the migration is blocked, leave the database at v0.48.0, keep the export, and restore the prior relay binary. The migration does not provide a down migration; a database backup is the rollback boundary.

v0.50.0 delivery-correctness upgrade

Stop the relay before updating the extension and binary. The adjacent 0.49.0 → 0.50.0 migration is a no-op compatibility step; it adds no catalog objects.

ALTER EXTENSION pg_tide UPDATE TO '0.50.0';

Replace the relay binary, then start it with the same configuration. Delivery remains at least once: a crash after destination acknowledgment and before checkpoint commit may duplicate an event, but cannot silently lose it. Use pg-tide replay execute --pipeline NAME --from-id N --to-id M for bounded, checkpoint-neutral replay of retained outbox rows.

v0.51.0 upgrade, relay rollback, and recovery

The supported extension floor is v0.47.0. PostgreSQL must apply each packaged adjacent migration through v0.51.0; do not invoke migration files directly:

ALTER EXTENSION pg_tide UPDATE TO '0.51.0';

The rolling relay window is v0.50.0 and v0.51.0. Older relays must stop before the extension update. The v0.51.0 relay checks the installed extension before creating a coordinator and rejects unsupported, malformed, or future versions with PGTIDE_EXTENSION_VERSION_INCOMPATIBLE.

Relay rollback means running the v0.50.0 relay against the v0.51.0 extension; it does not downgrade the extension. The v0.50.0 → v0.51.0 extension boundary is data-preserving but not downgrade-reversible because it registers backup metadata. Restore or PITR is the supported extension rollback boundary.

Use the backup and restore runbook for logical, physical, and PITR recovery. A restore may redeliver an event accepted by an external destination; stable event identity and destination deduplication are required, while external effects are not rolled back by PostgreSQL.


Breaking Changes

1. Positional SQL API variants removed

The following function signatures were removed in v0.36.0 and will not exist in v1.0.0:

Deprecated form (removed)Replacement
tide.relay_set_outbox(name, outbox, sink, config, batch_size, enabled)tide.relay_set_outbox_v2(config JSONB)
tide.relay_set_inbox(name, inbox, config, batch_size, source, enabled, max_retries, idempotent)tide.relay_set_inbox_v2(config JSONB)

These forms were deprecated since v0.18.0, emitted a WARNING on every call since v0.30.0, and were removed in v0.36.0 via the pg_tide--0.35.0--0.36.0.sql migration script. After running ALTER EXTENSION pg_tide UPDATE, any call to the positional forms will fail with ERROR: function tide.relay_set_outbox(...) does not exist.

Action required: Search your application code and migration files for calls to the positional forms and replace them with the JSONB form before upgrading.

Example migration:

-- Before (deprecated positional form — emits WARNING since v0.30.0):
SELECT tide.relay_set_outbox('my-pipeline', 'my-outbox', 'nats', '{}', 100, true);

-- After (v1.0.0 JSONB form):
SELECT tide.relay_set_outbox_v2('{
  "name": "my-pipeline",
  "outbox": "my-outbox",
  "sink_type": "nats",
  "batch_size": 100,
  "enabled": true
}'::jsonb);

To find remaining positional calls in your codebase:

# Search for the deprecated 6-argument form (look for 6 comma-separated args)
grep -rn 'relay_set_outbox\s*(' your-app/ | grep -v '_v2'
grep -rn 'relay_set_inbox\s*(' your-app/ | grep -v '_v2'

2. KMS envelope format (encrypted outboxes only)

v1.0.0 introduces optional envelope encryption with KMS-backed key management. The envelope format for encrypted messages includes a versioned _enc header field that is not backward-compatible with unencrypted payload parsers in v0.x relay binaries.

Action required (only if using encrypted outboxes): If you configure any outbox with tide.outbox_encryption_config(), all relay instances reading that outbox must be upgraded to v1.0.0 before encryption is activated. Unencrypted outboxes are unaffected — no action required.

Rollback note: Enabling encryption on an outbox is a one-way operation. Once the relay has written _enc envelopes, v0.x relay binaries cannot decode them. Disable encryption and allow the relay to drain the encrypted messages before downgrading to v0.x.

3. New required startup configuration (encrypted outboxes only)

When any pipeline's outbox has tide.outbox_encryption_config() set, the relay binary must have KMS connectivity configured (AWS credentials, GCP service account, Vault token, or local key file path, depending on kms_provider). The relay will fail to start if KMS is configured for an outbox but no matching provider credentials are available at startup.


Upgrade Procedure

Rolling upgrade order

The safest upgrade path is:

  1. Upgrade v0.50.0 relay processes to v0.51.0 within the declared rolling window.
  2. Apply the packaged extension update after all pre-v0.50.0 relays are stopped.
  3. Multiple relay instances: replace one supported relay at a time, verifying ownership and delivery before upgrading the next.

Step 1: Update your application code

  1. Replace all calls to the deprecated positional API forms (see Breaking Change #1).
  2. Test in a staging environment with the v0.33.0 binary — any remaining positional calls will emit WARNING in PostgreSQL logs.
  3. Ensure zero positional-form warnings appear in staging before proceeding.

Step 2: Take a full database backup

pg_dump -Fc -d "$PG_URL" -f "pg_tide-pre-v1.0.0-$(date +%Y%m%d).dump"

Step 3: Run the extension upgrade

-- Connect to your PostgreSQL database as superuser or pg_tide extension owner:
ALTER EXTENSION pg_tide UPDATE TO '1.0.0';

This applies all incremental migration scripts from your current version to 1.0.0. The migration is safe to run on a live database — it uses CREATE TABLE IF NOT EXISTS, CREATE OR REPLACE FUNCTION, and ALTER TABLE ... ADD COLUMN IF NOT EXISTS, which do not block ongoing relay operations.

Verify the upgrade:

SELECT extversion FROM pg_extension WHERE extname = 'pg_tide';
-- Expected: 1.0.0

Step 4: Update the relay binary

Replace the pg-tide binary with the v1.0.0 release artifact:

# Example for Linux amd64:
curl -L https://github.com/trickle-labs/pg-tide/releases/download/v1.0.0/pg-tide-linux-amd64 \
     -o /usr/local/bin/pg-tide
chmod +x /usr/local/bin/pg-tide

Step 5: Verify with --self-test

pg-tide --postgres-url "$PG_URL" --self-test

Exit code 0 = pass. Exit code 1 = schema or lifecycle incompatibility; see output for details.

Step 6: Restart the relay

# Kubernetes:
kubectl rollout restart deployment/pg-tide-relay

# systemd:
systemctl restart pg-tide

# Docker Compose:
docker compose up -d --no-deps pg-tide

Rollback Procedure

Only exact reverse scripts listed by the lifecycle policy are supported; restore or PITR is required for the v0.51.0 extension boundary.

Unencrypted deployments (no outbox_encryption_config rows):

  1. Stop the v1.0.0 relay binary.
  2. Restore from the pre-upgrade backup (Step 2 above).
  3. Start the v0.33.0 relay binary.

Encrypted deployments:

  1. Stop the v1.0.0 relay binary.
  2. Disable encryption for all affected outboxes: DELETE FROM tide.outbox_encryption_config;
  3. Allow the relay to process all remaining _enc envelopes (they will be logged as errors by a v0.33.0 binary and routed to DLQ).
  4. Only after the DLQ is clear, restore from the pre-upgrade backup.

Recommendation: Always take a full database backup before running ALTER EXTENSION pg_tide UPDATE.


Feature Compatibility Matrix

Featurev0.xv1.0.0Notes
Transactional outbox✅✅Unchanged
Idempotent inbox✅✅Unchanged
Forward relay (outbox → external sink)✅✅Unchanged
Reverse relay (external source → inbox)✅✅Unchanged
Connector surfaceSee generated matrixSee generated matrixEvidence-based
Wire formats (Debezium, Maxwell, Canal, CloudEvents, native)✅✅Unchanged
DuckLake integration✅✅Unchanged
Outbox table partitioning✅✅Unchanged
Multi-tenant relay groups✅✅Unchanged
Pipeline dependency DAG✅✅Unchanged
KMS envelope encryption❌✅New in v1.0.0
relay_set_outbox() 6-param positional form✅ (⚠️)❌Removed
relay_set_inbox() 8-param positional form✅ (⚠️)❌Removed
WAL logical-replication source🧪 (wal-source)❌Deferred to v1.1.0

⚠️ = deprecated; emits WARNING on every call since v0.30.0.
🧪 = feature-gated proof-of-concept; not production-ready.


Deprecation Schedule

SymbolDeprecated sinceWarning activatedRemoved in
tide.relay_set_outbox() (6-parameter positional form)v0.18.0v0.30.0v1.0.0
tide.relay_set_inbox() (8-parameter positional form)v0.18.0v0.30.0v1.0.0

What is NOT in v1.0.0

See v1-scope.md for a complete list of features explicitly deferred to post-v1.0.0 releases to prevent scope creep. Key exclusions:

  • WAL logical-replication source (v1.1.0)
  • Kafka exactly-once via transactions (v1.1.0)
  • WASM transform plugin system (v1.2.0)
  • Web UI control plane (v1.3.0)
  • Additional connector ecosystems beyond the current generated matrix (v1.1+)
  1. Replace all calls to the deprecated positional API forms (see above).
  2. Test in a staging environment with the v0.30.0 binary (which emits WARNING for any remaining positional calls).

Step 2: Run the extension upgrade

-- Connect to your PostgreSQL database and run:
ALTER EXTENSION pg_tide UPDATE TO '1.0.0';

This applies all incremental migration scripts from your current version to 1.0.0.

Step 3: Update the relay binary

Replace the pg-tide relay binary with the v1.0.0 release artifact. The binary and extension must be upgraded in lockstep — do not run a v0.x binary against a v1.0.0 schema.

Step 4: Verify with --self-test

pg-tide --postgres-url "$PG_URL" --self-test

The self-test will exit 0 on success or report any schema incompatibilities.


Rollback Procedure

Only exact reverse scripts listed by the lifecycle policy are supported; restore or PITR is required for the v0.51.0 extension boundary. To roll back to a v0.x version:

  1. Restore from a pre-upgrade database backup.
  2. Roll back the relay binary to the previous v0.x release.
  3. Do not run ALTER EXTENSION pg_tide UPDATE until ready to re-upgrade.

Recommendation: Always take a full database backup before running ALTER EXTENSION pg_tide UPDATE.


Deprecation Schedule

SymbolDeprecated sinceRemoved in
tide.relay_set_outbox() (6-parameter positional form)v0.18.0v1.0.0
tide.relay_set_inbox() (8-parameter positional form)v0.18.0v1.0.0

What is NOT in v1.0.0

See v1-scope.md for a complete list of features explicitly deferred to post-v1.0.0 releases to prevent scope creep.

Migrating from TOML Configuration to Catalog-First Config

This guide explains how to migrate an existing pg-tide relay from TOML file–based configuration to the catalog-first (catalog_only) mode introduced in v0.28.0.


Background

Prior to v0.28.0, all relay pipeline configuration was defined in a TOML file and loaded at startup. The relay would read the file, construct pipeline workers, and start polling.

Starting with v0.28.0, the relay also supports catalog-first configuration, where pipeline definitions are stored entirely in the PostgreSQL catalog (tide schema tables) and loaded at runtime. This enables dynamic reconfiguration without relay restarts.

The --config-mode flag (or PG_TIDE_CONFIG_MODE env var) controls the mode:

ValueDescription
toml_allowed (default)TOML file is read; catalog entries supplement or override it
catalog_onlyTOML file is ignored; all config must exist in the catalog

Step 1: Export your TOML config to the catalog

Run the migration helper command:

pg-tide migrate-config --postgres-url "postgres://user:password@host:5432/mydb"

This command prints the SQL INSERT statements needed to reproduce your TOML pipeline definitions in the tide catalog tables. Review the output before applying it.

To apply directly (review first!):

pg-tide migrate-config --postgres-url "$DATABASE_URL" | psql "$DATABASE_URL"

Step 2: Verify the catalog entries

Connect to the database and confirm the pipelines were inserted:

SELECT pipeline_name, sink_type, source_type
FROM tide.tide_relay_catalog;

Expected output: one row per pipeline that was defined in your TOML file.


Step 3: Run the doctor

pg-tide doctor --postgres-url "$DATABASE_URL"

All checks should pass, including:

  • tide.relay_delivery_receipts INSERT privilege (v0.28.0)
  • lo_get / lo_unlink EXECUTE privilege (for claim-check support)

Step 4: Switch to catalog-only mode

Update your relay startup command or container environment:

# CLI flag
pg-tide relay --config-mode catalog_only --postgres-url "$DATABASE_URL"

# Or via environment variable
export PG_TIDE_CONFIG_MODE=catalog_only
pg-tide relay --postgres-url "$DATABASE_URL"

In a Kubernetes deployment using the Helm chart:

# values.yaml
relay:
  env:
    - name: PG_TIDE_CONFIG_MODE
      value: catalog_only

Step 5: Validate

Watch the relay logs for a few minutes:

  • Pipeline workers should start without "failed to read TOML" warnings.
  • Messages should flow normally through all pipelines.
  • Delivery receipts should appear in tide.relay_delivery_receipts.

Rollback

To revert to TOML mode, remove the --config-mode catalog_only flag (or unset PG_TIDE_CONFIG_MODE). The relay will fall back to toml_allowed and read the TOML file again on the next restart.

Catalog entries are preserved and do not need to be removed unless you want a clean state.


FAQ

Q: Do I need to remove my TOML file when using catalog_only?
No. The file is simply ignored. You may delete it once you have verified the migration.

Q: What happens if a catalog entry conflicts with a TOML entry in toml_allowed mode?
In toml_allowed mode, the TOML file is authoritative. Catalog entries are merged as supplements. If both define the same pipeline name, the TOML definition wins.

Q: Can I add new pipelines to the catalog while the relay is running?
Yes. The relay reloads catalog entries on each polling cycle. New pipelines become active within one polling interval without a restart.

Troubleshooting

Common issues and their solutions.


Relay Won't Start

"error: --postgres-url is required"

The relay needs a PostgreSQL connection. Provide it via CLI flag or environment variable:

pg-tide run --postgres-url "postgres://user:pass@localhost:5432/mydb"
# or
export PG_TIDE_POSTGRES_URL="postgres://..."
pg-tide run

"PostgreSQL connection failed, retrying"

The relay cannot reach PostgreSQL. Check:

  • Is PostgreSQL running and accepting connections?
  • Is the connection string correct?
  • Are firewall rules allowing the connection?
  • Is the database user granted CONNECT privilege?

The relay retries with exponential backoff indefinitely.


No Messages Being Delivered

Check pending messages exist

SELECT * FROM tide.outbox_retention_status;

If empty, no messages have been published yet.

Check pipeline is enabled

SELECT tide.relay_list_configs();

Ensure the pipeline shows "enabled": true.

Check consumer group exists

Forward pipelines need a consumer group:

SELECT * FROM tide.tide_consumer_groups;

Check relay owns the pipeline

If another relay instance holds the advisory lock, this instance won't process the pipeline. Check logs for "acquired lock" messages.


Duplicate Messages

In the outbox

This is normal — your application may publish the same logical event multiple times. Consider adding a deterministic dedup key in the headers.

In the inbox

If the inbox receives duplicates, the UNIQUE(event_id) constraint should prevent it. If duplicates appear, check:

  • Is the dedup key truly unique per logical event?
  • Was the inbox table created with the UNIQUE constraint?

High Consumer Lag

SELECT * FROM tide.relay_pipeline_lag ORDER BY lag DESC;

Possible causes:

  • Sink is slow — check sink latency and error rate
  • Relay is overwhelmed — increase batch_size or deploy more relay instances
  • Relay is down — check health endpoint and process status
  • Advisory lock not acquired — another relay or stale process holds the lock

Extension Errors

"outbox already exists"

Use p_if_not_exists or check before creating:

SELECT tide.create_consumer_group('my-group', 'events', p_if_not_exists := true);

"outbox not found"

The named outbox doesn't exist. Create it first:

SELECT tide.outbox_create('my-outbox');

Useful Diagnostic Queries

-- All outbox config
SELECT * FROM tide.tide_outbox_config;

-- All inbox config
SELECT * FROM tide.tide_inbox_config;

-- Active relay pipelines
SELECT * FROM tide.relay_outbox_config WHERE enabled;
SELECT * FROM tide.relay_inbox_config WHERE enabled;

-- Advisory locks held (relay pipelines)
SELECT * FROM pg_locks WHERE locktype = 'advisory';

-- Relay offset tracking
SELECT * FROM tide.relay_consumer_offsets;

-- Retention blockers and progress
SELECT * FROM tide.outbox_retention_status;
SELECT * FROM tide.outbox_cleanup_state;
SELECT * FROM tide.outbox_storage_config;

Support bundles

pg-tide doctor --bundle <directory> writes a small, local support directory. The directory is created atomically: the requested path is never replaced or left partially populated. The command fails if the target already exists.

The fixed v1 file set is:

FileContents
manifest.jsonschema version, creation time, file sizes, SHA-256 digests, collection results, bounds, and sharing warning
versions.jsonrelay and installed extension versions plus compatibility class
doctor.jsonschema and required-table checks
status.jsonbounded pipeline health, ownership, lag, checkpoint, retry, and DLQ metadata
error-codes.jsonlatest stable error code metadata already exposed by status
metrics-metadata.jsonstable metric names, types, units, and labels

Each JSON file is bounded. Pipeline rows are limited to 100 and string values to 256 UTF-8 bytes; manifest.json records omitted rows and truncations. The completed directory is limited to 1 MiB. Files use restrictive permissions where the platform supports them.

The manifest lists the other five files; it is intentionally not self-listed because a file cannot contain its own final digest.

Bundles contain no payloads, headers, DLQ contents, pipeline configuration, URLs, environment variables, certificates, keys, trust-store paths, raw SQL errors, connector responses, or logs. Values from diagnostic data are redacted before writing. The manifest uses support-bundle-v1.schema.json.

Review the directory before sharing it. It is not uploaded, compressed, or retained by pg-tide; use your normal archive tool only after reviewing the contents and applying your support process.

Runbook: Crash Recovery

Applies to: pg-tide relay binary (pg-tide run)
Scope: What happens when the relay crashes mid-batch and how to recover.


At-Least-Once Guarantee

pg-tide implements an at-least-once delivery guarantee. When the relay crashes between polling messages from the outbox and acknowledging delivery to the sink, the un-acknowledged messages will be re-delivered after restart because the consumer offset has not advanced.

No manual intervention is required in the normal case. Restart the relay and it resumes from the last committed offset. A crash after sink success but before that commit may produce a duplicate; stable event identity and destination deduplication determine the outcome.


How the Relay Commits Offsets

The relay tracks its position in the outbox via tide.relay_consumer_offsets. After a complete batch reaches a durable terminal disposition, it advances the last_change_id for the pipeline. If the relay crashes before this write, the batch is re-read and re-delivered.

-- Inspect the current offset for each pipeline:
SELECT relay_group_id, pipeline_id, outbox_name, last_change_id, updated_at
FROM   tide.relay_consumer_offsets
ORDER  BY relay_group_id, pipeline_id, outbox_name;

Identifying a Stuck Pipeline

A stuck pipeline is one where exact pipeline lag is not decreasing despite the relay running. Signs include:

  • pg_tide_relay_pipeline_lag{pipeline="..."} is high and flat in Grafana.
  • pg-tide status shows the pipeline as owned but not progressing.
  • Repeated error log entries for the same pipeline.

Common Causes

CauseResolution
Sink is unreachableFix the sink endpoint; pipeline auto-resumes
Circuit breaker is openWait for half-open probe, or restart the worker
DLQ is full / INSERT deniedSee DLQ Replay runbook
Advisory lock held by crashed podSee below

Clearing a Stale Advisory Lock

PostgreSQL advisory locks are session-scoped — they are automatically released when the backend connection closes (e.g. on relay crash or pod eviction). In practice, stale locks resolve themselves within seconds.

If you believe a lock is genuinely stuck (e.g. the PostgreSQL backend is still connected after a relay pod was forcibly killed), identify and terminate it:

-- Find the backend holding the lock for a pipeline named "my-pipeline":
SELECT pid, application_name, state, query_start
FROM   pg_stat_activity
WHERE  pid IN (
    SELECT pid
    FROM   pg_locks
    WHERE  locktype = 'advisory'
      AND  classid = hashtext('default')        -- relay_group_id
      AND  objid   = hashtext('my-pipeline')    -- pipeline name
);

-- Terminate the backend (replaces the lock with nothing; the relay
-- will reacquire on next reconcile):
SELECT pg_terminate_backend(<pid>);

Restart Procedure

  1. Verify the relay process has fully stopped (no ghost connections).
  2. Restart the relay: docker restart pg-tide or kubectl rollout restart deployment/pg-tide.
  3. Watch logs for ownership acquisition and checkpoint transitions confirming pipelines resume.
  4. Check pg-tide status --postgres-url $PG_TIDE_POSTGRES_URL and tide.relay_pipeline_lag for lag convergence.

After a Partial Batch

Duplicate delivery to the sink is possible after a crash. Ensure your sink consumers are idempotent:

  • Use the stable event_id/dedup_key field as an idempotency key.
  • For inbox targets, pg-tide automatically deduplicates via the event_id primary key with ON CONFLICT DO NOTHING.

See Also

Runbook: DLQ Replay

Applies to: pg-tide relay v0.13.0+
Scope: How to drain a flooded dead-letter queue (DLQ), requeue messages for retry, and monitor progress.


What the DLQ Is

When a message cannot be delivered after exhausting retries (permanent error or circuit breaker open), pg-tide writes it to tide.relay_dlq. DLQ insertion is atomic for the complete failed batch: the source checkpoint advances only after every row is durable or already present under its idempotency key.

-- Count DLQ entries per pipeline:
SELECT   pipeline_name, error_kind, COUNT(*) AS entries
FROM     tide.relay_dlq
GROUP BY pipeline_name, error_kind
ORDER BY entries DESC;

Step 1 — Identify the Root Cause

Before requeuing, understand why messages landed in the DLQ:

-- Inspect recent DLQ entries for a pipeline:
SELECT id, event_id, error_kind, error_message, failed_at
FROM   tide.relay_dlq
WHERE  pipeline_name = 'my-pipeline'
ORDER  BY failed_at DESC
LIMIT  20;

Common error_kind values:

KindMeaningResolution
permanentSink rejected the message (invalid schema, auth, etc.)Fix the root cause before requeuing
transientSink was unavailable; max retries exhaustedConfirm sink is healthy, then requeue
dlq_write_failureSecondary DLQ write failureIndicates DLQ table is misconfigured; check tide.relay_dlq permissions

Step 2 — Fix the Underlying Problem

Requeuing DLQ entries while the root cause is still present will return them to the DLQ immediately. Fix the sink, schema, or configuration first:

# Validate pipeline config against the live catalog and sink:
pg-tide config validate --pipeline my-pipeline --postgres-url "$PG_TIDE_POSTGRES_URL"

# Check that the relay can connect to all required services:
pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL"

Step 3 — Requeue Messages for Retry

Requeue is an explicit operator action. It does not implicitly rewind a live relay offset. For a bounded replay, use the one-shot replay command with an explicit range and monitor its completion.

Via SQL

-- Requeue all DLQ entries for a pipeline (marks them as pending retry):
SELECT tide.dlq_requeue('my-pipeline');

-- Requeue a single entry by ID:
SELECT tide.dlq_requeue_entry(42);

Via CLI

# Requeue all DLQ entries for a pipeline:
pg-tide replay dlq-requeue --pipeline my-pipeline --postgres-url "$PG_TIDE_POSTGRES_URL"

# Preview without actually requeuing (dry run):
pg-tide replay dlq-requeue --pipeline my-pipeline --dry-run --postgres-url "$PG_TIDE_POSTGRES_URL"

Step 4 — Monitor Progress

Watch the DLQ depth decrease and message throughput increase:

# Tail the relay logs:
docker logs -f pg-tide 2>&1 | grep -E "(dlq|pipeline=my-pipeline)"

# Or watch Prometheus metrics:
curl -s http://localhost:9090/metrics | grep pg_tide_relay_dlq

Key metrics:

MetricDescription
pg_tide_relay_dlq_entries_written_totalCumulative DLQ writes — should stop growing after root cause is fixed
pg_tide_relay_messages_published_totalShould increase as requeued messages are delivered
pg_tide_relay_consumer_lagShould decrease as the pipeline catches up
pg_tide_relay_delivery_stage_total{stage="dlq_persisted"}Confirms durable DLQ terminal dispositions
pg_tide_relay_delivery_stage_total{stage="dlq_failed"}Alerts on retained source checkpoints

If DLQ persistence succeeds but source checkpointing fails, leave the DLQ rows in place and allow the relay to retry. The idempotency key makes the retry safe; do not manually advance the offset.


Step 5 — Purge Resolved DLQ Entries

After successful redelivery, clean up resolved entries:

-- Delete all successfully redelivered DLQ entries for a pipeline:
DELETE FROM tide.relay_dlq
WHERE  pipeline_name = 'my-pipeline'
  AND  requeued_at IS NOT NULL;

-- Or delete all entries older than 30 days:
DELETE FROM tide.relay_dlq
WHERE  failed_at < NOW() - INTERVAL '30 days';

Flood Control

If the DLQ is growing very fast (more than ~100 entries/min):

  1. Disable the pipeline to stop new DLQ writes:
    SELECT tide.relay_disable('my-pipeline');
    
  2. Fix the root cause.
  3. Clear the DLQ entries that will never be retryable.
  4. Re-enable the pipeline and requeue surviving entries:
    SELECT tide.relay_enable('my-pipeline');
    SELECT tide.dlq_requeue('my-pipeline');
    

See Also

Runbook: NATS JetStream

Scope: Outbox to a configured JetStream stream. Profile: core.

Symptoms

Use pg-tide status --output json --postgres-url "$PG_TIDE_POSTGRES_URL" and look for unavailable, timeout, throttled, authentication, authorization, invalid_destination, or protocol_rejection.

Diagnosis

  1. Run pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL".
  2. Verify the configured stream exists and its subject filter includes the rendered subject. A missing stream is invalid_destination, not a transient outage.
  3. Check pg_tide_relay_connector_failures_total{connector="nats"} without adding URLs, subjects, or upstream exception text as labels.
  4. Confirm NATS credentials and TLS trust configuration from the secret reference.

Recovery

  • unavailable, timeout, or throttled: restore the broker or capacity and let the worker retry.
  • authentication or authorization: repair credentials or permissions.
  • invalid_destination or protocol_rejection: create or repair the JetStream stream and subject policy before retrying.

The sink returns success only after a JetStream publish acknowledgment. Nats-Msg-Id is the stable event identity; JetStream suppresses duplicates only inside the stream's configured duplicate window. A restart can therefore produce a duplicate after that window expires.

Safety

Do not advance offsets manually or delete the stream to clear a retry. Preserve the source batch until the downstream acknowledgment and checkpoint transition are visible in status.

Runbook: Apache Kafka

Scope: Outbox to Kafka producer delivery. Profile: core-kafka.

Symptoms

Use pg-tide status --output json --postgres-url "$PG_TIDE_POSTGRES_URL" and inspect bounded codes: unavailable, timeout, throttled, authentication, authorization, invalid_destination, message_too_large, and protocol_rejection.

Diagnosis

  1. Run pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL".
  2. Verify the broker listener, topic, partition policy, and producer ACL.
  3. Check pg_tide_relay_connector_failures_total{connector="kafka"} and the pipeline checkpoint. Do not expose broker addresses or raw librdkafka errors in status or metrics.
  4. Confirm the topic message limit is at least the configured pg_tide encoded message limit.

Recovery

  • unavailable, timeout, or throttled: restore broker quorum or capacity and allow the bounded retry policy to operate.
  • authentication or authorization: repair SASL/mTLS credentials or ACLs.
  • invalid_destination: create the topic or correct its name/template.
  • message_too_large: reduce the event or raise the broker limit consistently; do not split one logical event.
  • protocol_rejection: repair the topic contract before replaying.

The producer uses acks=all, idempotence, bounded retries, and bounded in-flight requests. Acknowledgment means the broker accepted the record. A replay after relay restart may still be observed by consumers; Kafka producer idempotence is not an exactly-once consumer contract.

Runbook: PostgreSQL Inbox

Scope: sink_type = "inbox" and the pg_outbox compatibility alias. Profile: core.

Symptoms

Inspect the pipeline with pg-tide status --output json --postgres-url "$PG_TIDE_POSTGRES_URL". The useful bounded codes are unavailable, timeout, authentication, authorization, protocol_rejection, and unknown.

Diagnosis

  1. Run pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL".
  2. Confirm the destination inbox exists and is owned by the configured role: SELECT to_regclass('tide."orders_inbox"');
  3. For a remote destination, verify the secret reference resolves to a PostgreSQL URL with certificate verification enabled. Do not paste the URL into logs or tickets.
  4. Check pg_tide_relay_connector_failures_total{connector="inbox"} and the pipeline's last_error_code.

Recovery

  • unavailable or timeout: restore connectivity or failover, then allow the worker to retry. The source checkpoint is not advanced before the destination commit.
  • authentication or authorization: repair the role or secret and restart the worker. Do not increase retry counts.
  • protocol_rejection: repair the inbox schema or permissions before replaying.
  • unknown: inspect redacted relay logs and escalate; do not treat a display string as a retry policy.

Repeated delivery is expected after a crash between destination commit and source checkpoint commit. The inbox unique event_id constraint absorbs that duplicate.

Configuration Contract

Use sink.inbox as the destination name. Omit sink.postgres_url for the relay's local database; set it to a secret reference for a remote database. pg_outbox is only a compatibility alias for the remote inbox behavior.

Runbook: HTTPS Webhook

Scope: Outbox to a receiver-controlled HTTP endpoint. Profile: core.

Symptoms

Use pg-tide status --output json --postgres-url "$PG_TIDE_POSTGRES_URL" and inspect bounded codes: unavailable, timeout, throttled, authentication, authorization, tls_verification, invalid_destination, message_too_large, and protocol_rejection.

Diagnosis

  1. Run pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL".
  2. Confirm the endpoint certificate, hostname, and receiver status without placing credentials or request bodies in logs.
  3. Check pg_tide_relay_connector_failures_total{connector="webhook"} and the pipeline's last success and retry state.
  4. For a signed endpoint, verify the receiver computes HMAC-SHA256 over the exact serialized request body and reads X-Pg-Tide-Signature.

Recovery

  • unavailable, timeout, or throttled: restore the endpoint or honor its rate limit and let the worker retry.
  • authentication or authorization: repair the receiver credential contract.
  • tls_verification: repair the certificate chain or hostname; do not disable verification in production.
  • invalid_destination: correct the URL or redirect configuration. Redirects are refused and are never followed.
  • protocol_rejection: repair the receiver's request contract before replaying.

Every batch has a deterministic Idempotency-Key; a single message uses its stable event_id and a batch uses a hash of ordered event IDs. The receiver owns the retention and meaning of that key. A 2xx response is the downstream acknowledgment.

Operator error catalog

The relay emits the five frozen CLI diagnostic fields. Retryability, runbook ownership, safe context, and exit metadata are defined here.

CodeSurfaceSummaryRetryableExitRunbook
operator.failurecliThe requested operation could not be completed.false1relay-will-not-start
PGTIDE_EXTENSION_VERSION_INCOMPATIBLEcliThe installed pg_tide extension is outside the relay lifecycle policy.false1failed-upgrade
PGTIDE_POSTGRES_UNAVAILABLEcliPostgreSQL is unavailable.true1relay-will-not-start
PGTIDE_POSTGRES_AUTHENTICATIONcliPostgreSQL authentication was rejected.false1relay-will-not-start
PGTIDE_POSTGRES_AUTHORIZATIONcliPostgreSQL denied the requested operation.false1relay-will-not-start
PGTIDE_CATALOG_MISSINGcliThe pg_tide catalog is missing.false1failed-upgrade
PGTIDE_PIPELINE_NOT_FOUNDcliThe requested pipeline was not found.false1pipeline-undiscovered
PGTIDE_PIPELINE_INVALIDcliThe pipeline configuration is invalid.false1relay-will-not-start
PGTIDE_PIPELINE_NOT_DISCOVEREDcliThe pipeline was not discovered by the relay.false1pipeline-undiscovered
PGTIDE_PIPELINE_NOT_OWNEDcliThe relay does not own the requested pipeline.true1ownership-ambiguity
PGTIDE_CONNECTOR_UNAVAILABLEcliThe destination connector is unavailable.true1relay-will-not-start
PGTIDE_CONNECTOR_TIMEOUTcliThe destination connector timed out.true1relay-will-not-start
PGTIDE_CONNECTOR_THROTTLEDcliThe destination connector throttled the request.true1relay-will-not-start
PGTIDE_CONNECTOR_AUTHENTICATIONcliThe destination connector rejected authentication.false1relay-will-not-start
PGTIDE_CONNECTOR_AUTHORIZATIONcliThe destination connector denied authorization.false1relay-will-not-start
PGTIDE_TLS_VERIFICATION_FAILEDcliTLS verification failed.false1relay-will-not-start
PGTIDE_WEBHOOK_SSRF_REJECTEDcliThe webhook destination was rejected by SSRF protection.false1webhook-authentication-failure
PGTIDE_CONNECTOR_INVALID_DESTINATIONcliThe destination address or topic is invalid.false1relay-will-not-start
PGTIDE_CONNECTOR_MESSAGE_TOO_LARGEcliThe connector rejected a message that exceeded its limit.false1relay-will-not-start
PGTIDE_CONNECTOR_PROTOCOL_REJECTIONcliThe destination rejected the request protocol.false1relay-will-not-start
PGTIDE_CONNECTOR_INVALID_CONFIGcliThe connector configuration is invalid.false1relay-will-not-start
PGTIDE_CONNECTOR_UNKNOWNcliThe destination connector failed unexpectedly.true1relay-will-not-start
PGTIDE_REPLAY_INPUT_INVALIDcliThe replay or DLQ input is invalid.false1dlq-growth
PGTIDE_MAINTENANCE_SWEEP_FAILEDcliThe maintenance sweep could not be completed.true1cleanup-failure
PGTIDE_SHUTDOWN_FAILEDcliThe relay could not complete graceful shutdown.true1ownership-ambiguity
PGTIDE_SUPPORT_BUNDLE_WRITE_FAILEDcliThe support bundle could not be written.false1relay-will-not-start
PGTIDE_INTERNAL_FAILUREcliThe relay encountered an internal failure.true1relay-will-not-start
PGTIDE_CONFIG_UNSUPPORTED_SURFACEsqlThe requested configuration surface is not supported.false—failed-upgrade
PGTIDE_OUTBOX_ALREADY_EXISTSsqlThe outbox already exists.false—relay-will-not-start
PGTIDE_OUTBOX_NOT_FOUNDsqlThe outbox was not found.false—relay-will-not-start
PGTIDE_INBOX_ALREADY_EXISTSsqlThe inbox already exists.false—relay-will-not-start
PGTIDE_INBOX_NOT_FOUNDsqlThe inbox was not found.false—relay-will-not-start
PGTIDE_RELAY_NOT_FOUNDsqlThe relay pipeline was not found.false—pipeline-undiscovered
PGTIDE_INVALID_ARGUMENTsqlA SQL function argument is invalid.false—relay-will-not-start
PGTIDE_SWEEP_FAILEDsqlThe outbox sweep failed.true—cleanup-failure
PGTIDE_PUBLISH_DENIEDsqlPublishing to the outbox was denied.false—relay-will-not-start
PGTIDE_AUTHORIZATION_FAILEDsqlThe PostgreSQL authorization check failed.false—relay-will-not-start
PGTIDE_SPI_ERRORsqlThe PostgreSQL catalog operation failed.true—relay-will-not-start

v1 scope

v1.0.0 will be defined only after the v0.47.0 contract freeze, external pilots, independent review, and release evidence are complete. This is a reviewed candidate boundary, not a GA feature list.

Foundation

  • Transactional PostgreSQL outbox and idempotent PostgreSQL inbox.
  • Relay catalog configuration and the documented core relay path.
  • PostgreSQL inbox, NATS JetStream, Apache Kafka, and HTTPS webhook outbound support.
  • Stable, documented delivery, retry, failure, health, metrics, CLI, and envelope behavior covered by release evidence.

Outside the current scope

  • Inbound or reverse relay paths and all preview or experimental connectors.
  • Orchestration, managed backfills, data-lake integrations, and other non-core roadmap surfaces.
  • PostgreSQL versions below 18, arbitrary source-to-sink combinations, exactly-once transport, and a stable Rust or plugin ABI.
  • Internal tables and Rust types, undocumented configuration, and historical roadmap items without current implementation and evidence.

Read the stability guarantees, support policy, and release evidence guidance together.

Glossary

The canonical project glossary is maintained at the repository root as GLOSSARY.md. It is the shared Ubiquitous Language for pg_tide code, SQL APIs, documentation, dashboards, and incident reports.

Keep this page in the documentation navigation so readers can find the glossary from the book, but edit the root file when terminology changes. The root file deliberately uses longer entries to explain how neighboring terms fit together and which guarantees each term does, and does not, provide.

Changelog

Documentation changelog

0.44.0

  • Added documentation for the v0.44.0 privilege boundary, threat model, secret-file policy, dependency policy, and release verification evidence.

0.43.0

  • Added ADR-013 and operational guidance for bounded retention, exact lag, ID-range partitioning, conversion, vacuum, WAL, outage recovery, and measured capacity planning.
  • Removed unverified throughput, CPU, memory, and time-partition claims.

Support policy

Support follows the generated connector compatibility matrix and its source of truth, connectors.toml.

Support levels

  • Production-supported: documented behavior, an owner and security contact, an intentional production profile, and complete applicable contract, integration, failure, restart, duplicate, security, metrics, runbook, upgrade, and packaging evidence.
  • Preview: usable for evaluation, but interfaces, compatibility, and upgrade behavior may change or be removed.
  • Experimental: compile or test coverage only; no production promise.
  • Diagnostic: local output or test assistance, not a production integration.

Maturity is direction-aware. A supported outbound connector does not make its inbound path supported.

v0.53.0 baseline

  • PostgreSQL 18 is the supported PostgreSQL version.
  • The v1 extension upgrade floor is v0.47.0 through the packaged adjacent migration chain.
  • The supported rolling relay window is v0.52.0 and v0.53.0.
  • core is the normal production profile; core-kafka is an explicit opt-in profile for Apache Kafka.
  • Production-supported destinations are PostgreSQL inbox, NATS JetStream outbound, Apache Kafka outbound, and HTTPS webhook outbound.
  • PostgreSQL native outbox is the supported source. Diagnostics are supported only as diagnostics.
  • Linux amd64 and arm64 Docker images are the runtime-tested container targets. Other archives are build artifacts unless the release matrix says otherwise.
  • Helm and CloudNativePG support is limited to the exact profile tested by the lifecycle workflow; other Kubernetes distributions remain preview.

Unlisted service versions and compiling feature combinations are not covered. See the version compatibility guide.

Maintenance

Routine fixes target the latest 0.x minor line. Older minor lines are upgrade-only unless a separate security exception is announced. Preview and experimental interfaces may change in a minor release without a deprecation period. Supported deprecations follow the deprecation policy.

Production-supported definition

A row is production-supported only when all of the following are true:

  1. User-facing behavior is implemented and documented for a specific direction.
  2. Its owner and security contact are recorded in connectors.toml.
  3. Its production profile includes it intentionally.
  4. Current evidence covers the real boundary: contract/integration or E2E behavior, authentication, TLS, redaction, duplicates, failure windows, restart/recovery, metrics, runbook, upgrade, and packaging where applicable.
  5. The supported PostgreSQL 18 path and release artifact exercise it.

The v0.47.0 production-supported outbound set is PostgreSQL inbox, NATS JetStream, Apache Kafka, and HTTPS webhook. PostgreSQL native outbox is the supported source. Diagnostics are not production integrations; inbound connectors and every other registry row remain preview or experimental.

“Builds successfully” or “has a unit test” is not sufficient. Missing evidence downgrades maturity rather than weakening the gate. The generated release checklist shows the evidence recorded for each registry row.

Connector compatibility

This page is generated from connectors.toml. Maturity follows the production-supported policy.

IDDirectionMaturityCargo featureProfilesTested versionsOwnerDocsEvidence
postgresql-outboxsourcesupportedbuilt incorePostgreSQL 18@groveoutbox.mdoutbox_source_test.rs
diagnosticssinksupportedstdoutcorelocal process@grovestdout.mdpostgres_insert_microbenchmark.rs
postgresql-inboxsinksupportedbuilt incorePostgreSQL 18@grovepg-inbox.md, pg-outbox.mdpg_inbox_sink_test.rs, inbox_sink_test.rs, public_api_outbox_to_pg_inbox_e2e.rs
nats-jetstream-sinksinksupportednatscoreNATS Server 2.11.0 with JetStream@grovenats.mdpublic_api_outbox_to_nats_e2e.rs
webhook-sinksinksupportedwebhookcoreHTTP/1.1 with TLS 1.3@grovewebhook.mdwebhook_test.rs, public_api_outbox_to_webhook_e2e.rs
kafka-sinksinksupportedkafkacore-kafkaApache Kafka 3.8.0 KRaft@grovekafka.mdpublic_api_outbox_to_kafka_e2e.rs

A missing evidence category is not yet proved; compiling a connector does not promote it. The normal relay build is core. Kafka production support is explicit in the tested core-kafka profile.

Test levels

pg_tide uses these terms for evidence:

LevelMeaning
UnitOne function or module; no external process is required.
ContractRequest, response, serialization, or protocol shape against a local boundary or faithful stub.
IntegrationAt least two real components interact through their real protocol.
End-to-endA documented public API flow reaches the final observable result through the real coordinator.
ChaosA deliberate failure verifies a safety or recovery invariant.

Cargo's tests/ directory is a layout convention, not proof of integration or end-to-end coverage. Release claims must name the level actually exercised.

Deprecation policy

Deprecation applies to documented, supported APIs and configuration only. Preview and experimental surfaces may change or disappear in a minor release without a deprecation-period promise.

For a supported surface, a deprecation must:

  1. be announced in release notes and the relevant reference page;
  2. identify the replacement, migration steps, and the first release where removal may occur;
  3. emit a bounded, actionable warning where possible without exposing secrets or payloads;
  4. remain supported for at least one subsequent supported minor release; and
  5. be removed only in that announced window, unless a critical security or correctness issue requires an earlier exception.

The release manager records the affected contract, owner, issue, migration evidence, and removal decision. A compatibility alias is not a reason to freeze undocumented behavior.

Feature: Circuit Breaker

The circuit breaker protects your relay pipelines from cascading failures. When a sink becomes unavailable — a Kafka broker goes down, an HTTP endpoint returns 503s, a database connection drops — the circuit breaker detects the pattern of consecutive failures and stops attempting delivery. This prevents wasted resources, avoids flooding error logs, and gives the downstream system time to recover.

State Machine

The circuit breaker has three states:

                 failure_threshold
    ┌────────┐   consecutive     ┌────────┐
    │ CLOSED │ ─────────────────→│  OPEN  │
    │(normal)│                   │(failing)│
    └────────┘                   └────────┘
        ↑                            │
        │   success_threshold        │ half_open_timeout
        │   consecutive              ↓
    ┌────────────┐              ┌───────────┐
    │   CLOSED   │←─────────────│ HALF-OPEN │
    └────────────┘  success     │  (probe)  │
                                └───────────┘
                                     │
                                     │ failure
                                     ↓
                                ┌────────┐
                                │  OPEN  │
                                └────────┘

Closed (normal operation): Messages flow to the sink. Each failure increments a counter; each success resets it. When consecutive failures reach failure_threshold, the circuit opens.

Open (failing): All publish attempts fail immediately without contacting the sink. After half_open_timeout elapses, the circuit transitions to half-open.

Half-open (recovery probe): A single message is allowed through as a probe. If it succeeds, success_threshold consecutive successes close the circuit. If it fails, the circuit re-opens immediately.

Configuration

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-pipeline',
    'outbox', 'order_events',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "kafka:9092",
        "topic": "orders",
        "circuit_breaker": {
            "enabled": true,
            "failure_threshold": 5,
            "success_threshold": 3,
            "half_open_timeout_seconds": 30
        }
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
circuit_breaker.enabledbooltrueEnable circuit breaker
circuit_breaker.failure_thresholdint5Consecutive failures to open circuit
circuit_breaker.success_thresholdint3Consecutive successes to close from half-open
circuit_breaker.half_open_timeout_secondsint30Seconds before open → half-open transition

Behavior When Open

When the circuit is open:

  1. Messages are not sent to the sink (no wasted network calls)
  2. If a DLQ is configured, messages are routed there for later replay
  3. If no DLQ, the worker sleeps until the half-open timeout, then probes
  4. Prometheus metrics reflect the unhealthy state (pipeline_healthy = 0)
  5. The /health endpoint reports the pipeline as unhealthy

Tuning Guidelines

Low failure_threshold (2-3): Opens quickly, aggressive protection. Use for sinks that rarely have transient errors — if they fail twice, something is seriously wrong.

High failure_threshold (10-20): Tolerates intermittent failures. Use for sinks with occasional transient errors (network blips, DNS resolution hiccups).

Short half_open_timeout (5-15s): Recovers quickly after brief outages. Use for sinks that recover fast (load-balanced services, managed cloud endpoints).

Long half_open_timeout (60-300s): Gives downstream systems more time to recover. Use for sinks that take time to restart (database failovers, broker rebalances).

Monitoring

The circuit breaker state is reflected in:

  • Prometheus gauge: pg_tide_pipeline_healthy (1 = closed, 0 = open)
  • Health endpoint: /health returns 503 when any pipeline's circuit is open
  • Logs: State transitions logged at warn level (open) and info level (close)

Further Reading

Feature: Configuration Hot-Reload

pg_tide supports hot-reloading pipeline configurations without restarting the relay process. When you add, modify, or disable a pipeline in the PostgreSQL catalog, the relay detects the change and reconciles — starting new pipelines, stopping removed ones, and updating modified configurations in place.

How It Works

The relay discovers configuration changes through two mechanisms:

  1. LISTEN/NOTIFY — Immediate notification when catalog tables change
  2. Periodic polling — Rediscovers pipelines every discovery_interval_secs (fallback)

When a change is detected, the coordinator compares the new pipeline set against the currently running pipelines:

  • New pipeline → Acquire advisory lock, spawn worker task
  • Removed pipeline → Signal worker to stop, release advisory lock
  • Modified pipeline → Stop old worker, start new one with updated config
  • Disabled pipeline → Same as removed (worker stopped, lock released)

Triggering a Reload

Automatic (via LISTEN/NOTIFY)

The relay listens on the tide_relay_config PostgreSQL notification channel. When you call any tide.relay_set_* function, a notification is emitted automatically:

-- This triggers immediate reload
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-pipeline',
    'outbox', 'order_events',
    'sink_type', 'kafka',
    'config', '{ "brokers": "kafka:9092", "topic": "orders"}'::jsonb
  )
);

Periodic Discovery

Even without NOTIFY (e.g., if the relay reconnects after a network partition), the coordinator polls for changes every discovery_interval_secs:

# Default: 30 seconds
discovery_interval_secs = 30

What Can Be Changed Without Restart

ChangeHot-Reload?Notes
Add new pipeline✓Started within seconds
Remove pipeline✓Gracefully drained and stopped
Change sink type✓Worker restarted with new sink
Change sink config (URL, topic)✓Worker restarted
Change transforms/routing✓Worker restarted
Enable/disable pipeline✓Started or stopped
Change relay process config✗Requires restart
Change metrics_addr✗Requires restart
Change postgres_url✗Requires restart

Graceful Pipeline Transitions

When a pipeline configuration changes, the existing worker is drained before the new one starts:

  1. Worker receives stop signal
  2. Current batch completes (in-flight messages finish)
  3. Source acknowledgment completes
  4. Worker task exits
  5. New worker spawns with updated config
  6. New worker begins polling

This preserves the source checkpoint during reconfiguration. An in-flight batch may be redelivered after a restart or ownership transfer; stable deduplication identities make that duplicate observable and safe where the destination supports deduplication.

Configuration

The discovery mechanism itself is configured at the process level:

# How often to poll for pipeline changes (fallback)
discovery_interval_secs = 30

Or via CLI:

pg-tide --discovery-interval 30

Further Reading

Feature: Grafana Dashboards

pg_tide ships with a pre-built Grafana dashboard that visualizes relay health, throughput, latency, and error rates. Import it into your Grafana instance for instant observability without manual panel creation.

Importing the Dashboard

The dashboard JSON is located at pg-tide/dashboards/relay-health.json in the repository. Import it into Grafana:

  1. Open Grafana → Dashboards → Import
  2. Upload or paste the JSON from pg-tide/dashboards/relay-health.json
  3. Select your Prometheus data source
  4. Click Import

Or use the Grafana API:

curl -X POST http://admin:admin@grafana:3000/api/dashboards/db \
  -H 'Content-Type: application/json' \
  -d @pg-tide/dashboards/relay-health.json

Dashboard Panels

The relay health dashboard includes:

Overview Row

  • Pipeline Status — Table showing each pipeline's health status, last error, and uptime
  • Total Throughput — Graph of messages/second across all pipelines
  • Active Pipelines — Count of currently running pipelines

Throughput Row

  • Messages Published (per pipeline) — Rate of successful publishes
  • Messages Consumed (per pipeline) — Rate of messages polled from source
  • Publish Errors (per pipeline) — Rate of delivery failures

Latency Row

  • Delivery Latency (p50/p95/p99) — Histogram showing message transit time
  • Latency Heatmap — Distribution of delivery times over time

Health Row

  • Circuit Breaker State — Timeline showing open/closed state per pipeline
  • Consumer Lag — Current backlog per pipeline
  • DLQ Entries — Count of unresolved dead letter queue entries

Alerting Rules

Suggested Grafana alert rules to pair with the dashboard:

High Error Rate

alert: PgTideHighErrorRate
expr: rate(pg_tide_publish_errors_total[5m]) > 0.1
for: 5m
labels:
  severity: warning
annotations:
  summary: "pg_tide pipeline {{ $labels.pipeline }} has elevated errors"

Circuit Breaker Open

alert: PgTideCircuitOpen
expr: pg_tide_pipeline_healthy == 0
for: 1m
labels:
  severity: critical
annotations:
  summary: "pg_tide pipeline {{ $labels.pipeline }} circuit breaker is open"

High Consumer Lag

alert: PgTideHighLag
expr: pg_tide_consumer_lag > 10000
for: 10m
labels:
  severity: warning
annotations:
  summary: "pg_tide pipeline {{ $labels.pipeline }} has {{ $value }} pending messages"

Customization

The dashboard uses standard Prometheus queries. Customize it by:

  • Adding panels for specific pipelines
  • Adjusting time ranges and refresh intervals
  • Adding annotations for deployment events
  • Linking to your tracing backend (Tempo, Jaeger) for drill-down

Further Reading

Feature: Dead Letter Queue

When a message fails to deliver after all retry attempts — because the sink rejected it, the payload couldn't be decoded, or a permanent error occurred — it needs somewhere to go. The dead letter queue (DLQ) captures these failed messages in a PostgreSQL table where you can inspect them, understand why they failed, fix the underlying issue, and replay them back through the pipeline.

Without a DLQ, a single poison message can block an entire pipeline. The DLQ isolates failures so healthy messages continue flowing while problematic ones wait for human attention.

How It Works

Message fails        →  Retry (up to max_retries)
Still failing        →  Classify error kind
Route to DLQ         →  INSERT INTO tide.relay_dlq
Continue pipeline    →  Next messages flow normally

Failed messages are inserted into tide.relay_dlq with full context: the pipeline name, source and sink names, the original payload, the error message, and a classification of why it failed.

Error Classifications

Error KindMeaningExample
decodePayload couldn't be decoded from wire formatMalformed JSON, Avro schema mismatch
sink_permanentSink rejected permanently (no retry will help)Invalid credentials, schema validation failure
inbox_permanentInbox insertion failedConstraint violation, duplicate key
max_retries_exceededTransient error persisted beyond retry limitNetwork timeout after 5 attempts

Configuration

DLQ is configured per-pipeline:

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-pipeline',
    'outbox', 'order_events',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "kafka:9092",
        "topic": "orders",
        "dlq": {
            "enabled": true,
            "max_retries": 5,
            "retry_delay_seconds": 10,
            "retention_days": 30
        }
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
dlq.enabledbooltrueEnable dead letter queue
dlq.max_retriesint5Delivery attempts before DLQ routing
dlq.retry_delay_secondsint10Delay between retry attempts
dlq.retention_daysint30Days to keep resolved DLQ entries

Inspecting the DLQ

Query the DLQ table directly:

SELECT id, pipeline_name, error_kind, error_message, created_at
FROM tide.relay_dlq
WHERE resolved_at IS NULL
ORDER BY created_at DESC;

Or use the SQL API:

-- List unresolved DLQ entries for a pipeline
SELECT * FROM tide.relay_dlq_list('orders-pipeline');

-- View full payload of a specific entry
SELECT payload FROM tide.relay_dlq WHERE id = 42;

Replaying Failed Messages

Once you've fixed the underlying issue (corrected credentials, updated schema, fixed payload format), replay messages back through the pipeline:

-- Retry a single message
SELECT tide.relay_dlq_retry(42);

-- Retry all messages for a pipeline
SELECT tide.relay_dlq_retry_all('orders-pipeline');

Replayed messages go through the normal pipeline path. If they fail again, they return to the DLQ with an updated retry count.

Integration with Circuit Breaker

When the circuit breaker opens (sink is unhealthy), messages are routed directly to the DLQ rather than waiting indefinitely. This prevents message buildup in memory while the sink recovers. Once the circuit closes, new messages flow normally — and you can replay DLQ entries to recover the ones that were sidelined.

Monitoring

Track DLQ activity via Prometheus metrics:

  • pg_tide_dlq_entries_total — Total messages routed to DLQ (by pipeline, error_kind)
  • Check the DLQ table row count as part of your alerting

Further Reading

Feature: Graceful Shutdown

When the relay receives a shutdown signal (SIGTERM or SIGINT), it performs a graceful drain. In-flight batches finish or are aborted before the worker's dedicated ownership session is released. A batch whose sink succeeded but whose checkpoint did not commit may be delivered again with the same stable identity.

Shutdown Sequence

1. SIGTERM received
2. Coordinator signals all worker tasks to stop
3. Each worker:
   a. Finishes the current batch publish if possible
   b. Commits the source checkpoint only after durable terminal disposition
   c. Exits its processing loop
4. Coordinator waits for all workers to exit
5. Coordinator releases ownership through the same session (or drops it after abort)
6. Metrics server stops accepting new requests
7. OpenTelemetry flushes pending traces
8. Process exits with code 0

Why This Matters

Without graceful shutdown:

  • In-flight messages could be published to the sink but not acknowledged in the source, causing re-delivery (duplicates)
  • Advisory locks would be held until PostgreSQL's connection timeout (potentially minutes), delaying failover
  • Metrics might not be scraped for the final interval
  • Traces might be lost

With graceful shutdown:

  • A committed source event is retried when its checkpoint was not committed
  • Advisory locks are released only after the worker is gone, enabling safe failover
  • Final metrics are available for scraping
  • All traces are exported

Shutdown Timeout

The relay enforces a maximum shutdown duration. If workers don't exit within the timeout, the worker is aborted before the ownership session is released:

# Default: 30 seconds
pg-tide --shutdown-timeout 30

If a sink is extremely slow (e.g., a webhook endpoint that takes 60 seconds to respond), increase this timeout. In Kubernetes, ensure terminationGracePeriodSeconds exceeds your shutdown timeout.

Kubernetes Integration

In Kubernetes deployments, the pod receives SIGTERM when it's being evicted, scaled down, or updated. Configure your deployment to give pg_tide enough time:

spec:
  terminationGracePeriodSeconds: 60  # Must exceed shutdown-timeout
  containers:
    - name: pg-tide
      command: ["pg-tide", "--shutdown-timeout", "45"]

PreStop Hook (optional)

If you need extra time for load balancers to drain connections to the metrics endpoint:

lifecycle:
  preStop:
    exec:
      command: ["sleep", "5"]

Signal Handling

SignalBehavior
SIGTERMGraceful shutdown (standard Kubernetes signal)
SIGINTGraceful shutdown (Ctrl+C in terminal)
SIGKILLImmediate termination (cannot be caught)

Further Reading

Feature: High Availability Coordination

pg_tide achieves high availability through PostgreSQL advisory locks. Multiple relay instances can run simultaneously — each discovers the same set of pipelines, but only one instance owns each pipeline at any time. If an instance crashes or loses its database connection, its locks are automatically released and another instance takes over.

How It Works

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│  Relay #1   │     │  Relay #2   │     │  Relay #3   │
│ owns: A, B  │     │ owns: C, D  │     │ owns: E     │
└─────────────┘     └─────────────┘     └─────────────┘
       │                   │                   │
       └───────────────────┼───────────────────┘
                           │
                    ┌──────────────┐
                    │  PostgreSQL  │
                    │ advisory locks│
                    └──────────────┘

Each relay instance:

  1. Discovers all enabled pipelines from the catalog
  2. Attempts to acquire a PostgreSQL advisory lock for each pipeline
  3. Only starts worker tasks for pipelines where it holds the lock
  4. Periodically re-checks lock ownership during discovery

The lock is held on the worker's dedicated PostgreSQL session, not a pooled metadata connection. If that session ends, the worker is cancelled before another instance takes ownership. If Relay #1 crashes:

  • PostgreSQL automatically releases its advisory locks (session locks die with the connection)
  • Relay #2 or #3 acquires locks for pipelines A and B on the next discovery cycle
  • Messages continue flowing within discovery_interval_secs

Advisory Lock Mechanics

pg_tide uses pg_try_advisory_lock(key1, key2) where:

  • key1 and key2 are derived by one shared helper from the canonical identity (relay_group_id, tenant_name, direction, pipeline_name). The SQL API still uses PostgreSQL's two-key advisory-lock form.

pg_try_advisory_lock is non-blocking — if another instance holds the lock, it returns false immediately rather than waiting. This means relay instances never deadlock or block each other.

Configuration

Relay Group ID

All relay instances that should coordinate must share the same relay_group_id:

# Instance 1
pg-tide --postgres-url "..." --relay-group-id "production"

# Instance 2
pg-tide --postgres-url "..." --relay-group-id "production"

Instances with different group IDs operate independently — they can both own the same pipeline (useful for blue/green deployments or multi-region setups with separate databases).

Discovery Interval

Controls how quickly failover happens:

pg-tide --discovery-interval 10  # Check every 10 seconds

Lower values = faster failover, but more frequent PostgreSQL queries. The default of 30 seconds is a good balance for most deployments.

Failover Timeline

t=0s    Relay #1 crashes (holds locks for pipeline A, B)
t=0s    PostgreSQL closes connection, releases advisory locks
t=10s   Relay #2 runs discovery cycle
t=10s   Relay #2 acquires lock for pipeline A (success)
t=10s   Relay #2 spawns worker for pipeline A
t=10s   Pipeline A resumes processing

With discovery_interval = 10, worst-case failover is 10 seconds. Committed messages remain eligible from the durable source checkpoint. A crash after sink success but before checkpoint commit can produce a duplicate with the same stable event ID; it does not silently skip the event.

Scaling Patterns

Run N relay instances. Pipelines are distributed across all instances automatically. As you add instances, pipelines rebalance on the next discovery cycle.

Active-Standby

Run 2 instances. The primary acquires all locks. If it fails, the standby takes over. Simpler but less efficient than active-active.

Per-Pipeline Scaling

For high-throughput pipelines, use consumer groups to parallelize within a single pipeline rather than running multiple relay instances.

Graceful Shutdown

When a relay instance receives SIGTERM:

  1. Coordinator sends stop signal to all owned workers
  2. Workers drain their current batch within the timeout
  3. Workers commit the source checkpoint only after sink/DLQ terminal success
  4. Timed-out workers are aborted, then the ownership session is released
  5. Process exits

Other instances detect released locks on next discovery and take ownership.

Monitoring HA

  • Prometheus gauge: pg_tide_pipeline_healthy reports health, not ownership
  • Ownership metrics: acquisition, loss, and transfer counters show lock churn
  • Stage metric: pg_tide_relay_delivery_stage_total{pipeline,stage,outcome}
  • Advisory locks query: SELECT * FROM pg_locks WHERE locktype = 'advisory' shows current ownership
  • Health endpoint: /health reports healthy only if the instance owns at least one pipeline

Further Reading

Feature: Rate Limiting

Rate limiting controls how fast messages flow from the outbox to the sink. It uses a token-bucket algorithm that allows short bursts above the steady-state rate while enforcing a long-term maximum throughput. When the bucket is empty, the relay pauses — this back-pressure propagates upstream, causing outbox rows to accumulate in PostgreSQL until the rate allows them through.

Why Rate Limit?

Rate limiting protects downstream systems from being overwhelmed. Common scenarios:

  • API rate limits: Webhook endpoints, Slack, PagerDuty, and cloud APIs enforce request-per-second limits. Exceeding them causes 429 errors and potential account throttling.
  • Cost control: Cloud services (BigQuery, Kinesis, Pub/Sub) charge per operation. Rate limiting caps your bill predictably.
  • Graceful degradation: During bulk backfill operations, rate limiting prevents your relay from saturating network links or database connections.
  • Fair sharing: Multiple pipelines competing for the same sink — rate limiting ensures each gets predictable throughput.

Configuration

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'notifications',
    'outbox', 'notification_events',
    'sink_type', 'slack',
    'config', '{
        "webhook_url": "${env:SLACK_WEBHOOK_URL}",
        "rate_limit": {
            "enabled": true,
            "max_messages_per_second": 1,
            "burst_size": 5
        }
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
rate_limit.enabledboolfalseEnable rate limiting
rate_limit.max_messages_per_secondint0Steady-state rate (0 = unlimited)
rate_limit.burst_sizeintsame as rateBurst capacity above steady rate

How the Token Bucket Works

The token bucket starts full with burst_size tokens. Each message consumes one token. Tokens refill at max_messages_per_second rate. When the bucket is empty, the relay blocks until tokens are available.

Bucket capacity: burst_size = 10
Refill rate: max_messages_per_second = 5

Time 0s:   [■■■■■■■■■■] 10 tokens (full)
           → Send 10 messages instantly (burst)
Time 0s:   [          ]  0 tokens (empty)
           → Block until tokens refill
Time 1s:   [■■■■■     ]  5 tokens (refilled at 5/s)
           → Send 5 messages
Time 2s:   [■■■■■     ]  5 tokens
           ...

This means:

  • The first batch can send up to burst_size messages immediately
  • After the burst, throughput stabilizes at max_messages_per_second
  • Brief pauses allow tokens to accumulate for the next burst

Back-Pressure Propagation

When the rate limiter blocks, it creates a chain of back-pressure:

  1. Rate limiter blocks → Worker pauses before publishing
  2. Worker pauses → Source poll interval stretches
  3. Source poll stretches → Outbox rows stay in PostgreSQL longer
  4. Rows stay in DB → No data loss, messages wait safely in the transactional outbox

This is safe because the outbox is durable — messages persist in PostgreSQL until acknowledged. The rate limiter doesn't drop messages; it just slows the relay down.

Tuning Guidelines

For webhook/API sinks: Set max_messages_per_second at 80% of the API's documented rate limit. This leaves headroom for retries and other clients.

For streaming sinks (Kafka, NATS): Usually unnecessary — these systems handle high throughput natively. Only rate-limit if you're paying per-message or want to control network bandwidth.

For database sinks (ClickHouse, BigQuery): Set rate to keep bulk insert batches at a comfortable size. 100-1000 msg/s is typical for analytical databases.

Burst size: Set to your expected batch size. If default_batch_size is 100, a burst_size of 100-200 allows full batches to flow without blocking.

Further Reading

Feature: Webhook Signatures

When pg_tide sends outgoing webhooks (via the HTTP webhook sink) or receives incoming webhooks (via the webhook receiver source), it can sign and verify messages using HMAC-based signatures. This ensures the recipient can verify the webhook came from pg_tide (outgoing) and that pg_tide can verify webhooks come from a trusted sender (incoming).

Outgoing Webhook Signatures

When publishing to an HTTP webhook endpoint, pg_tide can sign the request body and include the signature in a header. The receiving service verifies the signature to ensure the request is authentic and hasn't been tampered with.

Configuration (Outgoing)

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'order-notifications',
    'outbox', 'order_events',
    'sink_type', 'webhook',
    'config', '{
        "url": "https://partner.example.com/webhooks/orders",
        "signature": {
            "scheme": "hmac-sha256",
            "secret": "${env:WEBHOOK_SIGNING_SECRET}",
            "header": "X-Signature-256"
        }
    }'::jsonb
  )
);

The signature is computed as HMAC-SHA256(secret, request_body) and sent as a hex-encoded string in the configured header.

Incoming Webhook Verification

When receiving webhooks from external services via the webhook receiver source, pg_tide verifies the signature before accepting the message. Requests with invalid signatures are rejected with HTTP 401.

Configuration (Incoming)

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'stripe-events',
    'inbox', 'payment_inbox',
    'source', 'webhook',
    'config', '{
        "listen_addr": "0.0.0.0:8080",
        "path": "/webhooks/stripe",
        "signature_scheme": "stripe",
        "signature_secret": "${env:STRIPE_WEBHOOK_SECRET}"
    }'::jsonb
  )
);

Supported Signature Schemes

hmac-sha256 — Standard HMAC

The most common webhook signing scheme. Computes HMAC-SHA256 of the request body using a shared secret.

  • Header: Configurable (default: X-Signature-256)
  • Format: sha256=<hex-encoded-hmac>
  • Verification: Recompute HMAC and compare (constant-time)

github — GitHub Webhooks

GitHub's webhook signature format using X-Hub-Signature-256.

  • Header: X-Hub-Signature-256
  • Format: sha256=<hex-encoded-hmac>
  • Secret: Your GitHub webhook secret

stripe — Stripe Webhooks

Stripe's signature includes a timestamp to prevent replay attacks.

  • Header: Stripe-Signature
  • Format: t=<timestamp>,v1=<hmac>
  • Verification: HMAC computed over timestamp.body
  • Replay protection: Rejects signatures with timestamps too far in the past

svix — Svix Webhook Platform

Svix is a webhook delivery platform. pg_tide can verify Svix-signed webhooks.

  • Header: svix-signature
  • Format: Svix-specific signature scheme
  • Includes: Message ID, timestamp, and signature

Security Considerations

  • Always use HTTPS for webhook endpoints. Signatures prove authenticity but don't encrypt the payload.
  • Rotate secrets periodically. When rotating, you can temporarily accept both old and new secrets.
  • Use environment variables for secrets (never hardcode): ${env:SECRET_NAME}
  • Reject stale timestamps (Stripe scheme does this automatically) to prevent replay attacks.

Further Reading

CloudNativePG Integration

CloudNativePG (CNPG) is the most popular PostgreSQL operator for Kubernetes. pg_tide integrates naturally with CNPG: the relay runs as a sidecar container alongside each PostgreSQL pod, sharing the same lifecycle and connection string.

Quick start

See the ready-to-use manifest in examples/cnpg/cluster.yaml.

Custom PostgreSQL image

CNPG uses container images for PostgreSQL. To bundle pg_tide, extend the official CNPG image:

FROM ghcr.io/cloudnative-pg/postgresql:18

# Copy the compiled extension files.
COPY pg_tide.so      /usr/lib/postgresql/18/lib/
COPY pg_tide.control /usr/share/postgresql/18/extension/
COPY sql/pg_tide--0.1.0.sql /usr/share/postgresql/18/extension/

Build and push to your container registry, then reference it in the CNPG Cluster spec:

spec:
  imageName: ghcr.io/your-org/postgres-pg-tide:18

Sidecar pattern

The relay runs as a sidecar in the same pod as PostgreSQL. It connects to localhost:5432 via the injected *-app secret that CNPG creates automatically:

spec:
  sidecars:
    - name: pg-tide-relay
      image: ghcr.io/trickle-labs/pg-tide:0.51.0
      env:
        - name: PG_TIDE_POSTGRES_URL
          valueFrom:
            secretKeyRef:
              name: my-cluster-app    # CNPG-generated secret
              key: uri

Because the relay runs in the same pod, it connects over the loopback interface with zero network latency — ideal for high-throughput workloads.

High availability

CNPG manages primary/replica failover automatically. The relay on the primary pod holds PostgreSQL advisory locks on each pipeline. When a failover occurs:

  1. The primary pod is terminated → advisory locks are released.
  2. CNPG promotes a replica to primary.
  3. The relay sidecar on the new primary pod starts and acquires the locks.
  4. Message delivery resumes from the last committed consumer offset.

In-flight messages from the old primary are re-delivered when their source checkpoint was not yet advanced. A downstream publish may therefore duplicate with the same stable event ID; it does not silently skip the event.

Initialisation SQL

Bootstrap pg_tide only when CNPG creates the cluster. Existing clusters need an explicit migration Job after the extension image is available:

spec:
  bootstrap:
    initdb:
      database: app
      owner: app
      postInitSQL:
        - CREATE EXTENSION IF NOT EXISTS pg_tide;
        - CREATE ROLE relay_user LOGIN PASSWORD 'strong-password';
        - GRANT USAGE ON SCHEMA tide TO relay_user;
        - GRANT SELECT, INSERT ON tide.tide_outbox_messages TO relay_user;
        - GRANT SELECT ON ALL TABLES IN SCHEMA tide TO relay_user;

Prometheus monitoring

CNPG integrates with the Prometheus Operator. Add a ServiceMonitor to scrape relay metrics alongside the built-in CNPG metrics:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: pg-tide-relay
spec:
  selector:
    matchLabels:
      cnpg.io/cluster: my-cluster
  endpoints:
    - port: relay-metrics
      path: /metrics
      interval: 15s

Integration: Datadog

This guide covers monitoring pg_tide with Datadog, including metrics collection, log forwarding, and APM trace correlation.

Metrics Collection

Option 1: Prometheus Integration

Datadog's OpenMetrics check can scrape pg_tide's Prometheus endpoint directly:

# datadog-agent/conf.d/openmetrics.d/conf.yaml
instances:
  - openmetrics_endpoint: http://pg-tide-relay:9090/metrics
    namespace: pg_tide
    metrics:
      - pg_tide_messages_published_total
      - pg_tide_messages_consumed_total
      - pg_tide_publish_errors_total
      - pg_tide_dedup_skipped_total
      - pg_tide_pipeline_healthy
      - pg_tide_consumer_lag
      - pg_tide_delivery_latency_seconds

Option 2: Kubernetes Annotations

With the Datadog Agent running as a DaemonSet:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: pg-tide-relay
spec:
  template:
    metadata:
      annotations:
        ad.datadoghq.com/pg-tide.checks: |
          {
            "openmetrics": {
              "instances": [{
                "openmetrics_endpoint": "http://%%host%%:9090/metrics",
                "namespace": "pg_tide",
                "metrics": ["pg_tide_*"]
              }]
            }
          }

Log Collection

Structured JSON Logs

Configure the relay to emit JSON logs:

pg-tide --log-format json --postgres-url "..."

Datadog Agent Log Collection

# Kubernetes pod annotation
annotations:
  ad.datadoghq.com/pg-tide.logs: |
    [{
      "source": "pg-tide",
      "service": "pg-tide-relay",
      "log_processing_rules": [{
        "type": "multi_line",
        "name": "rust_panics",
        "pattern": "^thread '"
      }]
    }]

Log Facets

Create facets for common fields:

  • pipeline — Pipeline name
  • direction — forward/reverse
  • batch_size — Messages in batch
  • error — Error message

APM / Traces

Option 1: OpenTelemetry → Datadog

pg_tide exports OTLP traces. Route them through the OTEL Collector to Datadog:

# otel-collector-config.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: "0.0.0.0:4317"

exporters:
  datadog:
    api:
      key: ${DD_API_KEY}

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [datadog]

Configure pg_tide to send traces:

pg-tide --otel-endpoint "http://otel-collector:4317" --postgres-url "..."

Option 2: Datadog Agent OTLP Ingestion

The Datadog Agent can receive OTLP directly (Agent 7.35+):

# datadog.yaml
otlp_config:
  receiver:
    protocols:
      grpc:
        endpoint: "0.0.0.0:4317"
pg-tide --otel-endpoint "http://datadog-agent:4317" --postgres-url "..."

Dashboards

Create a Datadog dashboard with these widgets:

Throughput (Timeseries)

sum:pg_tide.pg_tide_messages_published_total.count{*} by {pipeline}.as_rate()

Error Rate (Timeseries)

sum:pg_tide.pg_tide_publish_errors_total.count{*} by {pipeline}.as_rate()

Pipeline Health (Query Value)

min:pg_tide.pg_tide_pipeline_healthy{*} by {pipeline}

Consumer Lag (Timeseries)

avg:pg_tide.pg_tide_consumer_lag{*} by {pipeline}

Monitors (Alerts)

Pipeline Down

Monitor Type: Metric
Query: min(last_5m):min:pg_tide.pg_tide_pipeline_healthy{*} by {pipeline} < 1
Alert: Pipeline {{pipeline.name}} is unhealthy

High Error Rate

Monitor Type: Metric
Query: sum(last_5m):sum:pg_tide.pg_tide_publish_errors_total.count{*} by {pipeline}.as_rate() > 1
Warning: Pipeline {{pipeline.name}} error rate above threshold

Growing Lag

Monitor Type: Metric
Query: avg(last_10m):avg:pg_tide.pg_tide_consumer_lag{*} by {pipeline} > 10000
Warning: Pipeline {{pipeline.name}} has {{value}} pending messages

Further Reading

dbt Integration

dbt (data build tool) transforms data inside PostgreSQL using SQL SELECT statements. pg_tide can bridge the gap between dbt-managed tables and external consumers: any dbt model that writes to a table can trigger an outbox publish, and inbound events can feed into a staging table that dbt reads.

Pattern 1 — Publish dbt model output to the outbox

After a dbt model run completes, use a PostgreSQL trigger or an explicit CALL/SELECT to publish new rows to the outbox:

Trigger-based approach

-- Fired automatically whenever dbt inserts into the target table.
CREATE OR REPLACE FUNCTION public.on_customer_upsert()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
    PERFORM tide.outbox_publish(
        'customers',
        row_to_json(NEW)::jsonb,
        '{"x-op": "upsert", "x-model": "dim_customers"}'::jsonb
    );
    RETURN NEW;
END;
$$;

CREATE TRIGGER publish_customer_events
    AFTER INSERT OR UPDATE ON public.dim_customers
    FOR EACH ROW EXECUTE FUNCTION public.on_customer_upsert();

Post-hook approach (dbt project.yml)

# dbt_project.yml
models:
  my_project:
    dim_customers:
      +post-hook: >
        INSERT INTO tide.tide_outbox_messages (outbox_name, payload, headers)
        SELECT
            'customers',
            row_to_json(t)::jsonb,
            '{}'::jsonb
        FROM {{ this }} t
        WHERE updated_at > '{{ run_started_at }}'

Pattern 2 — Read inbox events in a dbt source

Configure the inbox table as a dbt source so that transformation models can join against inbound events:

# sources.yaml
sources:
  - name: tide
    schema: tide
    tables:
      - name: payments_inbox
        description: "Inbound payment events from Stripe via the pg_tide relay"
        columns:
          - name: event_id
            description: "Globally unique event identifier (dedup key)"
          - name: payload
            description: "Event payload as JSONB"
          - name: received_at
            description: "Timestamp when the event arrived in the inbox"

Then reference it in a dbt model:

-- models/stg_payments.sql
SELECT
    event_id,
    payload ->> 'payment_id'   AS payment_id,
    (payload ->> 'amount_cents')::int AS amount_cents,
    payload ->> 'currency'     AS currency,
    received_at
FROM {{ source('tide', 'payments_inbox') }}
WHERE processed_at IS NOT NULL

Pattern 3 — Event-driven dbt runs

Use pg_notify to trigger a dbt run when new outbox messages arrive:

-- Notify an external listener whenever the outbox receives a new message.
CREATE OR REPLACE FUNCTION tide.notify_dbt_trigger() RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
    PERFORM pg_notify('dbt_run_trigger', NEW.outbox_name);
    RETURN NEW;
END;
$$;

CREATE TRIGGER dbt_trigger
    AFTER INSERT ON tide.tide_outbox_messages
    FOR EACH ROW EXECUTE FUNCTION tide.notify_dbt_trigger();

A lightweight listener process (e.g. a Python script using psycopg2) can then invoke dbt run --select <model> on demand.

Best practices

  • Idempotency: dbt runs must be idempotent. Use ON CONFLICT DO NOTHING or surrogate keys when writing to tables that publish to the outbox.
  • Dedup keys: Set event_id in the payload to a deterministic key (e.g. {{ dbt_utils.generate_surrogate_key(['order_id', 'updated_at']) }}) so that the inbox deduplicates re-runs correctly.
  • Schema versioning: Add a _schema_version field to every outbox payload so downstream consumers can handle schema evolution gracefully.

Integration: GitHub Actions

This guide shows how to integrate pg_tide into your CI/CD pipeline with GitHub Actions — running tests against the extension, deploying relay instances, and managing database migrations.

Testing pg_tide in CI

Run Integration Tests

name: Test pg_tide pipelines
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
          POSTGRES_DB: testdb
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - uses: actions/checkout@v4

      - name: Install pg_tide extension
        run: |
          # Install the extension into the test database
          PGPASSWORD=test psql -h localhost -U postgres -d testdb -f sql/pg_tide--0.11.0.sql

      - name: Create test outbox and inbox
        run: |
          PGPASSWORD=test psql -h localhost -U postgres -d testdb -c "
            SELECT tide.outbox_create('test_events');
            SELECT tide.inbox_create('test_inbox');
          "

      - name: Run application tests
        run: |
          DATABASE_URL="postgres://postgres:test@localhost/testdb" cargo test
        env:
          DATABASE_URL: postgres://postgres:test@localhost/testdb

Validate Pipeline Configurations

      - name: Validate pipeline configs
        run: |
          # Dry-run the relay to validate all pipeline configs parse correctly
          pg-tide \
            --postgres-url "postgres://postgres:test@localhost/testdb" \
            --validate-only

Deploy Relay to Kubernetes

name: Deploy pg-tide relay
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build and push relay image
        uses: docker/build-push-action@v5
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}/pg-tide-relay:${{ github.sha }}

      - name: Deploy to Kubernetes
        uses: azure/k8s-deploy@v4
        with:
          manifests: k8s/relay-deployment.yaml
          images: ghcr.io/${{ github.repository }}/pg-tide-relay:${{ github.sha }}

Database Migrations

Apply Extension Upgrades

name: Migrate pg_tide
on:
  workflow_dispatch:
    inputs:
      target_version:
        description: 'Target pg_tide version'
        required: true
        default: '0.11.0'

jobs:
  migrate:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4

      - name: Apply migration
        run: |
          psql "${DATABASE_URL}" -c "ALTER EXTENSION pg_tide UPDATE TO '${{ inputs.target_version }}';"
        env:
          DATABASE_URL: ${{ secrets.DATABASE_URL }}

Configure Pipelines on Deploy

      - name: Apply pipeline configurations
        run: |
          for config_file in pipelines/*.sql; do
            echo "Applying $config_file"
            psql "${DATABASE_URL}" -f "$config_file"
          done
        env:
          DATABASE_URL: ${{ secrets.DATABASE_URL }}

Health Check After Deploy

      - name: Wait for relay to be healthy
        run: |
          for i in $(seq 1 30); do
            STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://$RELAY_HOST:9090/health)
            if [ "$STATUS" = "200" ]; then
              echo "Relay is healthy"
              exit 0
            fi
            echo "Waiting... (attempt $i)"
            sleep 5
          done
          echo "Relay did not become healthy"
          exit 1

Further Reading

Integration: Microcks

Microcks is a CNCF incubating project for API mocking and contract conformance testing. It ingests AsyncAPI, OpenAPI, gRPC, and GraphQL specifications — including the document emitted by pg-tide asyncapi export — and uses the examples within them to both mock event channels and verify that real consumers and producers stay conformant to the contract.

This guide shows how to use pg-tide asyncapi export as a first-class integration touchpoint: export your relay spec, import it into Microcks, develop against the mocks, and gate your CI pipeline on contract conformance.


Why This Matters

pg-tide publishes events from the database to any number of downstream consumers. Those consumers need a stable, documented contract: "what topics exist, in what format, with what shape of payload?" Today that contract lives implicitly inside pg-tide's relay configuration. The asyncapi export command makes it explicit — and Microcks makes it enforceable.

PostgreSQL → pg-tide relay → [Kafka / NATS / SQS / …] → consumers
                    ↓
             asyncapi export
                    ↓
               Microcks ──► mock topics (development)
                        ──► conformance test (CI)

Prerequisites

RequirementVersion
pg-tide CLI (pg-tide)≥ 0.14.0
Docker / Docker Composeany recent
Microcks (dev-mode image)≥ 1.11.0

Step 1 — Export Your AsyncAPI Spec

Connect to a database that has relay pipelines configured and run:

pg-tide asyncapi export \
  --postgres-url "postgres://user:pass@localhost/mydb" \
  --format yaml \
  > relay-asyncapi.yaml

This produces an AsyncAPI 3.0 YAML document that enumerates every outbox forward pipeline and every inbox reverse pipeline as named channels, operations, and message schemas.

Example output excerpt:

asyncapi: 3.0.0
info:
  title: pg-tide Relay AsyncAPI
  version: 0.16.0
  description: Auto-generated AsyncAPI 3.0 document from pg-tide relay catalog metadata.
channels:
  forward/orders:
    address: kafka/orders
    description: "Forward relay: outbox 'orders' → kafka"
    messages:
      ordersMessage:
        $ref: '#/components/messages/ordersMessage'
operations:
  sendOrders:
    action: send
    channel:
      $ref: '#/channels/forward~1orders'
    description: "Publish messages from outbox 'orders' to kafka"
components:
  messages:
    ordersMessage:
      name: ordersMessage
      contentType: application/json
      payload:
        type: object
        description: "pg_tide outbox message (wire_format: cloudevents)"

Enriching the spec: The auto-generated payload schemas use type: object as a baseline. For full contract value, add JSON Schema definitions for your actual message payloads either by hand or by running asyncapi export against a database where schema evolution guardrails have already captured column types.


Step 2 — Start Microcks Locally

The quickest path is Microcks' dev-mode Docker Compose, which bundles a Kafka broker (Redpanda) alongside the Microcks server:

git clone https://github.com/microcks/microcks
cd microcks/install/docker-compose
docker compose -f docker-compose-devmode.yml up -d

Wait until all five containers are healthy, then open http://localhost:8080.


Step 3 — Import the Spec

Via the Microcks UI

  1. Go to API | Services → Import.
  2. Upload relay-asyncapi.yaml as a primary artifact.
  3. Microcks parses the channels and begins publishing mock messages to the embedded Kafka broker on the addresses defined in the spec.

Via the Microcks REST API (CI-friendly)

curl -s -X POST http://localhost:8080/api/v1/artifact/upload \
  -H "Content-Type: multipart/form-data" \
  -F "file=@relay-asyncapi.yaml"

Step 4 — Develop Against Mock Topics

Once imported, Microcks publishes mock events at regular intervals to Kafka topics named after the channel addresses in your spec. Downstream consumer teams can target the Microcks Kafka endpoint instead of a real pg-tide deployment:

# Confirm mock messages are flowing
kcat -b localhost:9092 -t kafka/orders -C -e

# Output:
# {"id":1,"type":"order.created","source":"/orders","data":{...}}
# {"id":2,"type":"order.updated","source":"/orders","data":{...}}

This means consumer teams can write and test their Kafka consumers in isolation — no running PostgreSQL, no relay process, no seeded test data required.


Step 5 — Run Conformance Tests

Once a real pg-tide relay is running (e.g., in a staging environment), use Microcks to verify that the actual published events conform to the spec:

Via the Microcks UI

  1. Go to the imported pg-tide Relay AsyncAPI service.
  2. Click New Test, set the endpoint to your staging Kafka broker (kafka://staging-kafka:9092), choose AsyncAPI conformance as the runner.
  3. Microcks subscribes to the topic, collects messages, validates them against the schema and examples, and returns a conformance score.

Via the REST API (CI step)

# Retrieve the service ID
SERVICE_ID=$(curl -s http://localhost:8080/api/v1/services \
  | jq -r '.[] | select(.name=="pg-tide Relay AsyncAPI") | .id')

# Launch the conformance test
TEST_ID=$(curl -s -X POST http://localhost:8080/api/v1/tests \
  -H "Content-Type: application/json" \
  -d '{
    "serviceId": "'"$SERVICE_ID"'",
    "testEndpoint": "kafka://staging-kafka:9092",
    "runnerType": "ASYNC_API_SCHEMA",
    "timeout": 15000
  }' | jq -r '.id')

echo "Test launched: $TEST_ID"

# Poll for result
sleep 20
curl -s http://localhost:8080/api/v1/tests/$TEST_ID \
  | jq '{success: .success, conformanceScore: .conformanceScore}'

A failing test means the relay is publishing events that violate the contract — caught before production.


Step 6 — Gate CI on the Contract

GitHub Actions example

name: Contract conformance

on:
  push:
    branches: [main]

jobs:
  contract-test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env: { POSTGRES_PASSWORD: test, POSTGRES_DB: ci }
        ports: ["5432:5432"]

    steps:
      - uses: actions/checkout@v4

      - name: Install pg_tide + seed pipelines
        run: |
          PGPASSWORD=test psql -h localhost -U postgres ci \
            -f sql/pg_tide--0.16.0.sql
          # ...register relay pipelines via tide.relay_*_upsert()...

      - name: Export AsyncAPI spec
        run: |
          pg-tide asyncapi export \
            --postgres-url "postgres://postgres:test@localhost/ci" \
            --format yaml > relay-asyncapi.yaml

      - name: Start Microcks
        run: |
          git clone --depth 1 https://github.com/microcks/microcks /tmp/microcks
          docker compose \
            -f /tmp/microcks/install/docker-compose/docker-compose-devmode.yml \
            up -d
          # Wait for readiness
          until curl -sf http://localhost:8080/api/v1/health; do sleep 2; done

      - name: Import spec into Microcks
        run: |
          curl -s -X POST http://localhost:8080/api/v1/artifact/upload \
            -F "file=@relay-asyncapi.yaml"

      - name: Verify mock topics are live
        run: |
          # At least one message must arrive within 10 s
          kcat -b localhost:9092 -t kafka/orders -C -c 1 -e -w 10

      - name: Run conformance test against relay
        run: |
          # Start relay against test DB pointing at Microcks Kafka
          pg-tide --postgres-url "postgres://postgres:test@localhost/ci" &
          sleep 5

          SERVICE_ID=$(curl -s http://localhost:8080/api/v1/services \
            | jq -r '.[] | select(.name=="pg-tide Relay AsyncAPI") | .id')

          RESULT=$(curl -s -X POST http://localhost:8080/api/v1/tests \
            -H "Content-Type: application/json" \
            -d "{\"serviceId\":\"$SERVICE_ID\",
                 \"testEndpoint\":\"kafka://localhost:9092\",
                 \"runnerType\":\"ASYNC_API_SCHEMA\",
                 \"timeout\":15000}")

          TEST_ID=$(echo $RESULT | jq -r '.id')
          sleep 20

          SUCCESS=$(curl -s http://localhost:8080/api/v1/tests/$TEST_ID \
            | jq -r '.success')

          echo "Contract test success: $SUCCESS"
          [ "$SUCCESS" = "true" ]

Enriching the Generated Spec

The exported spec is intentionally minimal — type: object payload schemas are safe placeholders. You can enrich it in two ways:

Option A — Secondary artifact with example payloads

Create a relay-examples.yaml in the Microcks API Examples Format and import it as a secondary artifact alongside relay-asyncapi.yaml. Microcks merges the two: the spec provides structure, the examples provide realistic mock data and dynamic templates.

# relay-examples.yaml
apiVersion: mocks.microcks.io/v1alpha1
kind: APIExamples
metadata:
  name: pg-tide Relay AsyncAPI
  version: 0.16.0
operations:
  sendOrders:
    examples:
      order-created:
        value:
          id: "{{ uuid() }}"
          specversion: "1.0"
          type: "order.created"
          source: "/orders"
          time: "{{ now() }}"
          data:
            orderId: "{{ randomInt(1000,9999) }}"
            customerId: "{{ randomInt(100,999) }}"
            total: "{{ randomInt(10,500) }}.00"

Option B — Emit richer schemas from the relay config

If your relay configuration stores JSON Schema definitions alongside the wire format config, pg-tide can incorporate them into the exported spec. Open an issue or contribute a PR to pg-tide-relay/src/main.rs::run_asyncapi_export to expose this.


Summary

StepWhat you get
asyncapi exportA machine-readable contract for every relay pipeline
Import into MicrocksLive mock Kafka/NATS/SQS topics for consumer development
Conformance testAutomated verification that the relay honours the contract
CI gateCatch wire-format regressions before they reach production

The pg-tide asyncapi export command is the bridge between pg-tide's relay catalog and the broader API-contract ecosystem. Microcks is the natural home for running and enforcing that contract.

See Also

pg-trickle Integration

pg-trickle is the PostgreSQL extension that pg_tide was originally extracted from. If you already use pg-trickle, you can adopt pg_tide incrementally — or run both side-by-side during a migration.

When to use pg_tide instead of pg-trickle

SituationRecommendation
Starting a new projectUse pg_tide — it is the focused, standalone successor
Existing pg-trickle installationMigrate when ready; pg_tide's schema is compatible
Need stream tables (pg_trickle_streams)Stay on pg-trickle for now
Need transactional outbox + inbox onlypg_tide covers this fully

Stream tables and the inbox→outbox bridge

pg-trickle's stream tables enable a powerful routing pattern: a stream table attached to an outbox can watch a pg_tide inbox, and any new row inserted into the inbox is automatically republished to the outbox. This creates a two-hop path from an external source to a downstream sink:

External source (Kafka) → relay → inbox (PostgreSQL)
                                        ↓ stream table trigger
                                   outbox (PostgreSQL) → relay → sink (DuckLake)

This pattern is functionally equivalent to pg_tide's reverse pipeline sinks (where the relay routes directly from source to sink without any PostgreSQL intermediate), but the two approaches have different guarantees, costs, and capabilities.

The critical distinction is durability and the dedup boundary:

  • The inbox→outbox bridge provides PostgreSQL-strength durable deduplication: the inbox UNIQUE(event_id) constraint is the dedup wall. With transactional application processing, the outcome can be effectively exactly once. Once a message is in PostgreSQL, it is durable regardless of Kafka retention or downstream sink availability. Messages accumulate in the outbox and are delivered in order when the sink recovers — even after days of outage.

  • pg_tide's reverse pipeline sinks provide sink-dependent deduplication: the relay routes directly from Kafka to the sink (DuckLake, MongoDB, etc.) using _dedup_key for idempotency. Durability depends on Kafka retention — if the sink is unavailable for longer than the Kafka topic's retention period, messages that have not yet been delivered are lost.

Use the inbox→outbox bridge when you need unconditional durability, SQL transforms or enrichment between receipt and publication, fan-out to multiple sinks, or a full PostgreSQL audit trail.

Use the reverse pipeline sink when the path is a simple A→B data move, Kafka retention is long enough to absorb any realistic outage, and the PostgreSQL write overhead is not justified by business requirements.

See Message Guarantees — Reverse Pipeline Sink vs. Inbox→Outbox Bridge for a full side-by-side comparison including the durability table, dedup boundary explanation, and decision guide.

Schema compatibility

pg_tide uses a tide.* schema prefix. pg-trickle uses pg_trickle_* table names. The two schemas can coexist in the same database without conflict.

Migrating from pg-trickle

1. Install pg_tide alongside pg-trickle

CREATE EXTENSION pg_tide;

2. Create matching outboxes and inboxes

For each pg_trickle_outbox in your existing schema:

SELECT tide.outbox_create(outbox_name, retention_hours)
FROM pg_trickle_outbox_config;

3. Migrate pending messages

INSERT INTO tide.tide_outbox_messages (outbox_name, payload, headers, created_at)
SELECT stream_name, payload, headers, created_at
FROM pg_trickle_outbox_messages
WHERE consumed_at IS NULL;

4. Point the relay at pg_tide

Update your pg-tide relay configuration:

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'my-pipeline',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', '{"url":"tls://nats.example:4222"}'::jsonb
  )
);

5. Verify and cut over

Run both relays in parallel during the transition. Once the pg_tide relay is processing all new messages, decommission the pg-trickle relay.

Using both together

Both extensions can write to the same NATS subject or Kafka topic — consumers should use the x-source header to distinguish messages originating from pg_tide versus pg-trickle.

pg_tide stamps every envelope with:

{
  "id": 42,
  "outbox_name": "orders",
  "payload": { ... },
  "headers": { "x-source": "pg-tide", "x-outbox": "orders" }
}

PgBouncer Integration

PgBouncer is the standard PostgreSQL connection pooler. pg_tide's relay can run comfortably behind PgBouncer with a couple of small configuration choices.

Which pool mode to use

Pool modeAdvisory locksLISTEN/NOTIFYpg_tide compatibility
Session✅ Work✅ Work✅ Recommended
Transaction❌ Released between statements❌ Do not work⚠️ Not recommended for the relay
Statement❌❌❌ Do not use

Use session mode for the relay connection. The relay holds PostgreSQL advisory locks for pipeline ownership and uses LISTEN tide_relay_config for hot-reload — both require a persistent session.

1. Dedicate a small pool for the relay

Give the relay its own PgBouncer database entry so it always gets a session-mode connection, even if the main application pool uses transaction mode:

# pgbouncer.ini
[databases]
myapp        = host=127.0.0.1 port=5432 dbname=myapp  pool_mode=transaction
myapp_relay  = host=127.0.0.1 port=5432 dbname=myapp  pool_mode=session

[pgbouncer]
listen_port = 6432
listen_addr = 127.0.0.1
auth_type = scram-sha-256

2. Point the relay at the session pool

pg-tide \
  --postgres-url "postgres://relay_user:pass@127.0.0.1:6432/myapp_relay"

3. Application connections use transaction mode

Your application can still use the standard myapp pool with transaction mode — only the relay needs session mode.

Connection count

The relay opens one persistent PostgreSQL connection per pg-tide process (plus one short-lived connection for the LISTEN/NOTIFY channel). For a typical deployment:

  • 1 relay process → 2 PgBouncer connections → 2 PostgreSQL server connections.
  • 3 relay replicas (HA) → 6 PgBouncer connections → at most 3 active PostgreSQL connections (only the primary lock-holder does real work).

Set max_client_conn and default_pool_size in PgBouncer to accommodate this.

Health check

PgBouncer's server_check_query pings idle connections. pg_tide's relay sends its own heartbeat updates (UPDATE tide.tide_consumer_offsets SET last_heartbeat = now()), so no additional check query is needed.

TLS

If PgBouncer terminates TLS from the relay, ensure the relay's --postgres-url includes sslmode=require:

postgres://relay_user:pass@pgbouncer:6432/myapp_relay?sslmode=require

The relay will negotiate TLS with PgBouncer; PgBouncer can then connect to PostgreSQL using its own TLS configuration (including certificate pinning).

Pgpool-II

Pgpool-II is an alternative pooler with load-balancing capabilities. The same session-mode requirement applies. Route relay connections to the primary node only — the relay must never connect to a read replica because it writes consumer offsets.

Integration: Prometheus + Grafana

This guide covers setting up complete observability for pg_tide using Prometheus for metrics collection and Grafana for visualization and alerting.

Architecture

pg-tide relay (:9090/metrics)  →  Prometheus  →  Grafana
                                      ↓
                               Alertmanager → PagerDuty/Slack

Prometheus Configuration

Static Target

# prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'pg-tide'
    static_configs:
      - targets: ['pg-tide-relay:9090']
        labels:
          environment: 'production'

Kubernetes Service Discovery

scrape_configs:
  - job_name: 'pg-tide'
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_port]
        action: replace
        target_label: __address__
        regex: (.+)
        replacement: ${1}:$1
      - source_labels: [__meta_kubernetes_pod_label_app]
        action: keep
        regex: pg-tide-relay

Prometheus Operator (ServiceMonitor)

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: pg-tide-relay
  labels:
    release: prometheus
spec:
  selector:
    matchLabels:
      app: pg-tide-relay
  endpoints:
    - port: metrics
      interval: 15s
      path: /metrics

Grafana Dashboard

Import the pre-built dashboard from pg-tide/dashboards/relay-health.json:

  1. Grafana → Dashboards → Import
  2. Upload relay-health.json
  3. Select your Prometheus data source

Or provision automatically:

# grafana/provisioning/dashboards/pg-tide.yaml
apiVersion: 1
providers:
  - name: 'pg-tide'
    folder: 'Infrastructure'
    type: file
    options:
      path: /var/lib/grafana/dashboards/pg-tide

Alert Rules

Prometheus Alert Rules

# prometheus/rules/pg-tide.yaml
groups:
  - name: pg-tide
    rules:
      - alert: PgTidePipelineDown
        expr: pg_tide_pipeline_healthy == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Pipeline {{ $labels.pipeline }} circuit breaker is open"
          runbook_url: "https://wiki.example.com/pg-tide/circuit-breaker"

      - alert: PgTideHighErrorRate
        expr: rate(pg_tide_publish_errors_total[5m]) > 0.5
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Pipeline {{ $labels.pipeline }} error rate: {{ $value }}/s"

      - alert: PgTideHighLag
        expr: pg_tide_consumer_lag > 50000
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "Pipeline {{ $labels.pipeline }} backlog: {{ $value }} messages"

      - alert: PgTideLatencyHigh
        expr: histogram_quantile(0.99, rate(pg_tide_delivery_latency_seconds_bucket[5m])) > 10
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Pipeline {{ $labels.pipeline }} P99 latency: {{ $value }}s"

      - alert: PgTideRelayDown
        expr: up{job="pg-tide"} == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "pg-tide relay is not responding to scrapes"

Alertmanager Routing

# alertmanager.yml
route:
  receiver: 'default'
  routes:
    - match:
        severity: critical
      receiver: 'pagerduty'
    - match:
        severity: warning
      receiver: 'slack'

receivers:
  - name: 'slack'
    slack_configs:
      - channel: '#alerts'
        send_resolved: true
  - name: 'pagerduty'
    pagerduty_configs:
      - routing_key: '${PAGERDUTY_KEY}'

Docker Compose (Local Development)

version: '3.8'
services:
  prometheus:
    image: prom/prometheus:latest
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - ./rules:/etc/prometheus/rules
    ports:
      - "9090:9090"

  grafana:
    image: grafana/grafana:latest
    volumes:
      - ./dashboards:/var/lib/grafana/dashboards/pg-tide
      - ./provisioning:/etc/grafana/provisioning
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin

  pg-tide:
    image: pg-tide:latest
    environment:
      - DATABASE_URL=postgres://user:pass@postgres:5432/mydb
    ports:
      - "9091:9090"  # Metrics

Key PromQL Queries

# Overall health
min(pg_tide_pipeline_healthy)

# Total throughput
sum(rate(pg_tide_messages_published_total[5m]))

# Per-pipeline error ratio
rate(pg_tide_publish_errors_total[5m]) / rate(pg_tide_messages_consumed_total[5m])

# Delivery latency percentiles
histogram_quantile(0.5, rate(pg_tide_delivery_latency_seconds_bucket[5m]))
histogram_quantile(0.95, rate(pg_tide_delivery_latency_seconds_bucket[5m]))
histogram_quantile(0.99, rate(pg_tide_delivery_latency_seconds_bucket[5m]))

# Lag trend (positive = growing)
deriv(pg_tide_consumer_lag[5m])

Further Reading

Integration: Terraform

This guide shows how to manage pg_tide infrastructure as code using Terraform. You can provision PostgreSQL extensions, create outboxes/inboxes, and configure relay pipelines declaratively.

Provider Setup

Use the cyrilgdn/postgresql provider for managing PostgreSQL objects:

terraform {
  required_providers {
    postgresql = {
      source  = "cyrilgdn/postgresql"
      version = "~> 1.22"
    }
  }
}

provider "postgresql" {
  host     = var.postgres_host
  port     = var.postgres_port
  database = var.postgres_database
  username = var.postgres_username
  password = var.postgres_password
  sslmode  = "require"
}

Install the Extension

resource "postgresql_extension" "pg_tide" {
  name    = "pg_tide"
  schema  = "tide"
  version = "0.11.0"
}

Create Outboxes and Inboxes

resource "postgresql_function" "create_outbox" {
  depends_on = [postgresql_extension.pg_tide]
  
  name     = "create_order_outbox"
  language = "sql"
  body     = "SELECT tide.outbox_create('order_events');"
  
  lifecycle {
    ignore_changes = [body]
  }
}

For a more maintainable approach, use local-exec provisioners:

resource "null_resource" "outboxes" {
  depends_on = [postgresql_extension.pg_tide]

  for_each = toset(var.outbox_names)

  provisioner "local-exec" {
    command = <<-EOT
      psql "${var.postgres_url}" -c "SELECT tide.outbox_create('${each.value}');"
    EOT
  }
}

variable "outbox_names" {
  type    = list(string)
  default = ["order_events", "user_events", "notification_events"]
}

Configure Relay Pipelines

resource "null_resource" "pipeline_orders_to_kafka" {
  depends_on = [null_resource.outboxes]

  provisioner "local-exec" {
    command = <<-EOT
      psql "${var.postgres_url}" -c "
        SELECT tide.relay_set_outbox_v2(
          jsonb_build_object(
            'name', 'orders-to-kafka',
            'outbox', 'order_events',
            'sink_type', 'kafka',
            'config', '${jsonencode({
              brokers   = var.kafka_brokers
              topic     = "orders"
              wire_format = "debezium"
            })}'::jsonb
          )
        );
      "
    EOT
  }

  triggers = {
    config_hash = sha256(jsonencode({
      sink_type = "kafka"
      brokers   = var.kafka_brokers
      topic     = "orders"
    }))
  }
}

Deploy the Relay (Kubernetes)

resource "kubernetes_deployment" "pg_tide_relay" {
  metadata {
    name      = "pg-tide-relay"
    namespace = var.namespace
  }

  spec {
    replicas = var.relay_replicas

    selector {
      match_labels = {
        app = "pg-tide-relay"
      }
    }

    template {
      metadata {
        labels = {
          app = "pg-tide-relay"
        }
        annotations = {
          "prometheus.io/scrape" = "true"
          "prometheus.io/port"   = "9090"
        }
      }

      spec {
        termination_grace_period_seconds = 60

        container {
          name  = "pg-tide"
          image = "${var.relay_image}:${var.relay_version}"

          args = [
            "--postgres-url", "$(DATABASE_URL)",
            "--relay-group-id", var.relay_group_id,
            "--shutdown-timeout", "45",
          ]

          port {
            container_port = 9090
            name           = "metrics"
          }

          env {
            name = "DATABASE_URL"
            value_from {
              secret_key_ref {
                name = kubernetes_secret.pg_tide.metadata[0].name
                key  = "database-url"
              }
            }
          }

          liveness_probe {
            http_get {
              path = "/health"
              port = 9090
            }
            initial_delay_seconds = 10
            period_seconds        = 15
          }

          resources {
            requests = {
              cpu    = "100m"
              memory = "128Mi"
            }
            limits = {
              cpu    = "500m"
              memory = "512Mi"
            }
          }
        }
      }
    }
  }
}

resource "kubernetes_secret" "pg_tide" {
  metadata {
    name      = "pg-tide-secrets"
    namespace = var.namespace
  }

  data = {
    "database-url" = var.postgres_url
  }
}

Variables

variable "postgres_url" {
  type      = string
  sensitive = true
}

variable "kafka_brokers" {
  type    = string
  default = "kafka:9092"
}

variable "relay_replicas" {
  type    = number
  default = 2
}

variable "relay_group_id" {
  type    = string
  default = "production"
}

variable "relay_image" {
  type    = string
  default = "ghcr.io/your-org/pg-tide"
}

variable "relay_version" {
  type    = string
  default = "0.11.0"
}

Further Reading

Migrating to pg_tide

This guide covers migrating from common messaging and CDC solutions to pg_tide. Whether you're moving from Debezium, a custom outbox implementation, application-level message publishing, or another event streaming platform, this guide provides a path.

From Debezium

What Changes

AspectDebeziumpg_tide
CDC mechanismWAL logical replicationTransactional outbox
InfrastructureKafka Connect clusterSingle relay binary
ConfigurationConnector JSON via REST APISQL catalog + relay process
Message formatDebezium JSON/AvroSame (use wire_format = "debezium")
Schema changesAutomatic (WAL captures all)Application explicitly publishes
FilteringSMTs (Single Message Transforms)JMESPath transforms

Migration Steps

  1. Install pg_tide extension:

    CREATE EXTENSION pg_tide;
    
  2. Create outbox for each captured table:

    SELECT tide.outbox_create('orders_cdc');
    
  3. Add triggers or modify application to publish events:

    -- Option A: Trigger (captures all changes automatically)
    CREATE TRIGGER orders_cdc AFTER INSERT OR UPDATE OR DELETE ON orders
    FOR EACH ROW EXECUTE FUNCTION your_cdc_trigger();
    
    -- Option B: Application publishes explicitly (recommended)
    SELECT tide.outbox_publish('orders_cdc', 'orders', your_payload);
    
  4. Configure pipeline with Debezium wire format:

    SELECT tide.relay_set_outbox_v2(
      jsonb_build_object(
        'name', 'orders-cdc',
        'outbox', 'orders_cdc',
        'sink_type', 'kafka',
        'config', '{
          "brokers": "kafka:9092",
          "topic": "dbserver1.public.orders",
          "wire_format": "debezium",
          "wire_config": { "server_name": "dbserver1" }
        }'::jsonb
      )
    );
    
  5. Run in parallel: Deploy pg_tide alongside Debezium, publishing to a separate topic. Compare output.

  6. Switch consumers: Once validated, point consumers to the pg_tide topic.

  7. Decommission Debezium: Remove Kafka Connect connectors.

Key Differences to Communicate to Your Team

  • Consumers see identical Debezium-format messages (no consumer changes needed)
  • Events are now guaranteed to be published if and only if the transaction commits
  • You choose what to publish (vs. Debezium capturing everything)
  • No more "snapshot" mode — data is published at application time

From Custom Outbox Implementations

Many teams have hand-built outbox tables with cron jobs or application-level polling. Migrating to pg_tide replaces the custom infrastructure with a maintained, optimized solution.

Typical Custom Outbox

-- Your existing custom outbox table
CREATE TABLE outbox (
    id BIGSERIAL PRIMARY KEY,
    event_type TEXT,
    payload JSONB,
    published BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMPTZ DEFAULT now()
);

Migration Steps

  1. Create pg_tide outbox:

    SELECT tide.outbox_create('events');
    
  2. Backfill unpublished messages (if needed):

    INSERT INTO tide.outbox_events (stream_table, payload)
    SELECT event_type, payload FROM outbox WHERE published = FALSE;
    
  3. Update application code:

    -- Before: INSERT INTO outbox (event_type, payload) VALUES (...)
    -- After:
    SELECT tide.outbox_publish('events', 'orders', '{"order_id": "..."}'::jsonb);
    
  4. Configure relay pipeline:

    SELECT tide.relay_set_outbox_v2(
      jsonb_build_object(
        'name', 'events-pipeline',
        'outbox', 'events',
        'sink_type', 'your-sink',
        'config', '{
          ...
        }'::jsonb
      )
    );
    
  5. Remove old polling infrastructure: Delete cron jobs, background workers, custom retry logic.

From Direct Message Publishing

If your application publishes directly to Kafka/NATS/RabbitMQ (without an outbox), you have a dual-write problem — the database write and message publish can become inconsistent.

The Dual-Write Problem

BEGIN;
  INSERT INTO orders (...);  -- ✓ succeeds
COMMIT;
publish_to_kafka(...);       -- ✗ fails (network error)
-- Order exists but event was never published!

Migration to Transactional Outbox

BEGIN;
  INSERT INTO orders (...);
  SELECT tide.outbox_publish('order_events', 'orders', ...);
COMMIT;
-- Both succeed or both fail. pg_tide relay handles delivery.

Steps

  1. Install pg_tide and create outbox
  2. Replace direct publish calls with tide.outbox_publish() inside the transaction
  3. Configure relay to deliver to the same broker
  4. Remove direct publishing code and client libraries

From RabbitMQ / ActiveMQ

If you're using a traditional message broker and want to move to pg_tide:

  1. Keep the broker as the transport — pg_tide publishes to RabbitMQ/AMQP
  2. Replace the producer — use transactional outbox instead of direct publish
  3. Consumers stay the same — they still read from the same queues
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-rabbit',
    'outbox', 'order_events',
    'sink_type', 'rabbitmq',
    'config', '{
        "url": "amqp://guest:guest@rabbitmq:5672",
        "exchange": "orders",
        "routing_key": "order.created"
    }'::jsonb
  )
);

Rollback Plan

If you need to roll back the migration:

  1. pg_tide outbox tables remain in your database (no data loss)
  2. Re-enable your previous publishing mechanism
  3. Disable the pg_tide relay pipeline:
    UPDATE tide.relay_outbox_config SET enabled = false WHERE name = 'your-pipeline';
    
  4. The extension can be dropped if no longer needed:
    DROP EXTENSION pg_tide CASCADE;
    

Further Reading

Deployment Architectures

This guide covers proven deployment patterns for pg_tide in production, from simple single-instance setups to globally distributed architectures.

Single Instance

The simplest deployment: one relay process connected to one PostgreSQL database.

┌─────────────┐       ┌────────────┐       ┌──────────┐
│ Application │──────→│ PostgreSQL │──────→│ pg-tide  │──→ Sinks
│  (INSERT)   │       │  (outbox)  │       │ (relay)  │
└─────────────┘       └────────────┘       └──────────┘

When to use: Development, staging, or production whose named operational profile fits on one relay and where simplicity matters more than redundancy.

Pros: Simple to operate, no coordination overhead, easy to debug.

Cons: Single point of failure. If the relay crashes, messages queue in the outbox until it restarts.

Active-Active High Availability

Multiple relay instances share the workload using PostgreSQL advisory locks for coordination.

┌──────────┐     ┌────────────┐     ┌───────────┐
│ pg-tide  │────→│            │     │           │
│ relay #1 │     │            │────→│   Sinks   │
└──────────┘     │ PostgreSQL │     │           │
                 │            │     └───────────┘
┌──────────┐     │            │
│ pg-tide  │────→│            │
│ relay #2 │     └────────────┘
└──────────┘

Each instance acquires advisory locks for pipelines. If instance #1 crashes, instance #2 picks up its pipelines within one discovery interval (default: 30 seconds).

When to use: Production workloads requiring fault tolerance.

Configuration:

# Both instances use the same relay-group-id
pg-tide --relay-group-id "production" --discovery-interval 10

Pros: Automatic failover, no manual intervention, pipelines distributed across instances.

Cons: Slightly more complex to deploy and monitor.

Kubernetes Deployment

The recommended production deployment for most teams. pg_tide runs as a Kubernetes Deployment with multiple replicas.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: pg-tide-relay
spec:
  replicas: 3
  selector:
    matchLabels:
      app: pg-tide-relay
  template:
    metadata:
      labels:
        app: pg-tide-relay
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "9090"
    spec:
      terminationGracePeriodSeconds: 60
      containers:
        - name: pg-tide
          image: ghcr.io/your-org/pg-tide:latest
          args:
            - --postgres-url
            - $(DATABASE_URL)
            - --relay-group-id
            - production
            - --shutdown-timeout
            - "45"
          ports:
            - containerPort: 9090
              name: metrics
          livenessProbe:
            httpGet:
              path: /health
              port: 9090
            initialDelaySeconds: 10
            periodSeconds: 15
          readinessProbe:
            httpGet:
              path: /health
              port: 9090
            initialDelaySeconds: 5
            periodSeconds: 5
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: pg-tide-secrets
                  key: database-url

Key considerations:

  • Set terminationGracePeriodSeconds > shutdown-timeout
  • Use readinessProbe on /health to remove unhealthy pods from service discovery
  • Store secrets in Kubernetes Secrets or external secret managers
  • Use PodDisruptionBudget to prevent all replicas from being evicted simultaneously

Sidecar Pattern

Run pg_tide as a sidecar container alongside your application in the same pod. The relay connects to the same database and handles message delivery.

spec:
  containers:
    - name: app
      image: your-app:latest
    - name: pg-tide
      image: ghcr.io/your-org/pg-tide:latest
      args: ["--postgres-url", "$(DATABASE_URL)"]

When to use: When each service has its own dedicated outbox and you want relay lifecycle tied to the application.

Pros: Simple lifecycle management, dedicated resources per service.

Cons: More total relay instances, each handling fewer pipelines.

Multi-Region

For globally distributed applications, run relay instances in each region connecting to local read replicas or regional databases.

Region US:                    Region EU:
┌──────────┐                  ┌──────────┐
│ pg-tide  │──→ US Sinks      │ pg-tide  │──→ EU Sinks
│ relay    │                  │ relay    │
└──────────┘                  └──────────┘
     │                             │
     ↓                             ↓
┌──────────┐                  ┌──────────┐
│ PG (US)  │ ←── replication ──→ │ PG (EU) │
└──────────┘                  └──────────┘

Key considerations:

  • Use different relay-group-id per region to prevent cross-region lock contention
  • Or use the same group ID with a shared database for automatic geographic failover
  • Consider latency to sinks when choosing relay placement

Further Reading

Independent review

Reviewers other than the primary author must approve the exact candidate commit and artifact digests. The review index records reviewer handle, discipline, scope, date, findings, disposition, and reapproval.

Required perspectives:

  • PostgreSQL extension: SQL, transactions, privileges, SPI, locks, migrations, upgrade, and rollback;
  • Rust async/concurrency: ownership, cancellation, retries, backpressure, shutdown, and races;
  • delivery semantics: acknowledgements, checkpoints, duplicates, HA, and replay;
  • security: ACLs, TLS, SSRF, secrets, dependencies, and disclosure;
  • operations: install, health, metrics, alerts, capacity, runbooks, and rollback.

Re-review is required after changes to a frozen schema or rule, SQL transaction/privilege behavior, checkpoint/retry/HA/shutdown behavior, supported connector acknowledgement or deduplication, security handling, or release artifacts. Documentation typos and evidence clarifications do not invalidate unrelated approvals.

No P0/P1 finding may remain at release. Security details may stay private during coordinated disclosure; the public index records blocker status and disposition without sensitive content.

Partition management

v0.43 keeps one public parent: tide.tide_outbox_messages. Optional children use numeric PARTITION BY RANGE (id) bounds shared by every logical outbox. The old per-outbox created_at layout, stream_table procedures, and pg_partman examples are historical and are not supported.

Inspect storage

SELECT layout, partition_span, premake, last_maintenance_at
FROM tide.outbox_storage_config;

SELECT c.relname AS child, pg_get_expr(c.relpartbound, c.oid) AS bounds,
       pg_size_pretty(pg_total_relation_size(c.oid)) AS total_bytes
FROM pg_inherits i
JOIN pg_class p ON p.oid = i.inhparent
JOIN pg_class c ON c.oid = i.inhrelid
JOIN pg_namespace n ON n.oid = p.relnamespace
WHERE n.nspname = 'tide' AND p.relname = 'tide_outbox_messages'
ORDER BY c.relname;

heap is the default. id_range records the actual ID-range parent. legacy_noncanonical is a fail-closed diagnostic state for old created_at/dedicated-table layouts; do not reinterpret it automatically.

Preflight and conversion

Conversion applies to the complete canonical parent, not one outbox:

SELECT tide.admin_convert_outbox_storage(
  p_partition_span := 10000000,
  p_premake := 2,
  confirm_blocking_copy := TRUE
);

Both maintenance functions require a superuser or membership in the canonical tide_admin group; they are not executable by PUBLIC. Existing pg_tide_admin members retain this authority through the compatibility membership applied by the v0.44 provisioning script.

Run during a maintenance window with publishing and relay workers drained. Preflight must report temporary disk requirements and refuse without explicit confirmation. The operation verifies row count, ID range, and checksum samples, then swaps atomically in one transaction. An error or outer ROLLBACK restores the original heap parent. Zero-downtime conversion is not promised.

The deprecated outbox_convert_to_partitioned(name, strategy, ...) refuses new conversions and points to the global operation.

Provision and recover

Scheduled maintenance uses:

SELECT tide.outbox_maintain_partitions(
  p_ahead := 2,
  p_dry_run := TRUE
);

The helper reads span and premake from outbox_storage_config, creates missing future ranges and indexes idempotently, and drains the default partition in bounded batches. It records created/drained/dropped actions in tide.tide_partition_events. A non-empty default partition is an alert, not a reason to create overlapping bounds. Empty historical children are dropped only after the maintenance fence proves they contain no rows. Rerun the helper after a stopped maintenance job.

Safe removal

A whole child may be detached and dropped only when every row in it is older than that row's logical outbox retention cutoff, at or below that outbox's safe participant offset, and outside active leases. Hold all affected outbox fences in sorted order while proving the predicate. If one outbox is slower, do bounded row cleanup for eligible sibling rows and leave the child attached.

SELECT *
FROM tide.outbox_retention_status
WHERE storage_layout = 'id_range'
ORDER BY outbox_name;

Never manually drop a child based only on consumed_at or a global ID gap.

Query-plan verification

The public polling query is unchanged:

EXPLAIN (FORMAT JSON)
SELECT id, outbox_name, payload, headers, created_at
FROM tide.tide_outbox_messages
WHERE outbox_name = 'orders' AND id > 1000
ORDER BY id
LIMIT 100;

The plan should prune children wholly below the checkpoint and use the (outbox_name, id) index on scanned children. Use JSON-plan assertions rather than exact cost numbers.

Pilot evidence

Pilot evidence must describe the exact release candidate without exposing customer data. Use a stable pseudonymous pilot ID and record the candidate commit, artifact/image digest, PostgreSQL, relay, connector, deployment, and platform versions; topology and workload shape; latency, event/byte counts, resource and storage observations; installation, steady-state, induced failure, restart, upgrade, rollback, duplicate, and operator-diagnosis outcomes; documentation gaps, incidents, linked issues, and operator sign-off.

Do not record payloads, credentials, certificates, customer names, internal hostnames/IPs, account IDs, or raw unsanitized logs. Use public APIs and release artifacts; direct catalog mutation and test-only failpoints do not count.

Required profiles

Complete one record for each:

  • PostgreSQL native outbox to NATS JetStream;
  • PostgreSQL native outbox to Kafka;
  • PostgreSQL native outbox to a remote PostgreSQL inbox;
  • PostgreSQL native outbox to HTTPS webhook.

Include connector-specific outage, acknowledgement, retry, deduplication, TLS/authentication, and rollback observations from the runbook.

Every finding becomes an issue before sign-off with pilot/<profile>, P0-P3 severity, affected contract or non-contract, sanitized reproduction, owner, milestone, and disposition. P0/P1 findings cannot be accepted limitations.

Pre-GA Readiness Checklist

Purpose: Formal acceptance gate for declaring v1.0.0 Production GA.
Complete every item and record the result before cutting the GA tag.


1. TLS Configuration

  • Verify sslmode is set appropriately for your PostgreSQL deployment:
    • Development: sslmode=disable (explicit plaintext override only)
    • Staging/Production: sslmode=require or sslmode=verify-full (required)
  • If using sslmode=require, compile with the named core profile, which includes native-tls.
  • Run pg-tide doctor and confirm: [OK] TLS connection: TLSv1.2 or TLSv1.3.
  • Cloud-managed PostgreSQL services (RDS, Cloud SQL, Azure Database) behind a TLS proxy work without the native-tls feature.

2. Outbox retention and storage

  • Run the named operational profile matching payload size, pipeline count, sink, and PostgreSQL settings; attach its raw JSON result.
  • Reserve disk for the measured retained-row size, WAL, vacuum headroom, and the configured sink-outage window.
  • Verify tide.outbox_retention_status has no unexplained blockers and tide.relay_pipeline_lag is exact and converging.
  • Run tide.outbox_sweep(NULL, 1000, TRUE) and review blockers before scheduling bounded cleanup.
  • If using partitions, verify tide.outbox_storage_config reports id_range, the default partition is empty, and the canonical query prunes old children.

3. Consumer Group Setup

  • Register consumer groups for each pipeline using tide.consumer_group_create().
  • Verify committed offsets advance after test message delivery.
  • Confirm tide.poll_outbox() correctly prunes partitions via WHERE id > $last_offset.
  • For multi-tenant deployments: verify tenant_name is set correctly in relay_outbox_config.

4. DLQ Monitoring Thresholds

  • Set --dlq-warn-threshold (default: 100 per hour) appropriate for your data quality SLA.
  • Confirm tide.relay_dlq has an alert in your monitoring stack for entries older than your max retry window.
  • Test DLQ replay procedure: run pg-tide replay dlq-requeue against a staging deployment.
  • Verify pg_tide_relay_dlq_entries_written_total metric is visible in your Prometheus/Grafana stack.

5. pg-tide doctor Output Interpretation

Run pg-tide doctor --postgres-url $PG_TIDE_POSTGRES_URL and verify all lines are [OK]:

pg-tide doctor v0.25.0
  [OK] Connected to PostgreSQL
  [OK] TLS connection: TLSv1.3
  [OK] Schema 'tide' exists
  [OK] Table tide.tide_outbox_config
  [OK] Table tide.relay_outbox_config
  ...
  [OK] DLQ hourly rate: 0 (threshold: 100)
  [OK] relay_consumer_offsets.last_change_id column present
  [OK] Advisory lock acquisition succeeded
  [OK] LISTEN on tide_relay_config permitted

pg-tide doctor: all checks passed.

Expected warnings (non-blocking):

  • [INFO] Connection is plaintext — acceptable in private-network deployments.

Blocking failures (must resolve before GA):

  • [FAIL] Schema 'tide' not found
  • [FAIL] Table tide.relay_dlq missing
  • [FAIL] LISTEN on tide_relay_config denied

6. Helm Security Context Review

  • runAsNonRoot: true and runAsUser: 1000 are set in the Deployment spec.
  • readOnlyRootFilesystem: true is set (requires /tmp to be a writable emptyDir volume).
  • allowPrivilegeEscalation: false is set.
  • PodDisruptionBudget is configured with minAvailable: 1 for HA deployments.
  • ServiceMonitor is configured and Prometheus is scraping /metrics.

7. Benchmark Baseline Validation

  • Run just bench and confirm no regressions vs the committed baseline.
  • outbox_poll_decode at 1kb batch: baseline < 5ms.
  • inbox_unnest_params at 1000 rows: baseline < 1ms.
  • worker_inner_orchestration at 1000 messages: baseline < 10ms.

If benchmarks regress by more than 10%, investigate before declaring GA.

8. Rollback Procedure

If a v1.0.0 deployment needs to be rolled back to v0.25.0:

  1. Stop the relay: kubectl rollout undo deployment/pg-tide-relay
  2. Verify no schema changes are breaking: pg-tide doctor should pass with the v0.25.0 schema.
  3. If the outbox was converted to partitioned: the old backup table is preserved at
    tide.tide_outbox_messages_backup_{outbox_name} — no rollback SQL needed.
  4. All consumer offsets are preserved: polling resumes from the last committed offset.

Acceptance Sign-off

CategoryStatusNotes
TLS configuration☐
Outbox partitioning☐
Consumer group setup☐
DLQ monitoring☐
pg-tide doctor clean☐
Helm security contexts☐
Benchmark baseline☐
Rollback procedure tested☐

Once all items are checked, cut the v1.0.0 tag.


v1.0.0 GA Acceptance Criteria (from assessment cycle 6)

The following items must be resolved before v1.0.0 GA. Track resolution version in the Resolved in column.

Must-do (P0 blockers)

ItemDescriptionResolved in
Stability contract documenteddocs/src/stability-guarantees.md publishedv0.33.0
KMS envelope encryption foundationADR-010 written, SQL schema added, feature-gated Rust trait skeletonv0.33.0
Positional SQL APIs deprecatedrelay_set_outbox / relay_set_inbox 6/8-param forms emit SQL NOTICEv0.30.0
v0.x → v1.0.0 migration guideComprehensive rolling-upgrade guide with rollback procedurev0.33.0
supply-chain hardeningcargo audit suppress list re-evaluated; all 9 entries confirmed optional-dep onlyv0.33.0
Lifecycle compatibility gateRelay pre-flight rejects extensions outside its supported windowv0.51.0

Should-do (P1 polish)

ItemDescriptionResolved in
Inbox fleet dashboard panelGrafana panel for tide.inbox_status(NULL) added to relay-health.jsonv0.33.0
pg-tide status --inbox-summaryFleet inbox summary in status CLI outputv0.33.0
just check-stability recipeAutomated check that metric names and schema annotations are stablev0.33.0
KMS encryption implementationActual encryption logic for AwsKms, GcpKms, VaultKms, LocalKeyFilev1.0.0
Positional SQL APIs removedDrop the deprecated 6/8-param formsv1.0.0

Release evidence

The release evidence index is the claim-to-proof record for a candidate. It links the frozen contract documents, schemas, fixtures, and checks; generated connector material; sanitized pilot records and linked issues; independent approvals and reapprovals; blocker/severity queries and known P2/P3 limitations; install, upgrade, mixed-version, rollback, regression, security, and operational results; and artifact names, digests, signatures, SBOM, provenance, and release notes.

Each record names the exact candidate commit and artifact versions. Evidence from another candidate is invalid after a material contract or core-path change. Missing evidence, unavailable review, or an unresolved P0/P1 blocks release. Private security records may be referenced by status and owner without publishing sensitive details.

Pending versus ready

Historical release records remain pending until their own evidence is complete. The v0.51.0 index likewise keeps candidate.commit and artifact digests empty until the exact staged candidate artifacts have passed the lifecycle gates; a local run or later commit cannot substitute for that proof.

ready is a separate claim. It requires the exact candidate commit and artifact digests, completed pilot and review records with named identities and UTC dates, a zero blocker query result, and release-manager approval. CI may validate a pending record, but it must never promote one to ready.

Release-manager checklist

Use this checklist for the v0.51.0 candidate and future contract-freeze releases. Record links to the exact commit, artifact digests, and evidence.

Contract and support

  • Frozen surfaces have normative docs and machine-checkable evidence.
  • Compatibility and deprecation changes have review and migration notes.
  • connectors.toml and generated support pages agree on maturity, direction, owners, versions, profiles, and evidence.
  • No preview or experimental row inherits a production promise.
  • Documentation, examples, dashboards, alerts, and runbooks match reality.

Pilots, review, and blockers

  • NATS, Kafka, PostgreSQL inbox, and webhook pilots completed all required scenarios with sanitized evidence.
  • Every pilot finding is a linked issue with pilot/<profile>, P0-P3 severity, owner, and disposition.
  • PostgreSQL, async/concurrency, delivery-semantics, security, and operations reviews independently approved the exact candidate.
  • Material changes received targeted reapproval.
  • The release query proves zero open P0/P1 issues.

Validation and release evidence

  • Fresh install, sequential upgrade, mixed-version window, and rollback checks pass.
  • The lifecycle policy, compatibility matrix, and recovery runbook match the exact candidate artifacts.
  • Security, dependency, connector, schema, observability, and runbook checks pass.
  • Artifact contents match the support matrix.
  • Digests, signatures, SBOM, provenance, and vulnerability results are recorded.
  • Version, extension control files, migration, chart, image, and changelog metadata agree and were updated last.
  • The release evidence index links contracts, pilots, reviews, blockers, regressions, and artifacts.

An unavailable reviewer, missing evidence, or unresolved P0/P1 is a release blocker, not a reason to weaken the claim.

Runbook: Schema Migration

Applies to: pg_tide PostgreSQL extension
Scope: How to upgrade the pg_tide extension schema through v0.51.0.


Overview

pg_tide uses the standard PostgreSQL extension upgrade mechanism:

ALTER EXTENSION pg_tide UPDATE TO '0.51.0';

This command applies the appropriate pg_tide--<from>--<to>.sql upgrade script atomically within a transaction. Stop relays older than v0.50.0 before a floor-to-target upgrade; only the v0.50.0/v0.51.0 rolling window is supported.


Pre-Migration Checklist

Before upgrading:

  1. Back up the database (or ensure your point-in-time recovery is current).
  2. Check the current version:
    SELECT extversion FROM pg_extension WHERE extname = 'pg_tide';
    
  3. Check the available target version:
    SELECT * FROM pg_available_extension_versions WHERE name = 'pg_tide';
    
  4. Run pg-tide doctor to confirm the relay is healthy before the upgrade:
    pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL"
    
  5. Review the CHANGELOG for any breaking changes or required manual steps in the target version.

Upgrade Procedure

1. Deploy the New Extension Files

Copy the new .so library, control file, and SQL migration files to the PostgreSQL $libdir and share directory. For package-based installs:

# Debian/Ubuntu:
apt-get install pg-tide=0.51.0

# CNPG (CloudNativePG) — update the cluster manifest image tag:
kubectl patch cluster my-pg --type=merge \
  -p '{"spec":{"imageName":"ghcr.io/my-org/pg-tide-cnpg:0.51.0"}}'

2. Apply the Migration

-- Connect as a superuser or the extension owner:
ALTER EXTENSION pg_tide UPDATE;

-- Verify:
SELECT extversion FROM pg_extension WHERE extname = 'pg_tide';

Stop pre-v0.50.0 relays before the update. The upgrade is transactional, but the v0.48.0 → v0.49.0 migration can remove unsupported objects after its fail-closed preflight, so do not treat every step as a brief metadata change.

3. Verify Catalog Integrity

-- Confirm all expected functions are present:
SELECT routine_name, routine_type
FROM   information_schema.routines
WHERE  routine_schema = 'tide'
ORDER  BY routine_name;

-- Confirm relay config tables are intact:
SELECT COUNT(*) FROM tide.relay_outbox_config;
SELECT COUNT(*) FROM tide.relay_inbox_config;

4. Run pg-tide doctor Again

pg-tide doctor --postgres-url "$PG_TIDE_POSTGRES_URL"

All checks should pass. If any check fails, see the troubleshooting section below.


Rolling Back

If the migration must be rolled back:

-- The v0.50.0 -> v0.51.0 boundary is restore/PITR-only after commit.
-- Restore from backup or use PITR to the pre-upgrade snapshot.

Only migrations explicitly marked reversible in the v0.51.0 lifecycle policy have a supported reverse script. Always take a full backup before upgrading; the v0.50.0 → v0.51.0 boundary uses restore or PITR after commit.


Relay Behaviour During Migration

  • Stop pre-v0.50.0 relays before the floor-to-target update. Only the bounded v0.50.0/v0.51.0 relay window is supported.
  • The ALTER EXTENSION command is transactional, but lock duration and affected objects depend on the adjacent step. Pause publishing and keep the relay stopped whenever the migration procedure requires it.
  • If the relay encounters a schema error mid-migration (extremely unlikely with the standard upgrade path), it will classify it as a permanent error and pause the affected pipeline. Resume with SELECT tide.relay_enable('...').

Multi-Step Upgrade

For the supported v0.47.0 floor, PostgreSQL applies each packaged adjacent script automatically:

ALTER EXTENSION pg_tide UPDATE TO '0.19.0';

Do not infer support for releases older than v0.47.0 from the presence of historical SQL files; use the documented restore-and-upgrade procedure.


CNPG (CloudNativePG) Notes

When using CloudNativePG, updating the cluster image only makes the target extension artifact available. Run an explicit migration Job on the primary after the target files are available; bootstrap hooks do not update an existing cluster. See examples/cnpg/cluster.yaml for a reference manifest.


See Also

Scaling

Scale from the measured reference profiles in benchmarks/operational/. Payload size, sink acknowledgments, PostgreSQL settings, batch size, and pipeline count determine capacity; the project does not promise a universal throughput number.

Relay instances

Run multiple relays with the same relay_group_id for ownership transfer and HA. Each pipeline has one owner at a time. More instances improve failover and pipeline density, not the throughput of one pipeline. Measure the pipeline-density profile at 1, 10, and 50 pipelines and compare idle RSS, catalog discovery queries, CPU, and offset writes.

One busy pipeline

Increase batch_size and sink in-flight concurrency only after measuring end-to-end p99 latency and PostgreSQL lock/WAL cost. Keep the poll query canonical:

SELECT id, outbox_name, payload, headers, created_at
FROM tide.tide_outbox_messages
WHERE outbox_name = $1 AND id > $2
ORDER BY id
LIMIT $3;

The (outbox_name, id) index is required on the shared parent and every partition child. Verify pruning with EXPLAIN (FORMAT JSON).

Outage and disk planning

Committed rows accumulate while a sink is unavailable. Reserve:

outage disk = application_rate × outage_seconds × measured_bytes_per_retained_row

Relay backoff/rate limiting protects a recovering sink but does not reject application transactions. Use exact lag alerts and application admission control if an outage window must be hard bounded. inline_threshold does not provide a native pending-row cap.

Outbox storage

Heap storage is the default. Choose ID-range partitioning when measured retention, vacuum, index growth, or bounded cleanup requires it. It keeps the single public parent and partitions by global message ID; it does not create a table per outbox. Use the configured span and premake count, and monitor the default partition and child count.

Read replicas and pooling

The relay connects to the primary because it reads and writes checkpoints. Monitoring queries may use a read replica when its lag is acceptable. PgBouncer is suitable for short metadata transactions; ownership sessions must remain dedicated and session-persistent.

Troubleshooting Guide

A comprehensive guide to diagnosing and resolving common pg_tide issues in production.

Quick Diagnostic Checklist

When something isn't working:

  1. Check relay logs — Look for ERROR or WARN messages
  2. Check /health endpoint — Returns 503 if circuit breaker is open
  3. Check exact pipeline lag — query tide.relay_pipeline_lag and the matching relay metric
  4. Check DLQ — SELECT count(*) FROM tide.relay_dlq WHERE resolved_at IS NULL
  5. Check advisory locks — SELECT * FROM pg_locks WHERE locktype = 'advisory'

Messages Not Being Delivered

Symptom: Outbox rows accumulate, nothing reaches the sink

Check 1: Is the relay running?

# Check if the process is alive
ps aux | grep pg-tide

# Check Kubernetes
kubectl get pods -l app=pg-tide-relay

Check 2: Is the pipeline enabled?

SELECT name, enabled FROM tide.relay_outbox_config;

Check 3: Does the relay hold the advisory lock?

SELECT pid, objid 
FROM pg_locks 
WHERE locktype = 'advisory' AND granted = true;

If no locks are held, the relay may have lost its database connection.

Check 4: Is cleanup blocked or the default partition non-empty?

SELECT outbox_name, blockers, safe_offset, default_partition_rows
FROM tide.outbox_retention_status;

Check 5: Is the circuit breaker open?

curl http://localhost:9090/health
# If unhealthy, circuit breaker is open for one or more pipelines

Check 6: Is the sink reachable? Test connectivity from the relay host to the sink (Kafka broker, HTTP endpoint, etc.).

Symptom: Messages delivered but arriving slowly

Check 1: Batch size too small? Small batch sizes (1-10) increase per-message overhead. Try increasing to 100+.

Check 2: Rate limiter configured?

SELECT config->'rate_limit' FROM tide.relay_outbox_config WHERE name = 'your-pipeline';

Check 3: Sink response time? Check pg_tide_delivery_latency_seconds — if high, the sink is slow to acknowledge.

Circuit Breaker Stuck Open

Symptom: Pipeline unhealthy, /health returns 503

The circuit breaker opens after failure_threshold consecutive failures. It won't close until probe requests succeed.

Resolution:

  1. Check sink availability (is the Kafka broker up? Is the webhook endpoint responding?)
  2. Check relay logs for the specific error message
  3. Fix the underlying issue
  4. Wait for half_open_timeout — the circuit will probe automatically
  5. If the probe succeeds, the circuit closes and normal flow resumes

Force-close (nuclear option): Restart the relay. Circuit breaker state is in-memory and resets on restart.

Duplicate Messages at Sink

Symptom: Consumers see the same message multiple times

pg_tide guarantees at-least-once delivery. Duplicates can occur when:

  1. The relay publishes to the sink but crashes before acknowledging
  2. Network partition causes timeout after successful publish
  3. Replay mode reprocesses an already-delivered range

Resolution:

  • Implement idempotent consumers (dedup on outbox_id or dedup_key)
  • Use the inbox on the receiving side for built-in deduplication
  • For Kafka, use enable.idempotence=true on the consumer side

DLQ Entries Accumulating

Symptom: tide.relay_dlq table growing

Diagnose the error pattern:

SELECT error_kind, error_message, count(*)
FROM tide.relay_dlq
WHERE resolved_at IS NULL
GROUP BY error_kind, error_message
ORDER BY count(*) DESC
LIMIT 10;

Common causes:

Error KindTypical CauseFix
decodeMalformed message in outboxFix the producing application
sink_permanentAuth failure, schema mismatchUpdate credentials or schema
inbox_permanentConstraint violationCheck inbox table constraints
max_retries_exceededTransient issue that lasted too longFix sink, then replay

After fixing: Replay the DLQ entries:

SELECT tide.relay_dlq_retry_all('your-pipeline');

Connection Issues

Symptom: "connection refused" or "timeout" in logs

PostgreSQL connection:

# Test from relay host
psql "${DATABASE_URL}" -c "SELECT 1"

Common issues:

  • Connection string wrong (check --postgres-url)
  • PostgreSQL max_connections reached
  • Firewall rules blocking relay → database
  • SSL/TLS certificate issues

Sink connection:

  • Check DNS resolution from relay host
  • Check firewall/security group rules
  • Verify credentials haven't expired
  • Check TLS certificate validity

Symptom: "too many connections" from PostgreSQL

Each active pipeline has a measured connection and worker cost. Use the pipeline-density profile rather than assuming a fixed multiplier.

Resolution:

  • Increase max_connections in PostgreSQL
  • Use PgBouncer in front of PostgreSQL
  • Reduce number of pipelines per relay instance

Transform/Filter Issues

Symptom: Messages being silently dropped

If messages are consumed but never published, a transform filter might be dropping them.

Diagnose:

  1. Check if messages_consumed > messages_published consistently
  2. Check transform configuration:
SELECT config->'transform' FROM tide.relay_outbox_config WHERE name = 'your-pipeline';
  1. Test the filter expression against a sample payload
  2. Temporarily remove the filter to confirm

Symptom: Transform producing unexpected output

Set dry_run: true on the pipeline to see what transforms produce without publishing:

UPDATE tide.relay_outbox_config 
SET config = config || '{"dry_run": true}'::jsonb 
WHERE name = 'your-pipeline';

Check relay logs for the dry-run output, then disable dry-run when satisfied.

Advisory Lock Conflicts

Symptom: Pipeline not being picked up by any relay instance

Check lock ownership:

SELECT l.pid, a.application_name, l.objid
FROM pg_locks l
JOIN pg_stat_activity a ON l.pid = a.pid
WHERE l.locktype = 'advisory';

If a stale connection holds the lock (zombie process), terminate it:

SELECT pg_terminate_backend(<pid>);

Performance Degradation

Symptom: Gradual slowdown over time

Check 1: Table bloat

SELECT relname, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
WHERE relname LIKE 'outbox%' OR relname LIKE 'inbox%';

If n_dead_tup is high, autovacuum may be falling behind. See Maintenance.

Check 2: Index bloat

SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid))
FROM pg_stat_user_indexes
WHERE relname LIKE 'outbox%';

Check 3: Disk pressure High I/O wait indicates the database can't keep up with the workload.

Further Reading

Vulnerability response

Use this procedure for a private report about pg_tide, its extension, relay, release artifacts, or supported production connectors. Keep the report and raw evidence private until the maintainer approves disclosure.

Receive and acknowledge a report

  1. Receive the report through the private channel in SECURITY.md.
  2. Assign a private issue ID and restrict access to the response team.
  3. Acknowledge receipt within two business days.
  4. Record the reporter, affected version, profile, reproduction status, and requested disclosure date without copying credentials or payloads.

Triage the report

  1. Reproduce the report in an isolated environment.
  2. Classify impact as P0, P1, P2, or P3 using SECURITY.md.
  3. Identify affected versions, profiles, trust boundaries, and artifacts.
  4. Record whether the issue can expose secrets, bypass authorization, send an unsafe request, alter delivery state, or compromise an artifact.
  5. Create a remediation issue with an owner, target release, and due date.

P0 and P1 findings block a release. Do not add a production advisory exception.

Contain and fix

  1. Revoke or rotate affected credentials when exposure is possible.
  2. Withdraw affected artifacts when their digest or provenance is suspect.
  3. Preserve source events and checkpoints when delivery state is involved.
  4. Patch the smallest shared control that covers every affected caller.
  5. Add a blocking required test for the reproduced failure.
  6. Re-run the relevant security, lifecycle, and artifact gates from the exact candidate commit.

Close and disclose

  1. Verify the fix against the original report and regression cases.
  2. Record affected versions, fixed versions, severity, and mitigations.
  3. Notify the reporter before public disclosure when contact is available.
  4. Publish a sanitized advisory after the fix and disclosure date are agreed.
  5. Record the outcome without private report details, credentials, or exploit material.

The v0.52.0 rehearsal record is v0.52.0-vulnerability-response.json. Its status remains pending until the security owner approves the exercise.

Security evidence index

The v0.52.0 evidence set binds each security claim to a required result, control path, and candidate-bound release record. Records contain pointers only. Status remains pending until the exact candidate passes every blocking result and receives independent approval.

ThreatRequired resultControl and runbookRelease record
T01privilege-model-prpg-tide-ext/src/outbox.rs, SQL privilege matrixrelease-evidence/v0.52.0-security.json
T02privilege-model-prdocs/src/sql-reference/relay-api.mdrelease-evidence/v0.52.0-security.json
T03secret-canary-prpg-tide-relay/src/secret.rsrelease-evidence/v0.52.0-security.json
T04relay-unit-pr, relay-integration-prpg-tide-relay/src/envelope.rsrelease-evidence/v0.52.0-security.json
T05network-security-core-prpg-tide-relay/src/http_util.rs, webhook runbookrelease-evidence/v0.52.0-security.json
T06network-security-core-prpg-tide-relay/src/http_util.rsrelease-evidence/v0.52.0-security.json
T07network-security-core-pr, network-security-kafka-prTLS and connector runbooksrelease-evidence/v0.52.0-security.json
T08privilege-model-pr, delivery-model-prOffset API and crash-recovery runbookrelease-evidence/v0.52.0-security.json
T09privilege-model-pr, replay-recovery-prDLQ/replay runbookrelease-evidence/v0.52.0-security.json
T10privilege-model-pr, replay-recovery-prpg-tide-relay/src/cmd/replay.rsrelease-evidence/v0.52.0-security.json
T11secret-canary-prConfig/output redaction pathsrelease-evidence/v0.52.0-security.json
T12supply-chain-prscripts/check_supply_chain.py, dependency policyrelease-evidence/v0.52.0-security.json
T13artifact-verification-releaseRelease workflow and release-evidence runbookrelease-evidence/v0.52.0-security.json
T14artifact-policy-prscripts/check_release_artifacts.pyrelease-evidence/v0.52.0-security.json
T15privilege-model-prSQL migration and extension function inventoryrelease-evidence/v0.52.0-security.json
T16privilege-model-prDefiner path inventory and migrationrelease-evidence/v0.52.0-security.json
T17lifecycle-contract-pr, lifecycle-adjacent-prLifecycle policy and relay-upgrade runbookrelease-evidence/v0.52.0-security.json

Release records

The connector registry remains authoritative for the core and core-kafka production boundary. Removed and experimental connectors have no v0.52.0 production claim. Do not copy test output, credentials, private reports, or resolved secrets into release evidence.

PostgreSQL 17 feasibility

Owner: @grove. Assessment environment: Ubuntu latest, Rust stable, cargo-pgrx 0.18.0, and the repository's pinned PostgreSQL 18/pgrx toolchain.

Decision

PostgreSQL 17 is rejected as a v0.41.0 supported target. The repository has no maintained pg17 feature or CI matrix, so there is no evidence for an upgrade from the PostgreSQL 18 support path.

Required gate and current result

CheckRequired command/evidenceResult in v0.41.0
Versioned buildcargo build --workspace --features pg17Blocked: no pg17 feature.
Clippycargo clippy --workspace --features pg17 --all-targets -- -D warningsBlocked by the missing feature.
Extension testscargo pgrx test pg17Blocked: no maintained pg17 pgrx target.
Package/installcargo package; install the extension into PostgreSQL 17Not established.
SQL smokeFresh install, create an outbox/inbox, publish, consumeNot established.
Relay/NATS E2ERun the public outbox-to-NATS workflow against PostgreSQL 17Not established.
CI ownershipMaintain the same compile, package, SQL, and E2E jobs as PostgreSQL 18Absent; adds a second full matrix.

The exact PostgreSQL 18 dependency is the only maintained pgrx/extension test path currently present. A future support proposal must add the complete matrix above and keep the PostgreSQL 18 gate unchanged before changing this decision.

Commands assessed: cargo build --workspace --features pg17, cargo clippy --workspace --features pg17 --all-targets -- -D warnings, cargo pgrx test pg17, cargo package --package pg-tide-relay --locked, fresh extension install plus SQL smoke, and the public public_api_outbox_to_nats_e2e test against PostgreSQL 17. None can be accepted because the pg17 feature and maintained PostgreSQL 17 target do not exist. Adding them would duplicate the full PostgreSQL 18 CI/install/E2E matrix, so the exact blocker is both missing pgrx configuration and unowned CI cost, not a claimed SQL incompatibility.

Connector promotion policy

Promotion extends the production-supported definition and the generated connector release checklist. It does not create a second connector registry.

Before promotion, the connectors.toml row must include a stable ID, direction, owner, security contact, docs, tested service versions, intentional production profile, and configuration boundary. It must declare acknowledgement, retry, ordering, deduplication, TLS, authentication, limits, and shutdown behavior.

Evidence must cover the real protocol boundary, including happy path, failure before and after acknowledgement, restart/recovery, duplicates, authentication, TLS, redaction, metrics, runbook, upgrade, and packaging checks where applicable. Evidence must use the public API and exact release artifact.

Promotion requires independent review of the implementation and security boundary, a release-manager decision, and generated compatibility material that agrees with connectors.toml. A successful compile, unit test, or private anecdote does not promote a connector. Direction is independent: promoting an outbound sink does not promote its source.

Connector release checklist

Generated from connectors.toml. This is a release-review artifact, not a promise that unchecked evidence exists.

PostgreSQL native outbox (postgresql-outbox)

  • Maturity: supported
  • Owner: @grove
  • postgresql-outbox-poll (integration, source): pg-tide-relay/tests/outbox_source_test.rs::test_outbox_poll_returns_pending_messages in test-integration-core

stdout and file diagnostics (diagnostics)

  • Maturity: supported
  • Owner: @grove
  • contract tests: postgres_insert_microbenchmark.rs
  • integration tests: —
  • e2e tests: —
  • failure before publish tests: —
  • failure after publish tests: —
  • restart tests: —
  • duplicate tests: —
  • auth tests: —
  • tls tests: —
  • redaction tests: —
  • metrics evidence: —
  • runbooks: —
  • upgrade tests: —

PostgreSQL inbox (postgresql-inbox)

  • Maturity: supported
  • Owner: @grove
  • postgresql-inbox-round-trip (integration, sink): pg-tide-relay/tests/pg_inbox_sink_test.rs::test_pg_inbox_sink_round_trip in test-integration-relay
  • postgresql-inbox-deduplication (integration, sink): pg-tide-relay/tests/inbox_sink_test.rs::test_inbox_deduplication in test-integration-relay
  • postgresql-inbox-public-api (e2e, sink): pg-tide-relay/tests/public_api_outbox_to_pg_inbox_e2e.rs::public_api_outbox_to_pg_inbox_e2e in public-api-nats-e2e

NATS JetStream outbound (nats-jetstream-sink)

  • Maturity: supported
  • Owner: @grove
  • nats-jetstream-publish-ack (e2e, sink): pg-tide-relay/tests/public_api_outbox_to_nats_e2e.rs::public_api_outbox_to_nats_e2e in public-api-nats-e2e

HTTPS webhook outbound (webhook-sink)

  • Maturity: supported
  • Owner: @grove
  • webhook-http-post (integration, sink): pg-tide-relay/tests/webhook_test.rs::test_webhook_sink_posts_messages in test-integration
  • webhook-public-api (e2e, sink): pg-tide-relay/tests/public_api_outbox_to_webhook_e2e.rs::public_api_outbox_to_webhook_e2e in public-api-nats-e2e

Apache Kafka outbound (kafka-sink)

  • Maturity: supported
  • Owner: @grove
  • kafka-public-api-delivery (e2e, sink): pg-tide-relay/tests/public_api_outbox_to_kafka_e2e.rs::public_api_outbox_to_kafka_e2e in public-api-kafka-e2e

Concept: Consumer Groups

Consumer groups allow multiple independent consumers to process messages from the same outbox, each maintaining its own position. This enables fan-out patterns where a single stream of events is consumed by different services at different speeds, without them interfering with each other.

The Problem

Without consumer groups, a single outbox has a single "cursor" — one position tracking which messages have been delivered. If you want two services to receive the same events (say, an analytics service and a notification service), you'd need to create two separate outboxes and publish events to both.

The Solution

Consumer groups give each consumer its own independent position within the same outbox:

Outbox: order_events
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │10 │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
                    ↑               ↑
          Analytics group      Notifications group
          (position: 4)        (position: 8)

The analytics service processes messages slowly (heavy aggregation), while the notification service processes them quickly. Each advances independently.

Creating Consumer Groups

-- Create an outbox
SELECT tide.outbox_create('order_events');

-- Create consumer groups for different services
SELECT tide.consumer_group_create('order_events', 'analytics');
SELECT tide.consumer_group_create('order_events', 'notifications');
SELECT tide.consumer_group_create('order_events', 'search-indexer');

Configuring Pipelines per Group

Each consumer group gets its own relay pipeline:

-- Analytics: sends to data warehouse (slow, large batches)
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-analytics',
    'outbox', 'order_events',
    'sink_type', 'bigquery',
    'config', '{
        "consumer_group": "analytics",
        "batch_size": 1000,
        "dataset": "raw_events",
        "table": "orders"
    }'::jsonb
  )
);

-- Notifications: sends to Slack (fast, small batches)
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-notifications',
    'outbox', 'order_events',
    'sink_type', 'slack',
    'config', '{
        "consumer_group": "notifications",
        "batch_size": 1,
        "webhook_url": "${env:SLACK_WEBHOOK}"
    }'::jsonb
  )
);

-- Search: sends to Elasticsearch (medium speed)
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-search',
    'outbox', 'order_events',
    'sink_type', 'elasticsearch',
    'config', '{
        "consumer_group": "search-indexer",
        "batch_size": 100,
        "url": "http://elasticsearch:9200",
        "index": "orders"
    }'::jsonb
  )
);

Independent Processing

Each consumer group:

  • Tracks its own position (last delivered outbox ID)
  • Advances at its own pace
  • Has its own circuit breaker state
  • Can have different rate limits and delivery settings
  • Can target different sinks

If one pipeline falls behind, independent consumer groups continue unaffected.

Checking Group Status

-- See position and lag for each consumer group
SELECT * FROM tide.consumer_group_status('order_events');

Returns:

group_namelast_delivered_idpending_count
analytics4,2311,769
notifications5,9982
search-indexer5,500500

Adding a New Consumer Group

When you add a new consumer group, you choose where it starts:

-- Start from the beginning (process all historical events)
SELECT tide.consumer_group_create('order_events', 'new-service', 0);

-- Start from the current position (only future events)
SELECT tide.consumer_group_create('order_events', 'new-service');

Use Cases

  • Fan-out: Same events go to Kafka, Elasticsearch, and a data lake
  • Selective processing: Each group applies different filters/transforms
  • Speed isolation: Fast consumers aren't blocked by slow ones
  • A/B testing: Two groups process the same events with different logic
  • Migration: New consumer group processes alongside old one during transition

Further Reading

Source: Airbyte

The Airbyte source runs Airbyte source connectors (as Docker containers) and delivers extracted records into a pg_tide inbox. This provides access to approximately 400 data sources from the Airbyte connector catalog.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'salesforce-data',
    'inbox', 'crm_inbox',
    'source', 'airbyte',
    'config', '{
        "source_image": "airbyte/source-salesforce:latest",
        "source_config": {
            "client_id": "${env:SF_CLIENT_ID}",
            "client_secret": "${env:SF_CLIENT_SECRET}",
            "refresh_token": "${env:SF_REFRESH_TOKEN}"
        },
        "streams": ["contacts", "opportunities"]
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "airbyte"
source_imagestring—Docker image for the Airbyte source connector
source_configobject{}Connector configuration
streamsarraynullStreams to sync (null = all discovered)
sync_modestring"incremental"Sync mode: "incremental" or "full_refresh"

Further Reading

Source: Azure Event Hubs

The Event Hubs source reads events from Azure Event Hubs and delivers them into a pg_tide inbox.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-eventhubs',
    'inbox', 'incoming_events',
    'source', 'eventhubs',
    'config', '{
        "connection_string": "${env:EVENTHUBS_CONNECTION_STRING}",
        "event_hub_name": "external-events",
        "consumer_group": "$Default",
        "batch_size": 100
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "eventhubs"
connection_stringstring—Event Hubs connection string (Listen permission)
event_hub_namestring—Event Hub name
consumer_groupstring"$Default"Consumer group
batch_sizeint100Events per read batch
starting_positionstring"latest"Start position: "latest", "earliest"

Further Reading

Source: Apache Kafka

The Kafka source consumes messages from Kafka topics and delivers them into a pg_tide inbox. This enables reverse pipelines where events produced by other systems (via Kafka) flow reliably into your PostgreSQL database for processing. The relay acts as a Kafka consumer, managing offsets, partition assignment, and rebalancing automatically.

When to Use This Source

Use the Kafka source when other services produce events to Kafka that your PostgreSQL-based application needs to process, when you want to consume CDC events from Debezium (which publishes to Kafka), or when you want to build a reliable event consumer that processes Kafka messages within database transactions.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'payments-from-kafka',
    'inbox', 'payment_events',
    'source', 'kafka',
    'config', '{
        "brokers": "${env:KAFKA_BROKERS}",
        "topic": "payment-events",
        "group_id": "pg-tide-payments",
        "auto_offset_reset": "earliest",
        "sasl_mechanism": "SCRAM-SHA-256",
        "sasl_username": "${env:KAFKA_USER}",
        "sasl_password": "${env:KAFKA_PASS}",
        "tls_enabled": true
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "kafka"
brokersstring—Kafka broker addresses
topicstring—Topic to consume from
group_idstring—Kafka consumer group ID
auto_offset_resetstring"earliest"Where to start: "earliest" or "latest"
sasl_mechanismstringnullAuth mechanism
sasl_usernamestringnullSASL username
sasl_passwordstringnullSASL password
tls_enabledboolfalseEnable TLS
batch_sizeint100Messages per inbox insert batch

Offset Management

The relay commits Kafka consumer offsets only after messages are successfully written to the inbox. A crash before that commit leaves messages eligible for redelivery; the inbox's durable deduplication makes the retry safe at the database boundary. Kafka retention still bounds recovery.

Wire Format Integration

When consuming Debezium-formatted messages from Kafka, specify the wire format:

{
    "source_type": "kafka",
    "brokers": "localhost:9092",
    "topic": "dbserver1.public.orders",
    "group_id": "pg-tide-cdc",
    "wire_format": "debezium"
}

This decodes Debezium envelope messages and maps them to inbox rows with proper operation type (insert/update/delete), old and new payload, and commit timestamp.

Troubleshooting

  • "Group coordinator not available" — Brokers are unreachable or the cluster is starting up
  • "Topic not found" — Create the topic or check the name spelling
  • Consumer lag growing — Increase batch_size or check if inbox inserts are slow

Further Reading

Source: Amazon Kinesis

The Kinesis source reads records from Amazon Kinesis Data Streams and delivers them into a pg_tide inbox.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-kinesis',
    'inbox', 'incoming_events',
    'source', 'kinesis',
    'config', '{
        "stream_name": "external-events",
        "region": "us-east-1",
        "iterator_type": "LATEST",
        "batch_size": 100
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "kinesis"
stream_namestring—Kinesis stream name
regionstring—AWS region
iterator_typestring"LATEST"Start position: "LATEST", "TRIM_HORIZON", "AT_TIMESTAMP"
batch_sizeint100Records per GetRecords call
access_key_idstringnullAWS credentials
secret_access_keystringnullAWS secret key

Further Reading

Source: MQTT v5

The MQTT source subscribes to MQTT topics and delivers messages into a pg_tide inbox. This is ideal for ingesting IoT telemetry, sensor data, and device events into PostgreSQL for processing and analytics.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'telemetry-from-devices',
    'inbox', 'device_telemetry',
    'source', 'mqtt',
    'config', '{
        "url": "mqtts://${env:MQTT_BROKER}:8883",
        "topic": "devices/+/telemetry",
        "qos": 1,
        "client_id": "pg-tide-ingest-01",
        "username": "${env:MQTT_USER}",
        "password": "${env:MQTT_PASS}",
        "tls_enabled": true
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "mqtt"
urlstring—MQTT broker URL
topicstring—MQTT topic filter (supports + and # wildcards)
qosint1Quality of Service level
client_idstringautoMQTT client ID
usernamestringnullAuth username
passwordstringnullAuth password
tls_enabledboolfalseEnable TLS
clean_startboolfalseClean session on connect

Delivery Guarantees

With QoS 1, the MQTT broker guarantees at-least-once delivery to the relay. The inbox's deduplication handles any duplicates that arrive. With clean_start: false, the broker retains subscriptions and queues messages while the relay is offline.

Further Reading

Source: NATS JetStream

The NATS source subscribes to NATS JetStream subjects and delivers messages into a pg_tide inbox. This enables reverse pipelines where events from NATS-connected services flow reliably into your PostgreSQL database.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-nats',
    'inbox', 'incoming_events',
    'source', 'nats',
    'config', '{
        "url": "tls://nats.example:4222",
        "subject": "events.>",
        "durable_name": "pg-tide-consumer",
        "stream": "EVENTS",
        "ack_wait_secs": 30
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "nats"
urlstring—NATS server URL
subjectstring—Subject filter (supports wildcards: *, >)
durable_namestring—Durable consumer name for offset tracking
streamstringnullJetStream stream name
ack_wait_secsint30Seconds before unacknowledged messages are redelivered
credentials_filestringnullNATS credentials file
batch_sizeint100Messages per inbox insert batch

Delivery Guarantees

The NATS source acknowledges messages only after they are written to the inbox. JetStream's durable consumer retains unacknowledged messages subject to stream retention, and the inbox's deduplication mechanism (using the stable message identity) makes redelivery safe at the database boundary.

Troubleshooting

  • "Consumer not found" — Create the consumer or ensure the stream and subject match
  • "No messages" — Verify the subject filter matches what publishers are sending to
  • High redelivery count — The relay may be slow to acknowledge; increase ack_wait_secs

Further Reading

Source: PostgreSQL Outbox

The PostgreSQL Outbox source is the heart of pg_tide's forward pipeline. It polls the outbox table for new messages and feeds them to whichever sink is configured for the pipeline. Unlike the reverse sources (which consume from external systems), the outbox source reads from your own PostgreSQL database — it is the starting point for every forward pipeline.

How It Works

The native outbox source uses a combination of polling and PostgreSQL NOTIFY to detect new messages efficiently:

  1. Notification-driven wake-up — When your application publishes a message with outbox_publish(), PostgreSQL sends a NOTIFY on the tide_outbox_notify channel. The relay, which is LISTENing on this channel, wakes up immediately.
  2. Batch polling — The relay queries tide.tide_outbox_messages by logical outbox_name, fetching up to batch_size messages at a time.
  3. Offset tracking — After the sink confirms delivery, the relay commits the scoped (relay_group_id, pipeline_id, outbox_name) offset.
  4. Retention cleanup — Legacy cleanup remains separate from native per-pipeline delivery state.

This hybrid approach means messages are typically delivered within milliseconds of being published (notification-driven), while the polling fallback ensures no messages are missed even if a notification is lost.

Configuration

The outbox source is implicitly configured when you create a forward pipeline with relay_set_outbox_v2(JSONB):

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-pipeline',
    'outbox', 'orders',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "localhost:9092",
        "topic": "order-events",
        "batch_size": 100,
        "poll_interval_ms": 1000
    }'::jsonb
  )
);

Source-Relevant Parameters

ParameterTypeDefaultDescription
batch_sizeint100Maximum messages fetched per poll cycle
poll_interval_msint1000Fallback polling interval when no NOTIFY is received
visibility_timeout_msint30000How long a batch is "leased" before it can be re-claimed by another relay instance

Consumer Groups

Each forward pipeline uses a consumer group to track its position in the outbox. Multiple pipelines can read from the same outbox independently:

-- Two pipelines reading the same outbox independently
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'to-kafka',
    'outbox', 'orders',
    'sink_type', 'kafka',
    'config', '{ ...}'::jsonb
  )
);
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'to-s3',
    'outbox', 'orders',
    'sink_type', 'object_storage',
    'config', '{ ...}'::jsonb
  )
);

Each pipeline maintains its own scoped offset, so Kafka delivery and S3 archival proceed independently without affecting each other.

Troubleshooting

  • Messages not flowing — Check that the pipeline is enabled: SELECT tide.relay_get_config('orders-pipeline')
  • High consumer lag — Increase batch_size or add more relay instances (with different relay_group_id)
  • Messages redelivered after relay restart — Normal behavior for uncommitted batches; downstream sinks should be idempotent

Further Reading

Sources Overview

While sinks deliver messages from your PostgreSQL outbox to external systems, sources work in the opposite direction — they consume messages from external systems and deliver them into your PostgreSQL inbox. This is what pg_tide calls a "reverse pipeline." Think of it as an intake funnel: events from the outside world flow through the source, through the relay, and into your inbox table where your application can process them with full transactional guarantees and idempotent deduplication.

The current source surface is intentionally narrow and evidence-based. See the generated connector compatibility matrix for maturity, build profiles, tested versions, and evidence before choosing a source.

Why Use Sources?

The inbox pattern solves the same reliability problem as the outbox, but in reverse. External sources use at-least-once transport; routing them through a pg_tide inbox provides durable deduplication and lets application processing share a transaction with inbox_mark_processed().

How Sources Work

  1. The relay connects to the external system as a consumer/subscriber
  2. Messages are pulled (or pushed) from the external system in batches
  3. Each message is written to the configured pg_tide inbox table
  4. The inbox's deduplication mechanism (UNIQUE constraint on event_id) prevents duplicates
  5. The relay acknowledges the messages to the external system
  6. Your application processes inbox messages at its own pace within database transactions
sequenceDiagram
    participant External as External System
    participant Relay as pg-tide relay
    participant PG as PostgreSQL
    participant App as Application

    External-->>Relay: Pull messages (batch)
    Relay->>PG: INSERT INTO inbox (deduplicated)
    PG-->>Relay: Confirm insert
    Relay->>External: Acknowledge messages
    App->>PG: SELECT from inbox + process + mark_processed
    Note over App,PG: Single transaction

Available Sources

SourceSystemDirection
PostgreSQL OutboxPostgreSQL outbox pollingForward (outbox → sink)
Apache KafkaKafka consumerReverse
NATS JetStreamNATS subscriberReverse
RabbitMQRabbitMQ consumerReverse
Redis StreamsRedis XREADGROUPReverse
Amazon SQSSQS receiverReverse
Amazon KinesisKinesis readerReverse
Google Cloud Pub/SubPub/Sub subscriberReverse
Azure Service BusService Bus receiverReverse
Azure Event HubsEvent Hubs readerReverse
MQTT v5MQTT subscriberReverse
HTTP Webhook ReceiverHTTP serverReverse
Singer / MeltanoSinger tap consumerReverse
AirbyteAirbyte source connectorReverse
stdin / FileStandard inputReverse

Configuring a Reverse Pipeline

Reverse pipelines are configured using tide.relay_set_inbox_v2():

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'payments-from-stripe',
    'inbox', 'payment_events',
    'source', 'webhook',
    'config', '{
        "listen_addr": "0.0.0.0:8080",
        "path": "/webhooks/stripe",
        "signature_scheme": "stripe",
        "signature_secret": "${env:STRIPE_WEBHOOK_SECRET}"
    }'::jsonb
  )
);

Deduplication

Every source implementation extracts or generates a stable event identifier for each message. This ID is used as the inbox's dedup_key, ensuring that repeated delivery is stored once at the inbox boundary. The deduplication mechanism varies by source:

  • Kafka — Partition + offset combination
  • NATS — JetStream sequence number
  • SQS — SQS message ID
  • Webhook — Request-provided idempotency key or generated UUID

Next Steps

Source: Google Cloud Pub/Sub

The Pub/Sub source subscribes to a Google Cloud Pub/Sub subscription and delivers messages into a pg_tide inbox.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-pubsub',
    'inbox', 'incoming_events',
    'source', 'pubsub',
    'config', '{
        "project_id": "${env:GCP_PROJECT_ID}",
        "subscription": "pg-tide-sub",
        "credentials_json": "${file:/etc/gcp/sa.json}",
        "batch_size": 100
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "pubsub"
project_idstring—GCP project ID
subscriptionstring—Pub/Sub subscription name
credentials_jsonstringnullService account JSON
batch_sizeint100Messages per pull
ack_deadline_secsint30Acknowledgment deadline

Delivery Guarantees

Messages are acknowledged only after inbox insertion. The inbox deduplicates using the Pub/Sub message ID. Unacknowledged messages are redelivered after the ack deadline expires.

Further Reading

Source: RabbitMQ

The RabbitMQ source consumes messages from RabbitMQ queues and delivers them into a pg_tide inbox.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-rabbit',
    'inbox', 'incoming_events',
    'source', 'rabbitmq',
    'config', '{
        "url": "amqp://user:pass@rabbitmq:5672/%2f",
        "queue": "pg-tide-events",
        "prefetch_count": 100,
        "auto_ack": false
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "rabbitmq"
urlstring—AMQP connection URL
queuestring—Queue to consume from
prefetch_countint100Messages pre-fetched from broker
auto_ackboolfalseAuto-acknowledge (set false for at-least-once)
tls_enabledboolfalseEnable TLS

Delivery Guarantees

Messages are acknowledged only after successful inbox insertion. The inbox's deduplication uses the RabbitMQ message ID as the event identifier, preventing duplicate processing even on redelivery.

Further Reading

Source: Redis Streams

The Redis source consumes messages from Redis Streams using consumer groups (XREADGROUP) and delivers them into a pg_tide inbox.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-redis',
    'inbox', 'incoming_events',
    'source', 'redis',
    'config', '{
        "url": "redis://localhost:6379",
        "stream_key": "events:orders",
        "group_name": "pg-tide",
        "consumer_name": "relay-01",
        "batch_size": 100
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "redis"
urlstring—Redis connection URL
stream_keystring—Redis stream key to consume from
group_namestring—Consumer group name
consumer_namestring—Consumer name within the group
batch_sizeint100Messages per XREADGROUP call
passwordstringnullRedis password

Delivery Guarantees

Messages are acknowledged (XACK) only after inbox insertion. Unacknowledged messages remain in the pending entries list (PEL) and are reclaimed on relay restart, ensuring no message loss.

Further Reading

Source: Azure Service Bus

The Service Bus source receives messages from Azure Service Bus queues or topic subscriptions and delivers them into a pg_tide inbox.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-servicebus',
    'inbox', 'incoming_events',
    'source', 'servicebus',
    'config', '{
        "connection_string": "${env:SERVICEBUS_CONNECTION_STRING}",
        "queue_or_subscription": "incoming-events",
        "batch_size": 50
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "servicebus"
connection_stringstring—Service Bus connection string (Listen permission)
queue_or_subscriptionstring—Queue name or topic/subscription path
batch_sizeint50Messages per receive batch
max_lock_duration_secsint60Message lock duration

Delivery Guarantees

Messages are completed (acknowledged) only after inbox insertion. The peek-lock mechanism ensures unprocessed messages are redelivered after the lock expires.

Further Reading

Source: Singer / Meltano

The Singer source runs a Singer "tap" (data extractor) and delivers its output records into a pg_tide inbox. This gives you access to approximately 500 data sources from the Meltano Hub ecosystem — SaaS APIs, databases, file formats, and more — all flowing reliably into your PostgreSQL inbox with incremental sync state management.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'hubspot-contacts',
    'inbox', 'crm_events',
    'source', 'singer',
    'config', '{
        "tap_command": "tap-hubspot",
        "tap_config": {
            "api_key": "${env:HUBSPOT_API_KEY}",
            "start_date": "2024-01-01T00:00:00Z"
        },
        "on_schema_change": "log"
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "singer"
tap_commandstring—Singer tap executable
tap_configobject{}Tap configuration
on_schema_changestring"log"Schema drift policy
state_persistencebooltruePersist STATE for incremental syncs
stream_filterarraynullSpecific streams to extract (null = all)

STATE Persistence for Incremental Syncs

Singer taps emit STATE messages containing bookmarks (last sync position). pg_tide persists these in tide.singer_state, enabling incremental syncs — on each run, only new or changed data is extracted.

Further Reading

Source: Amazon SQS

The SQS source receives messages from Amazon SQS queues and delivers them into a pg_tide inbox. It uses long polling for efficient message retrieval and deletes messages from SQS only after successful inbox insertion.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'events-from-sqs',
    'inbox', 'incoming_events',
    'source', 'sqs',
    'config', '{
        "queue_url": "${env:SQS_QUEUE_URL}",
        "region": "us-east-1",
        "wait_time_seconds": 20,
        "visibility_timeout": 60,
        "batch_size": 10
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "sqs"
queue_urlstring—SQS queue URL
regionstring—AWS region
wait_time_secondsint20Long poll wait time (max 20)
visibility_timeoutint60Seconds before unprocessed messages become visible again
batch_sizeint10Messages per ReceiveMessage call (max 10)
access_key_idstringnullAWS credentials (optional, falls back to default chain)
secret_access_keystringnullAWS secret key

Delivery Guarantees

Messages are deleted from SQS only after inbox insertion succeeds. The inbox's deduplication uses the SQS message ID, making Standard-queue redelivery safe at the database boundary. FIFO deduplication is bounded by the queue's configured window; relay transport remains at least once.

Further Reading

Source: stdin / File

The stdin source reads line-delimited JSON from standard input or a file and delivers each line as a message into a pg_tide inbox. This is useful for testing, replay from log files, data migration, and piping output from external commands into your inbox.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'file-import',
    'inbox', 'imported_events',
    'source', 'stdin',
    'config', '{
        "input_file": "/data/events-export.jsonl",
        "batch_size": 1000
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "stdin"
input_filestringnullFile path (null = read from stdin)
batch_sizeint100Lines per inbox insert batch
formatstring"jsonl"Input format: "jsonl" (one JSON per line)

Use Cases

Replaying from a log file

pg-tide --postgres-url "..." < events-backup.jsonl

Piping from another tool

kafka-console-consumer --topic events --from-beginning | pg-tide --postgres-url "..."

Further Reading

Source: HTTP Webhook Receiver

The Webhook Receiver source starts an HTTP server within the relay that accepts incoming webhook POST requests and delivers them into a pg_tide inbox. This turns pg_tide into a webhook endpoint — external services (Stripe, GitHub, Shopify, or any custom service) can push events directly to your relay, which stores them reliably in your PostgreSQL inbox for processing.

When to Use This Source

Use the webhook receiver when external services push events to you via HTTP (payment notifications from Stripe, repository events from GitHub, order updates from Shopify), when you want to decouple webhook reception from processing (accept the webhook immediately, process later within a transaction), or when you need webhook signature verification and idempotent deduplication built in.

Configuration

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'stripe-webhooks',
    'inbox', 'payment_events',
    'source', 'webhook',
    'config', '{
        "listen_addr": "0.0.0.0:8080",
        "path": "/webhooks/stripe",
        "signature_scheme": "stripe",
        "signature_secret": "${env:STRIPE_WEBHOOK_SECRET}",
        "idempotency_header": "Stripe-Idempotency-Key"
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
source_typestring—Must be "webhook"
listen_addrstring"0.0.0.0:8080"Address and port for the HTTP server
pathstring"/"URL path to accept webhooks on
signature_schemestringnullVerification scheme: "hmac-sha256", "github", "stripe", "svix"
signature_secretstringnullSecret key for signature verification
idempotency_headerstringnullHeader containing the dedup key
max_body_sizeint1048576Maximum request body size (bytes)

Signature Verification

The webhook receiver can verify the authenticity of incoming requests using various signature schemes:

  • hmac-sha256 — Standard HMAC-SHA256 signature in a configurable header
  • github — GitHub's X-Hub-Signature-256 header format
  • stripe — Stripe's Stripe-Signature header with timestamp verification
  • svix — Svix webhook signature format

Requests with invalid signatures are rejected with HTTP 401, protecting your inbox from spoofed events.

Response Codes

The webhook receiver responds to senders with:

  • 200 OK — Message accepted and written to inbox
  • 401 Unauthorized — Signature verification failed
  • 409 Conflict — Duplicate message (already in inbox, idempotent success)
  • 413 Payload Too Large — Body exceeds max_body_size
  • 500 Internal Server Error — Database write failed

Troubleshooting

  • "Connection refused" from sender — Check listen_addr port and firewall rules
  • HTTP 401 from all requests — Verify signature_secret matches the sender's configuration
  • Missing events — Check that path matches what the sender is configured to POST to

Further Reading

Bidirectional Sync

Some systems need two-way data flow: events flow out of PostgreSQL to a message broker (forward relay), and events from that same broker flow back into PostgreSQL (reverse relay). pg_tide handles this without any external coordinator — you simply configure both directions as separate pipelines.

When to use bidirectional sync

  • Microservice choreography: Service A writes orders; Service B processes them and writes fulfilments back. Both share the same broker topic but different outboxes and inboxes.
  • Read model synchronisation: Keep an Elasticsearch index or Redis cache updated by streaming writes out of PostgreSQL and projecting them back into a read database via the inbox.
  • Event sourcing with CQRS: The write-side emits domain events to the outbox; the read-side rebuilds its projection from the inbox.

Architecture

┌───────────────────────────────┐
│         PostgreSQL             │
│                               │
│  tide.outbox_messages         │  ──(forward)──►  NATS / Kafka
│                               │
│  tide.<name>_inbox            │  ◄──(reverse)──  NATS / Kafka
└───────────────────────────────┘
          ▲           │
          │   pg-tide relay
          └──────────┘
         (single process, two pipelines)

The relay reads both pipeline configurations from the tide schema on startup. A single pg-tide process can run dozens of forward and reverse pipelines simultaneously — no separate instances are required.

Step-by-step example

1. Set up the outbox and inbox

-- Forward: orders flow out.
SELECT tide.outbox_create('orders');

-- Reverse: fulfilments flow in.
SELECT tide.inbox_create('fulfilments');

2. Configure the relay pipelines

-- Forward pipeline: outbox → NATS subject "orders.events"
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'forward-orders',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', '{"url":"tls://nats.example:4222","subject":"orders.events"}'::jsonb
  )
);

-- Reverse pipeline: NATS subject "fulfilments.events" → inbox
SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'reverse-fulfilments',
    'inbox', 'nats',
    'source', 'fulfilments',
    'config', '{"url":"tls://nats.example:4222","subject":"fulfilments.events"}'::jsonb
  )
);

3. Start the relay

pg-tide --postgres-url "$DATABASE_URL"

Both pipelines start automatically. The relay logs each pipeline direction on startup:

INFO pipeline name=forward-orders  direction=Forward
INFO pipeline name=reverse-fulfilments direction=Reverse

4. Publish an order and receive the fulfilment

-- Application publishes an order:
SELECT tide.outbox_publish(
    'orders',
    '{"order_id": 1001, "item": "widget", "qty": 3}'::jsonb,
    '{}'::jsonb
);

The relay picks this up and publishes it to orders.events. The fulfilment service consumes it, processes it, and publishes to fulfilments.events. The relay's reverse pipeline writes the result into the inbox:

SELECT event_id, source, payload, received_at
FROM tide.fulfilments_inbox
ORDER BY received_at DESC
LIMIT 5;

Preventing loops

Bidirectional sync carries the risk of infinite feedback loops if both sides subscribe to the same topic. Prevent this with:

  1. Separate subjects/topics for each direction (recommended).
  2. Event filtering: check a custom header (e.g. x-source: service-a) in the relay's transform config and drop events originating from self.
  3. Inbox idempotency: the inbox's UNIQUE(event_id) constraint silently ignores messages it has already processed.

Monitoring

Both pipelines emit independent metrics:

MetricLabels
pg_tide_relay_messages_consumed_totalpipeline=forward-orders, direction=forward
pg_tide_relay_messages_published_totalpipeline=forward-orders, direction=forward
pg_tide_relay_messages_consumed_totalpipeline=reverse-fulfilments, direction=reverse
pg_tide_relay_pipeline_healthypipeline=forward-orders / pipeline=reverse-fulfilments

Check consumer lag to verify neither side is falling behind:

SELECT group_name, consumer_id, lag, last_heartbeat
FROM tide.consumer_lag
ORDER BY lag DESC;

Tutorial: Cross-Region Event Replication

This tutorial shows how to replicate events between PostgreSQL instances in different geographic regions using pg_tide. Each region maintains its own outbox and inbox, with NATS (or Kafka) as the cross-region transport.

Architecture

Region US-East                          Region EU-West
┌───────────────────┐                   ┌───────────────────┐
│  PostgreSQL (US)  │                   │  PostgreSQL (EU)  │
│                   │                   │                   │
│  outbox: orders   │──→ pg_tide ──┐    │  inbox: orders    │
│  inbox: orders    │              │    │  outbox: orders   │──→ pg_tide ──┐
└───────────────────┘              │    └───────────────────┘              │
                                   │                                       │
                                   ↓                                       ↓
                            ┌─────────────┐                         ┌─────────────┐
                            │  NATS (US)  │←── NATS Gateway ──────→│  NATS (EU)  │
                            └─────────────┘                         └─────────────┘
                                   ↑                                       ↑
                                   │                                       │
                            pg_tide ──→ inbox (US)                  pg_tide ──→ inbox (EU)

What You'll Build

  • Orders created in US-East are replicated to EU-West within seconds
  • Orders created in EU-West are replicated to US-East
  • Each region can operate independently during network partitions
  • The inbox provides deduplication for messages that arrive during recovery

Step 1: Setup US-East Region

-- US-East PostgreSQL
CREATE EXTENSION pg_tide;
SELECT tide.outbox_create('order_events');
SELECT tide.inbox_create('replicated_orders');

Publish pipeline (US → NATS):

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'us-orders-publish',
    'outbox', 'order_events',
    'sink_type', 'nats',
    'config', '{
        "url": "tls://nats-us:4222",
        "subject_template": "orders.{op}.us-east",
        "stream": "ORDERS"
    }'::jsonb
  )
);

Subscribe pipeline (NATS → US inbox, for EU-originated events):

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'eu-orders-subscribe',
    'inbox', 'replicated_orders',
    'source', 'nats',
    'config', '{
        "url": "tls://nats-us:4222",
        "subject": "orders.*.eu-west",
        "stream": "ORDERS",
        "consumer_group": "us-east-replica",
        "durable_name": "us-east-replica"
    }'::jsonb
  )
);

Step 2: Setup EU-West Region

-- EU-West PostgreSQL
CREATE EXTENSION pg_tide;
SELECT tide.outbox_create('order_events');
SELECT tide.inbox_create('replicated_orders');

Publish pipeline (EU → NATS):

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'eu-orders-publish',
    'outbox', 'order_events',
    'sink_type', 'nats',
    'config', '{
        "url": "tls://nats-eu:4222",
        "subject_template": "orders.{op}.eu-west",
        "stream": "ORDERS"
    }'::jsonb
  )
);

Subscribe pipeline (NATS → EU inbox, for US-originated events):

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'us-orders-subscribe',
    'inbox', 'replicated_orders',
    'source', 'nats',
    'config', '{
        "url": "tls://nats-eu:4222",
        "subject": "orders.*.us-east",
        "stream": "ORDERS",
        "consumer_group": "eu-west-replica",
        "durable_name": "eu-west-replica"
    }'::jsonb
  )
);

Step 3: Configure NATS Gateway

NATS supports multi-region replication via Gateway connections:

# nats-us.conf
gateway {
  name: "us-east"
  listen: "0.0.0.0:7222"
  gateways: [
    { name: "eu-west", urls: ["tls://nats-eu:7222"] }
  ]
}

# nats-eu.conf
gateway {
  name: "eu-west"
  listen: "0.0.0.0:7222"
  gateways: [
    { name: "us-east", urls: ["tls://nats-us:7222"] }
  ]
}

Step 4: Application Usage

In US-East:

BEGIN;
INSERT INTO orders (id, region, customer_id, total)
VALUES ('ORD-US-001', 'us-east', 'CUST-42', 149.99);

SELECT tide.outbox_publish('order_events', 'orders', jsonb_build_object(
    'order_id', 'ORD-US-001',
    'region', 'us-east',
    'customer_id', 'CUST-42',
    'total', 149.99
));
COMMIT;

This event automatically replicates to EU-West via: outbox → NATS (US) → NATS Gateway → NATS (EU) → inbox (EU).

Handling Network Partitions

During a network partition between regions:

  1. Each region continues operating independently (local outbox/inbox works fine)
  2. Cross-region messages queue in the local NATS JetStream
  3. When connectivity restores, NATS gateways resync automatically
  4. The inbox's deduplication prevents double-processing of any message

Conflict Resolution

For bidirectional replication, you need a conflict resolution strategy. Options:

  • Last-writer-wins: Include timestamps, take the latest
  • Region priority: US-East wins ties
  • Merge: Application-specific merge logic in the inbox processor
  • CRDT-style: Use commutative operations (add-only sets, counters)

Further Reading

Tutorial: Loading Data into a Data Lake

This tutorial demonstrates how to stream events from PostgreSQL into a data lake (S3/GCS with Apache Iceberg or Delta Lake format) for analytics. You'll set up a pipeline that continuously loads transactional data into a lakehouse architecture.

What You'll Build

PostgreSQL (transactions)  →  pg_tide  →  Object Storage (S3/GCS)
                                          └── Iceberg/Delta tables
                                              └── Query with Spark/Trino/DuckDB

Prerequisites

  • PostgreSQL with pg_tide installed
  • Object storage (AWS S3, GCS, or MinIO for local testing)
  • A query engine (Trino, Spark, or DuckDB) for reading the lake

Step 1: Create the Outbox

SELECT tide.outbox_create('analytics_events');

Step 2: Configure Iceberg Sink

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'events-to-lake',
    'outbox', 'analytics_events',
    'sink_type', 'iceberg',
    'config', '{
        "catalog_type": "rest",
        "catalog_uri": "http://iceberg-rest:8181",
        "warehouse": "s3://my-lake/warehouse",
        "namespace": "raw",
        "table": "events",
        "s3_endpoint": "https://s3.amazonaws.com",
        "s3_region": "us-east-1",
        "aws_access_key_id": "${env:AWS_ACCESS_KEY_ID}",
        "aws_secret_access_key": "${env:AWS_SECRET_ACCESS_KEY}",
        "partition_by": ["year", "month", "event_type"],
        "commit_interval_seconds": 60
    }'::jsonb
  )
);

Alternative: Delta Lake

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'events-to-delta',
    'outbox', 'analytics_events',
    'sink_type', 'delta',
    'config', '{
        "table_uri": "s3://my-lake/delta/events",
        "partition_columns": ["year", "month"],
        "aws_access_key_id": "${env:AWS_ACCESS_KEY_ID}",
        "aws_secret_access_key": "${env:AWS_SECRET_ACCESS_KEY}",
        "target_file_size_mb": 128
    }'::jsonb
  )
);

Alternative: Raw Object Storage (Parquet)

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'events-to-parquet',
    'outbox', 'analytics_events',
    'sink_type', 'object_storage',
    'config', '{
        "provider": "s3",
        "bucket": "my-lake",
        "prefix": "raw/events/",
        "format": "parquet",
        "partition_template": "year={year}/month={month}/day={day}/",
        "file_rotation_seconds": 300,
        "file_rotation_rows": 100000,
        "aws_access_key_id": "${env:AWS_ACCESS_KEY_ID}",
        "aws_secret_access_key": "${env:AWS_SECRET_ACCESS_KEY}"
    }'::jsonb
  )
);

Step 3: Publish Events

-- Your application publishes events as part of normal transactions
BEGIN;
INSERT INTO orders (id, customer_id, total) VALUES ('ORD-001', 'CUST-42', 299.99);

SELECT tide.outbox_publish('analytics_events', 'orders', jsonb_build_object(
    'event_type', 'order_created',
    'order_id', 'ORD-001',
    'customer_id', 'CUST-42',
    'total', 299.99,
    'year', extract(year from now())::int,
    'month', extract(month from now())::int
));
COMMIT;

Step 4: Start the Relay

pg-tide --postgres-url "postgres://user:pass@localhost/mydb"

Step 5: Query the Lake

With Trino

SELECT event_type, count(*), sum(cast(json_extract_scalar(payload, '$.total') as decimal))
FROM iceberg.raw.events
WHERE year = 2024 AND month = 6
GROUP BY event_type;

With DuckDB

SELECT event_type, count(*), sum(payload->>'total')
FROM read_parquet('s3://my-lake/raw/events/**/*.parquet')
GROUP BY event_type;

Choosing a Lake Format

FormatBest ForEcosystem
IcebergLarge-scale analytics, schema evolutionSpark, Trino, Flink, Snowflake
Delta LakeDatabricks ecosystem, ACID transactionsSpark, Databricks, DuckDB
Parquet filesSimple analytics, maximum compatibilityEverything

Key Considerations

  • Commit interval: Controls how frequently data becomes queryable. 60s gives near-real-time; 300s reduces small file overhead.
  • Partitioning: Partition by time (year/month/day) and optionally by event type for efficient pruning.
  • File size: Target 128-256 MB files for optimal query performance.

Further Reading

Dead-Letter Queue

Even the most reliable systems occasionally encounter messages they cannot process: a malformed payload, a downstream service that is permanently down, or a bug in the consumer. pg_tide's idempotent inbox gives you a first-class dead-letter queue (DLQ) built directly into PostgreSQL — no extra broker configuration required.

How the DLQ works

When a message fails more than max_retries times, tide.inbox_mark_failed() moves it to a separate retention bucket tracked by the dlq_retention_hours column. The message stays visible in the inbox table with processed_at = NULL and a non-empty last_error, making it trivial to query, investigate, and replay.

Normal flow:
  received → pending → mark_processed ──► deleted after processed_retention_hours

Failure flow:
  received → pending → mark_failed (retry_count++)
                            │
                    retry_count > max_retries?
                            │
                           YES
                            ▼
                    last_error set, stays in table
                    until dlq_retention_hours expires

Setting up an inbox with a DLQ

SELECT tide.inbox_create(
    'payments',
    'tide',                -- schema
    3,                     -- max_retries before DLQ
    72,                    -- processed_retention_hours (3 days)
    168                    -- dlq_retention_hours (7 days)
);

With max_retries = 3, the relay will attempt to process each message up to three times. After the third failure, last_error is populated and the message is left in the DLQ section of the inbox.

Viewing DLQ messages

SELECT
    event_id,
    source,
    payload,
    retry_count,
    last_error,
    received_at
FROM tide.payments_inbox
WHERE processed_at IS NULL
  AND retry_count >= 3
ORDER BY received_at;

Replaying failed messages

Once you have fixed the root cause, replay individual events or entire batches:

-- Replay a single event:
SELECT tide.replay_inbox_messages('payments', ARRAY['evt-abc-123']);

-- Replay all DLQ messages at once:
SELECT tide.replay_inbox_messages(
    'payments',
    ARRAY(
        SELECT event_id
        FROM tide.payments_inbox
        WHERE processed_at IS NULL AND retry_count >= 3
    )
);

replay_inbox_messages resets retry_count to 0 and clears last_error, making the events eligible for re-processing on the next relay poll.

Alerting on DLQ depth

Wire the DLQ depth to your alerting stack using a simple SQL query:

-- Prometheus-style metric via pg_stat_statements or a custom exporter:
SELECT
    inbox_name,
    COUNT(*) AS dlq_depth
FROM tide.tide_inbox_config cfg
CROSS JOIN LATERAL (
    SELECT COUNT(*) AS cnt
    FROM tide.tide_inbox_messages msg
    WHERE msg.processed_at IS NULL
      AND msg.retry_count >= cfg.max_retries
) sub
WHERE cnt > 0;

Or, if you use Alertmanager with a Postgres exporter, add a rule:

# prometheus-rules.yaml
groups:
  - name: pg_tide
    rules:
      - alert: InboxDLQNotEmpty
        expr: pg_tide_dlq_depth > 0
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "pg_tide inbox {{ $labels.inbox }} has {{ $value }} dead-lettered messages"

Forwarding DLQ messages to an external queue

For long-term storage or cross-team visibility, you can forward DLQ messages to an external queue (e.g. an S3 bucket or a dedicated Slack alert):

-- Notify via LISTEN/NOTIFY when a message exceeds max_retries:
CREATE OR REPLACE FUNCTION tide.notify_dlq() RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
    IF NEW.retry_count >= (
        SELECT max_retries FROM tide.tide_inbox_config
        WHERE inbox_name = TG_TABLE_NAME::text
    ) THEN
        PERFORM pg_notify(
            'tide_dlq',
            json_build_object(
                'inbox',    TG_TABLE_NAME,
                'event_id', NEW.event_id,
                'error',    NEW.last_error
            )::text
        );
    END IF;
    RETURN NEW;
END;
$$;

The relay's reverse pipeline can listen on tide_dlq and route messages to a dedicated dead-letter topic in NATS or Kafka for out-of-band handling.

Automatic DLQ cleanup

DLQ rows are removed automatically when dlq_retention_hours expires via tide.inbox_truncate_processed(). You can also clean them manually:

-- Remove DLQ rows older than 7 days from the payments inbox:
SELECT tide.inbox_truncate_processed('payments');

Tutorial: Debezium-Compatible CDC Replication

This tutorial shows how to use pg_tide as a Debezium-compatible CDC (Change Data Capture) source. If you're currently using Debezium to capture PostgreSQL changes and publish them to Kafka, pg_tide can replace the Debezium connector while producing identical message formats — giving you transactional outbox guarantees instead of WAL-based CDC.

Why Replace Debezium with pg_tide?

AspectDebeziumpg_tide
MechanismReads WAL (logical replication)Transactional outbox (application-level)
ConsistencyEventually consistent (WAL delay)Transactionally consistent
Schema changesCan miss or break on DDLApplication controls the schema
SelectivityCaptures all row changesApplication chooses what to publish
InfrastructureKafka Connect clusterSingle relay binary
Message formatDebezium JSON/AvroSame (via wire_format = "debezium")

What You'll Build

A pipeline that publishes order changes in Debezium format to Kafka, compatible with existing Debezium consumers.

Step 1: Create the Outbox

CREATE EXTENSION pg_tide;
SELECT tide.outbox_create('cdc_events');

Step 2: Create a Trigger (Optional)

If you want automatic CDC (capture all changes without modifying application code), add a trigger:

CREATE OR REPLACE FUNCTION capture_order_changes() RETURNS trigger AS $$
BEGIN
    IF TG_OP = 'INSERT' THEN
        PERFORM tide.outbox_publish('cdc_events', 'orders', 
            jsonb_build_object(
                'op', 'insert',
                'new_row', row_to_json(NEW)::jsonb,
                'old_row', null
            )
        );
    ELSIF TG_OP = 'UPDATE' THEN
        PERFORM tide.outbox_publish('cdc_events', 'orders',
            jsonb_build_object(
                'op', 'update',
                'new_row', row_to_json(NEW)::jsonb,
                'old_row', row_to_json(OLD)::jsonb
            )
        );
    ELSIF TG_OP = 'DELETE' THEN
        PERFORM tide.outbox_publish('cdc_events', 'orders',
            jsonb_build_object(
                'op', 'delete',
                'new_row', null,
                'old_row', row_to_json(OLD)::jsonb
            )
        );
    END IF;
    RETURN COALESCE(NEW, OLD);
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER orders_cdc
    AFTER INSERT OR UPDATE OR DELETE ON orders
    FOR EACH ROW EXECUTE FUNCTION capture_order_changes();

Step 3: Configure Debezium Wire Format

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'cdc-orders',
    'outbox', 'cdc_events',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "kafka:9092",
        "topic": "dbserver1.public.orders",
        "wire_format": "debezium",
        "wire_config": {
            "server_name": "dbserver1",
            "emit_tombstones": true,
            "key_strategy": "primary_key"
        }
    }'::jsonb
  )
);

The topic name dbserver1.public.orders follows Debezium's naming convention: {server_name}.{schema}.{table}.

Step 4: Start the Relay

pg-tide --postgres-url "postgres://user:pass@localhost/mydb"

Step 5: Verify Consumer Compatibility

Your existing Debezium consumers should work without changes. The messages have the same shape:

{
  "schema": { ... },
  "payload": {
    "before": null,
    "after": {
      "id": 1,
      "customer_id": "CUST-42",
      "total": 149.99,
      "status": "created"
    },
    "op": "c",
    "ts_ms": 1714029482000,
    "source": {
      "version": "pg-tide",
      "connector": "postgresql",
      "name": "dbserver1",
      "ts_ms": 1714029482000,
      "db": "mydb",
      "schema": "public",
      "table": "orders"
    }
  }
}

The only visible difference: source.version says "pg-tide" instead of a Debezium version number.

Migration Strategy

  1. Run in parallel: Deploy pg_tide alongside Debezium, publishing to a test topic
  2. Compare output: Verify messages are compatible with your consumers
  3. Switch consumers: Point consumers to the pg_tide topic
  4. Decommission Debezium: Remove the Debezium connector and Kafka Connect cluster

With Schema Registry (Avro)

For Avro-encoded Debezium messages:

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'cdc-orders-avro',
    'outbox', 'cdc_events',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "kafka:9092",
        "topic": "dbserver1.public.orders",
        "wire_format": "debezium",
        "wire_config": {
            "server_name": "dbserver1",
            "envelope": "avro"
        },
        "schema_registry": {
            "url": "http://schema-registry:8081"
        }
    }'::jsonb
  )
);

Further Reading

Tutorial: End-to-End Pipeline

This tutorial builds a complete bidirectional messaging system: order events flow out from PostgreSQL to Kafka (forward pipeline), and payment confirmations flow in from NATS back into PostgreSQL (reverse pipeline). By the end, you'll have both directions working with at-least-once relay transport and, for the PostgreSQL inbox path, an effectively exactly-once processing outcome through durable deduplication.

This demonstrates a realistic pattern: your order service publishes events when orders are created, and a payment service (running elsewhere) confirms payments by publishing to NATS, which pg_tide relays back into your database for processing.


Prerequisites

  • PostgreSQL 18 with pg_tide installed
  • Kafka cluster running (or Redpanda, which is Kafka-compatible)
  • NATS server running
  • pg-tide relay built with kafka and nats features
  • kafka-console-consumer CLI (comes with Kafka) and nats CLI

Part 1: Forward Pipeline (Orders → Kafka)

Step 1: Set up the database schema

-- Install the extension
CREATE EXTENSION pg_tide;

-- Create a table for our orders
CREATE TABLE orders (
    id          SERIAL PRIMARY KEY,
    customer_id TEXT NOT NULL,
    total       NUMERIC(10,2) NOT NULL,
    status      TEXT NOT NULL DEFAULT 'pending',
    created_at  TIMESTAMPTZ DEFAULT now()
);

-- Create an outbox for order events with 72-hour retention
-- (longer retention gives us time to investigate if something goes wrong)
SELECT tide.outbox_create('orders', p_retention_hours := 72);

-- Create a consumer group for the Kafka relay
-- Using 'earliest' so it processes all existing messages on startup
SELECT tide.create_consumer_group('kafka-relay', 'orders',
  p_auto_offset_reset := 'earliest'
);

Step 2: Configure the Kafka pipeline

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-kafka',
    'outbox', 'orders',
    'sink_type', 'kafka',
    'config', jsonb_build_object(
      'brokers', 'localhost:9092',
      'topic', 'order-events',
      'acks', 'all',            -- wait for all replicas to acknowledge
      'compression', 'snappy',  -- good balance of speed and compression ratio
      'key', '{event_type}'     -- partition by event type for ordering
    ),
    'batch_size', 200
  )
);

Why these choices?

  • acks=all — ensures messages are replicated before the relay considers them delivered. This is the safest option for production.
  • compression=snappy — reduces network bandwidth with minimal CPU overhead. Kafka consumers decompress transparently.
  • key={event_type} — messages with the same event type go to the same Kafka partition, preserving ordering within a type.
  • batch_size=200 — Kafka's efficiency improves with larger batches (amortizes protocol overhead and compression).

Step 3: Start the relay

pg-tide --postgres-url "postgres://user:pass@localhost:5432/mydb"

The relay discovers the orders-to-kafka pipeline, acquires an advisory lock, and begins polling.

Step 4: Publish order events

Simulate a new order being placed:

BEGIN;
  INSERT INTO orders (id, customer_id, total, status)
  VALUES (1, 'alice', 149.99, 'confirmed');

  -- Publish the event atomically with the business data
  SELECT tide.outbox_publish('orders',
    jsonb_build_object(
      'order_id', 1,
      'customer_id', 'alice',
      'total', 149.99,
      'status', 'confirmed',
      'items', jsonb_build_array(
        jsonb_build_object('sku', 'WIDGET-01', 'qty', 2, 'price', 49.99),
        jsonb_build_object('sku', 'GADGET-03', 'qty', 1, 'price', 50.01)
      )
    ),
    jsonb_build_object(
      'event_type', 'order.confirmed',
      'schema_version', '1.0',
      'correlation_id', 'req-abc-123'
    )
  );
COMMIT;

Publish a few more to make the pipeline active:

BEGIN;
  INSERT INTO orders (id, customer_id, total, status) VALUES (2, 'bob', 42.00, 'confirmed');
  SELECT tide.outbox_publish('orders',
    '{"order_id": 2, "customer_id": "bob", "total": 42.00, "status": "confirmed"}'::jsonb,
    '{"event_type": "order.confirmed", "schema_version": "1.0"}'::jsonb);
COMMIT;

BEGIN;
  INSERT INTO orders (id, customer_id, total, status) VALUES (3, 'charlie', 299.95, 'confirmed');
  SELECT tide.outbox_publish('orders',
    '{"order_id": 3, "customer_id": "charlie", "total": 299.95, "status": "confirmed"}'::jsonb,
    '{"event_type": "order.confirmed", "schema_version": "1.0"}'::jsonb);
COMMIT;

Step 5: Verify delivery to Kafka

kafka-console-consumer --bootstrap-server localhost:9092 \
  --topic order-events --from-beginning --max-messages 3

You should see all three order events. Verify from the PostgreSQL side:

-- All messages delivered
SELECT * FROM tide.outbox_pending;
-- Should show 0 pending

-- Consumer lag at zero
SELECT * FROM tide.consumer_lag;
-- Should show lag = 0 for kafka-relay group

Part 2: Reverse Pipeline (Payment Confirmations from NATS → Inbox)

Now let's set up the reverse direction: payment confirmations arrive on a NATS subject and are written to a pg_tide inbox for processing.

Step 6: Create the inbox

-- Create an inbox for payment events
-- max_retries: how many times we'll retry processing before DLQ
-- processed_retention: keep successfully processed messages for 3 days (auditing)
-- dlq_retention: keep failed messages forever (manual investigation)
SELECT tide.inbox_create('payments',
  p_max_retries := 5,
  p_processed_retention_hours := 72,
  p_dlq_retention_hours := 0
);

This creates a table tide."payments_inbox" with a UNIQUE constraint on event_id for deduplication.

Step 7: Configure the reverse pipeline

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'nats-to-payments',
    'inbox', 'payments',
    'source', 'nats',
    'config', jsonb_build_object(
      'url', 'tls://nats.example:4222',
      'subject', 'payments.confirmed',
      'queue_group', 'pg-tide-payments'
    ),
    'batch_size', 50,
    'idempotent', true
  )
);

The relay subscribes to payments.confirmed on NATS and writes incoming messages to the payments inbox. The queue_group ensures that if you run multiple relay instances, each message is processed by only one instance.

Step 8: Simulate incoming payment confirmations

Using the NATS CLI, publish some payment events (as if a payment service were sending them):

nats pub payments.confirmed '{"payment_id": "pay-001", "order_id": 1, "amount": 149.99, "status": "completed", "processor": "stripe"}'

nats pub payments.confirmed '{"payment_id": "pay-002", "order_id": 2, "amount": 42.00, "status": "completed", "processor": "stripe"}'

nats pub payments.confirmed '{"payment_id": "pay-003", "order_id": 3, "amount": 299.95, "status": "completed", "processor": "stripe"}'

Step 9: Verify inbox delivery

-- Check that messages arrived in the inbox
SELECT event_id, payload->>'payment_id' as payment_id,
       payload->>'order_id' as order_id,
       received_at, processed_at
FROM tide."payments_inbox"
ORDER BY id;
 event_id              | payment_id | order_id |       received_at        | processed_at
-----------------------+------------+----------+--------------------------+--------------
 payments:nats:seq-1   | pay-001    | 1        | 2025-01-15 10:05:00+00  |
 payments:nats:seq-2   | pay-002    | 2        | 2025-01-15 10:05:01+00  |
 payments:nats:seq-3   | pay-003    | 3        | 2025-01-15 10:05:02+00  |

Messages are in the inbox, waiting to be processed. Notice the event_id — this is the dedup key that prevents duplicate processing if the same message is delivered twice.

Step 10: Process inbox messages

In your application, you'd read and process these messages:

-- Read pending payments
SELECT id, event_id, payload
FROM tide."payments_inbox"
WHERE processed_at IS NULL
  AND retry_count < 5
ORDER BY id
LIMIT 10;

-- After successfully updating the order status
UPDATE orders SET status = 'paid' WHERE id = 1;
SELECT tide.inbox_mark_processed('payments', 'payments:nats:seq-1');

-- Process the rest
UPDATE orders SET status = 'paid' WHERE id = 2;
SELECT tide.inbox_mark_processed('payments', 'payments:nats:seq-2');

UPDATE orders SET status = 'paid' WHERE id = 3;
SELECT tide.inbox_mark_processed('payments', 'payments:nats:seq-3');

Step 11: Test deduplication

What happens if the same payment confirmation is delivered twice (e.g., the payment service retried)?

# Publish the same payment again
nats pub payments.confirmed '{"payment_id": "pay-001", "order_id": 1, "amount": 149.99, "status": "completed", "processor": "stripe"}'

The inbox's UNIQUE constraint catches the duplicate:

-- Still only one row for pay-001
SELECT count(*) FROM tide."payments_inbox"
WHERE payload->>'payment_id' = 'pay-001';
-- Returns: 1

No double-processing, no duplicate orders marked as paid.


Part 3: Monitoring the Complete System

Check both directions

-- Forward pipeline status: outbox → Kafka
SELECT * FROM tide.outbox_pending;
SELECT * FROM tide.consumer_lag;

-- Reverse pipeline status: NATS → inbox
SELECT
  count(*) FILTER (WHERE processed_at IS NULL AND retry_count < 5) as pending,
  count(*) FILTER (WHERE processed_at IS NOT NULL) as processed,
  count(*) FILTER (WHERE processed_at IS NULL AND retry_count >= 5) as dead_letter
FROM tide."payments_inbox";

Prometheus metrics

curl -s http://localhost:9090/metrics | grep pg_tide

Key metrics to watch:

pg_tide_relay_messages_published_total{pipeline="orders-to-kafka",direction="forward"} 3
pg_tide_relay_messages_consumed_total{pipeline="nats-to-payments",direction="reverse"} 3
pg_tide_relay_pipeline_healthy{pipeline="orders-to-kafka"} 1
pg_tide_relay_pipeline_healthy{pipeline="nats-to-payments"} 1

Part 4: Failure Scenarios

Let's test what happens when things go wrong.

Scenario: Kafka is temporarily down

Stop Kafka, then publish a new order:

BEGIN;
  INSERT INTO orders (id, customer_id, total, status) VALUES (4, 'diana', 75.50, 'confirmed');
  SELECT tide.outbox_publish('orders',
    '{"order_id": 4, "customer_id": "diana", "total": 75.50}'::jsonb,
    '{"event_type": "order.confirmed"}'::jsonb);
COMMIT;

The message is safely in the outbox. The relay will retry delivery with exponential backoff until Kafka recovers. Check the outbox:

SELECT * FROM tide.outbox_pending;
-- Shows 1 pending message

Start Kafka again — the relay delivers the message automatically:

SELECT * FROM tide.outbox_pending;
-- Back to 0 pending

Scenario: Processing an inbox message fails

-- Simulate a processing failure
SELECT tide.inbox_mark_failed('payments', 'payments:nats:seq-4',
  'External API timeout: Stripe returned 504');

The message stays in the inbox with an incremented retry_count. Your application can retry it later. After 5 failures (our max_retries), it's in the dead-letter queue:

-- Check DLQ
SELECT event_id, retry_count, last_error
FROM tide."payments_inbox"
WHERE processed_at IS NULL AND retry_count >= 5;

After fixing the issue, replay the message:

SELECT tide.replay_inbox_messages('payments', ARRAY['payments:nats:seq-4']);

Production Considerations

When adapting this tutorial for production:

  • Use TLS for all connections (PostgreSQL, Kafka, NATS)
  • Use acks=all for Kafka to ensure message durability
  • Set appropriate batch sizes — 200-500 for Kafka, 50-100 for NATS
  • Monitor consumer lag and alert when it exceeds thresholds
  • Run multiple relay instances (same relay_group_id) for HA
  • Use structured JSON logging (--log-format json) for log aggregation
  • Set retention appropriately — longer retention means more disk usage but easier debugging

Next Steps

Tutorial: Fan-out Pattern

Deliver the same outbox events to multiple downstream systems simultaneously. Each system maintains its own consumer group with independent offset tracking.


The Pattern

                    ┌──▶ NATS (real-time notifications)
orders outbox ──▶──┼──▶ Kafka (analytics pipeline)
                    └──▶ Webhook (partner integration)

Each destination gets its own relay pipeline and consumer group, progressing independently.


Step 1: Create the Shared Outbox

SELECT tide.outbox_create('orders', p_retention_hours := 72);

Step 2: Create Consumer Groups

SELECT tide.create_consumer_group('nats-relay', 'orders');
SELECT tide.create_consumer_group('kafka-relay', 'orders');
SELECT tide.create_consumer_group('webhook-relay', 'orders');

Step 3: Configure Pipelines

-- To NATS
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-nats',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', '{"url": "tls://nats:4222", "subject": "orders.events"}'::jsonb
  )
);

-- To Kafka
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-kafka',
    'outbox', 'orders',
    'sink_type', 'kafka',
    'config', '{"brokers": "kafka:9092", "topic": "orders"}'::jsonb
  )
);

-- To partner webhook
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-webhook',
    'outbox', 'orders',
    'sink_type', 'webhook',
    'config', '{"url": "https://partner.example.com/hooks/orders"}'::jsonb
  )
);

Step 4: Monitor Independent Progress

SELECT * FROM tide.consumer_lag;
 group_name    | outbox_name | consumer_id | committed_offset | lag
---------------+-------------+-------------+------------------+-----
 nats-relay    | orders      | relay-0     |             1000 |   0
 kafka-relay   | orders      | relay-0     |              950 |  50
 webhook-relay | orders      | relay-0     |              800 | 200

The webhook relay is behind (maybe the partner endpoint is slow) — but it doesn't affect NATS or Kafka delivery.


Benefits

  • Independent progress — slow consumers don't block fast ones
  • Independent retry — if one sink fails, others continue
  • Single source of truth — all events come from the same outbox
  • No message duplication at the source — publish once, deliver many

Tutorial: Getting Started with pg_tide

This tutorial takes you from zero to a working pg_tide pipeline in 10 minutes. You'll create an outbox, publish events, configure a relay pipeline, and see messages delivered to a sink.

Prerequisites

  • PostgreSQL 18
  • The pg_tide extension installed (CREATE EXTENSION pg_tide)
  • The pg-tide relay binary (see Installation)

Step 1: Install the Extension

CREATE EXTENSION pg_tide;

This creates the tide schema with all catalog tables and SQL functions.

Step 2: Create an Outbox

SELECT tide.outbox_create('my_events');

This creates an outbox table that will store your events until they're relayed.

Step 3: Publish an Event

SELECT tide.outbox_publish('my_events', 'user-signups', '{
    "user_id": "USR-001",
    "email": "alice@example.com",
    "plan": "pro"
}'::jsonb);

The event is now stored in the outbox. It's part of your current transaction — if you ROLLBACK, the event disappears too. That's the transactional outbox guarantee.

Step 4: Check the Outbox

SELECT * FROM tide.outbox_status('my_events');

You'll see one pending event waiting to be relayed.

Step 5: Configure a Relay Pipeline

For this tutorial, we'll use the stdout sink (prints messages to the relay's terminal):

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'my-first-pipeline',
    'outbox', 'my_events',
    'sink_type', 'stdout',
    'config', '{
        "format": "json_pretty"
    }'::jsonb
  )
);

Step 6: Start the Relay

In a terminal:

pg-tide --postgres-url "postgres://user:pass@localhost/mydb"

You should see your event printed to the terminal:

{
  "outbox_id": 1,
  "op": "insert",
  "stream_table": "user-signups",
  "payload": {
    "user_id": "USR-001",
    "email": "alice@example.com",
    "plan": "pro"
  }
}

Step 7: Publish More Events

With the relay running, publish additional events and watch them appear in real-time:

SELECT tide.outbox_publish('my_events', 'user-signups', '{
    "user_id": "USR-002",
    "email": "bob@example.com",
    "plan": "free"
}'::jsonb);

Next Steps

Now that you have a working pipeline, try:

Further Reading

Tutorial: Kafka + Flink Stream Processing

This tutorial shows how to build a real-time analytics pipeline using pg_tide and Apache Flink. You'll publish order events from PostgreSQL to Kafka via pg_tide, then process them with Flink SQL to compute running totals and write results back.

What You'll Build

PostgreSQL (orders)  →  pg_tide  →  Kafka  →  Flink SQL  →  Kafka (results)  →  pg_tide  →  PostgreSQL (analytics)

Prerequisites

  • PostgreSQL 18 with pg_tide extension installed
  • pg-tide relay binary
  • Apache Kafka (or Redpanda)
  • Apache Flink 1.17+ with SQL Gateway

Step 1: Create the Outbox

-- Create an outbox for order events
SELECT tide.outbox_create('order_events');

-- Insert some test events
SELECT tide.outbox_publish('order_events', 'orders', jsonb_build_object(
    'order_id', 'ORD-001',
    'customer_id', 'CUST-42',
    'total', 149.99,
    'region', 'us-east',
    'created_at', now()
));

Step 2: Configure the Pipeline

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-kafka',
    'outbox', 'order_events',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "kafka:9092",
        "topic": "order-events",
        "wire_format": "debezium",
        "wire_config": {
            "server_name": "production"
        }
    }'::jsonb
  )
);

Step 3: Start the Relay

pg-tide --postgres-url "postgres://user:pass@localhost/mydb"

Connect to Flink SQL Gateway and define a source table reading from Kafka:

CREATE TABLE order_events (
    order_id STRING,
    customer_id STRING,
    total DECIMAL(10, 2),
    region STRING,
    created_at TIMESTAMP(3),
    WATERMARK FOR created_at AS created_at - INTERVAL '5' SECOND
) WITH (
    'connector' = 'kafka',
    'topic' = 'order-events',
    'properties.bootstrap.servers' = 'kafka:9092',
    'properties.group.id' = 'flink-analytics',
    'format' = 'debezium-json',
    'scan.startup.mode' = 'earliest-offset'
);

Define the output table:

CREATE TABLE order_analytics (
    window_start TIMESTAMP(3),
    window_end TIMESTAMP(3),
    region STRING,
    order_count BIGINT,
    total_revenue DECIMAL(12, 2)
) WITH (
    'connector' = 'kafka',
    'topic' = 'order-analytics',
    'properties.bootstrap.servers' = 'kafka:9092',
    'format' = 'json'
);

Run the aggregation:

INSERT INTO order_analytics
SELECT 
    window_start,
    window_end,
    region,
    COUNT(*) as order_count,
    SUM(total) as total_revenue
FROM TABLE(
    TUMBLE(TABLE order_events, DESCRIPTOR(created_at), INTERVAL '1' MINUTE)
)
GROUP BY window_start, window_end, region;

Step 5: Ingest Results Back to PostgreSQL

Create an inbox and configure a reverse pipeline to consume Flink's output:

-- Create inbox for analytics results
SELECT tide.inbox_create('analytics_results');

-- Configure pipeline to consume from the results topic
SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'analytics-from-flink',
    'inbox', 'analytics_results',
    'source', 'kafka',
    'config', '{
        "brokers": "kafka:9092",
        "topic": "order-analytics",
        "consumer_group": "pg-tide-analytics",
        "auto_offset_reset": "earliest"
    }'::jsonb
  )
);

Step 6: Query Results

SELECT payload->>'region' as region,
       (payload->>'total_revenue')::decimal as revenue,
       (payload->>'order_count')::int as orders,
       payload->>'window_end' as period
FROM tide.inbox_pending('analytics_results')
ORDER BY period DESC;

Key Takeaways

  • pg_tide's Debezium wire format integrates seamlessly with Flink's debezium-json format
  • The bidirectional flow (outbox → Kafka → Flink → Kafka → inbox) keeps PostgreSQL as the source of truth
  • Flink provides windowed aggregations that would be expensive to compute in PostgreSQL

Further Reading

Tutorial: Notification Fan-Out

This tutorial demonstrates how to fan out events from a single outbox to multiple notification channels simultaneously — Slack for team alerts, PagerDuty for on-call escalation, email via webhook, and a message archive.

What You'll Build

                          ┌──→ Slack (#alerts channel)
                          │
PostgreSQL  →  pg_tide  ──┼──→ PagerDuty (critical only)
(incidents)               │
                          ├──→ Email webhook (all incidents)
                          │
                          └──→ Kafka (archive + analytics)

Step 1: Create the Outbox

CREATE EXTENSION pg_tide;
SELECT tide.outbox_create('incident_events');

Step 2: Application Publishes Events

BEGIN;
INSERT INTO incidents (id, title, severity, team, description)
VALUES ('INC-042', 'Database latency spike', 'critical', 'platform', 'P99 > 5s');

SELECT tide.outbox_publish('incident_events', 'incidents', jsonb_build_object(
    'event_type', 'incident.created',
    'incident_id', 'INC-042',
    'title', 'Database latency spike',
    'severity', 'critical',
    'team', 'platform',
    'description', 'P99 latency exceeded 5s threshold'
));
COMMIT;

Step 3: Configure Multiple Pipelines

Pipeline 1: Slack (all incidents)

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'incidents-to-slack',
    'outbox', 'incident_events',
    'sink_type', 'slack',
    'config', '{
        "webhook_url": "${env:SLACK_ALERTS_WEBHOOK}",
        "channel": "#incidents",
        "transform": {
            "payload": "{ text: join('"'"''"'"', ['"'"'🚨 *'"'"', payload.title, '"'"'* ('"'"', payload.severity, '"'"')\\nTeam: '"'"', payload.team]) }"
        }
    }'::jsonb
  )
);

Pipeline 2: PagerDuty (critical only)

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'incidents-to-pagerduty',
    'outbox', 'incident_events',
    'sink_type', 'pagerduty',
    'config', '{
        "routing_key": "${env:PAGERDUTY_ROUTING_KEY}",
        "transform": {
            "filter": "payload.severity == '"'"'critical'"'"'"
        }
    }'::jsonb
  )
);

Pipeline 3: Email webhook (all incidents)

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'incidents-to-email',
    'outbox', 'incident_events',
    'sink_type', 'webhook',
    'config', '{
        "url": "https://api.sendgrid.com/v3/mail/send",
        "method": "POST",
        "headers": {
            "Authorization": "Bearer ${env:SENDGRID_API_KEY}"
        },
        "transform": {
            "payload": "{ personalizations: [{ to: [{ email: '"'"'oncall@company.com'"'"' }] }], from: { email: '"'"'alerts@company.com'"'"' }, subject: join('"'"''"'"', ['"'"'['"'"', payload.severity, '"'"'] '"'"', payload.title]), content: [{ type: '"'"'text/plain'"'"', value: payload.description }] }"
        }
    }'::jsonb
  )
);

Pipeline 4: Kafka archive (all incidents)

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'incidents-to-archive',
    'outbox', 'incident_events',
    'sink_type', 'kafka',
    'config', '{
        "brokers": "kafka:9092",
        "topic": "incidents-archive",
        "routing": {
            "rules": [
                { "match_field": "severity", "match_value": "critical", "subject": "incidents.critical" },
                { "match_field": "severity", "match_value": "warning", "subject": "incidents.warning" }
            ],
            "default_template": "incidents.info"
        }
    }'::jsonb
  )
);

Step 4: Start the Relay

pg-tide --postgres-url "postgres://user:pass@localhost/mydb"

All four pipelines run independently. A single outbox event fans out to four destinations.

How Fan-Out Works

Each pipeline is independent:

  • They each have their own consumer position (last relayed outbox ID)
  • They process at their own pace
  • If one sink is slow or down, others continue unaffected
  • Each can have different transforms, filters, and routing rules

Rate Limiting Notifications

To avoid notification storms, add rate limiting to chatty channels:

-- Limit Slack to 1 message per second
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'incidents-to-slack',
    'outbox', 'incident_events',
    'sink_type', 'slack',
    'config', '{
        "webhook_url": "${env:SLACK_ALERTS_WEBHOOK}",
        "rate_limit": {
            "enabled": true,
            "max_messages_per_second": 1,
            "burst_size": 5
        }
    }'::jsonb
  )
);

Further Reading

Real-World Scenarios

This page demonstrates pg_tide in realistic business contexts. Each scenario shows a complete architecture with SQL setup, pipeline configuration, and operational guidance — giving you a blueprint for solving similar problems in your own systems.


Scenario 1: E-Commerce Order Pipeline

The situation: You're building an e-commerce platform. When a customer places an order, multiple downstream systems need to know: the warehouse service ships the items, the analytics pipeline tracks revenue, the email service sends a confirmation, and the search index updates product availability.

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                    PostgreSQL (pg_tide)                           │
│                                                                   │
│  orders table ─── outbox_publish() ──▶ "orders" outbox           │
│                                              │                    │
└──────────────────────────────────────────────┼────────────────────┘
                                               │
                              ┌─────────────────┼─────────────────┐
                              │                 │                  │
                              ▼                 ▼                  ▼
                     ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
                     │ NATS        │  │ Kafka       │  │ Webhook     │
                     │ (warehouse) │  │ (analytics) │  │ (email svc) │
                     └─────────────┘  └─────────────┘  └─────────────┘

Setup

-- Create the outbox
SELECT tide.outbox_create('orders', p_retention_hours := 72);

-- Three independent consumer groups — each tracks its own progress
SELECT tide.create_consumer_group('warehouse-relay', 'orders');
SELECT tide.create_consumer_group('analytics-relay', 'orders');
SELECT tide.create_consumer_group('email-relay', 'orders');

-- Three pipelines: same outbox, different destinations
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-warehouse',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', jsonb_build_object(
      'url', 'tls://nats:4222',
      'subject', 'warehouse.orders.{event_type}'
    ),
    'batch_size', 50
  )
);

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-analytics',
    'outbox', 'orders',
    'sink_type', 'kafka',
    'config', jsonb_build_object(
      'brokers', 'kafka:9092',
      'topic', 'order-events',
      'compression', 'zstd'
    ),
    'batch_size', 500
  )
);

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-email',
    'outbox', 'orders',
    'sink_type', 'webhook',
    'config', jsonb_build_object(
      'url', 'https://email-service.internal/hooks/orders',
      'timeout_ms', 5000,
      'headers', '{"Authorization": "Bearer ${ENV:EMAIL_SVC_TOKEN}"}'
    ),
    'batch_size', 10
  )
);

Publishing events throughout the order lifecycle

-- When an order is placed
BEGIN;
  INSERT INTO orders (id, customer_id, total, status)
  VALUES (1001, 'cust-42', 249.99, 'confirmed');

  SELECT tide.outbox_publish('orders',
    jsonb_build_object(
      'order_id', 1001,
      'customer_id', 'cust-42',
      'total', 249.99,
      'items', '[{"sku": "LAPTOP-15", "qty": 1}]'::jsonb,
      'shipping_address', '{"city": "Oslo", "country": "NO"}'::jsonb
    ),
    '{"event_type": "order.confirmed", "schema_version": "2.0"}'::jsonb
  );
COMMIT;

-- When the order ships
BEGIN;
  UPDATE orders SET status = 'shipped' WHERE id = 1001;

  SELECT tide.outbox_publish('orders',
    '{"order_id": 1001, "tracking_number": "NO-123-456", "carrier": "Posten"}'::jsonb,
    '{"event_type": "order.shipped"}'::jsonb
  );
COMMIT;

Why this works well

  • Each downstream system progresses independently — the email service can be slow without blocking the warehouse
  • If the email service goes down, its messages accumulate in the outbox; the warehouse and analytics pipelines are unaffected
  • The analytics pipeline uses large batches for Kafka efficiency
  • The webhook pipeline uses small batches and a short timeout to detect email service issues quickly

Scenario 2: Multi-Tenant SaaS Webhook Delivery

The situation: You're building a B2B SaaS platform where tenants configure webhook endpoints to receive events. Each tenant has different endpoint URLs, different reliability requirements, and different event volumes. You need retry logic, per-tenant isolation, and visibility into delivery status.

Architecture

Each tenant gets their own outbox. This provides:

  • Independent backpressure (one slow tenant doesn't block others)
  • Per-tenant monitoring (consumer lag is per-outbox)
  • Tenant-specific retention policies

Setup

-- Tenant onboarding: create a dedicated outbox
CREATE OR REPLACE FUNCTION provision_tenant_outbox(tenant_id TEXT, webhook_url TEXT)
RETURNS void LANGUAGE plpgsql AS $$
BEGIN
  -- Each tenant gets their own outbox
  PERFORM tide.outbox_create(
    'webhooks-' || tenant_id,
    p_retention_hours := 168  -- 7 days for webhook retry window
  );

  PERFORM tide.create_consumer_group(
    'webhook-delivery-' || tenant_id,
    'webhooks-' || tenant_id
  );

  -- Configure webhook delivery pipeline
  PERFORM tide.relay_set_outbox_v2(
    jsonb_build_object(
      'name', 'deliver-' || tenant_id,
      'outbox', 'webhooks-' || tenant_id,
      'sink_type', 'webhook',
      'config', jsonb_build_object(
        'url', webhook_url,
        'timeout_ms', 10000,
        'retry_codes', '[429, 500, 502, 503, 504]',
        'headers', jsonb_build_object(
          'X-Tenant-ID', tenant_id,
          'X-Webhook-Version', '2024-01-01'
        )
      ),
      'batch_size', 1  -- Deliver webhooks one at a time for ordering
    )
  );
END;
$$;

-- Provision a few tenants
SELECT provision_tenant_outbox('acme-corp', 'https://hooks.acme.com/events');
SELECT provision_tenant_outbox('globex-inc', 'https://api.globex.io/webhooks');

Publishing tenant events

-- Publish an event for a specific tenant
SELECT tide.outbox_publish(
  'webhooks-acme-corp',
  jsonb_build_object(
    'event', 'invoice.paid',
    'data', jsonb_build_object(
      'invoice_id', 'inv-2025-001',
      'amount_cents', 49900,
      'currency', 'USD'
    ),
    'timestamp', now()
  ),
  '{"event_type": "invoice.paid"}'::jsonb
);

Monitoring per-tenant delivery

-- Which tenants have delivery lag?
SELECT
  outbox_name,
  pending_count,
  oldest_at,
  now() - oldest_at AS oldest_age
FROM tide.outbox_pending
WHERE outbox_name LIKE 'webhooks-%'
  AND pending_count > 0
ORDER BY pending_count DESC;

Scenario 3: Event-Driven Data Warehouse Loading

The situation: Your operational database (PostgreSQL) processes transactions throughout the day, and your analytics team needs those changes loaded into a data warehouse (Snowflake, BigQuery, or a PostgreSQL analytics replica). Instead of batch ETL jobs that run once an hour, you want near-real-time streaming of changes.

Architecture

┌─────────────────┐         ┌──────────┐         ┌─────────────────┐
│  App Database   │         │ pg-tide  │         │  Data Warehouse │
│  (PostgreSQL)   │────────▶│  relay   │────────▶│  (staging area) │
│                 │  outbox  │         │  Kafka   │                 │
└─────────────────┘         └──────────┘         └────────┬────────┘
                                                           │
                                                    ┌──────▼──────┐
                                                    │  dbt / ETL  │
                                                    │  transforms │
                                                    └─────────────┘

Setup

-- Outbox for dimension table changes
SELECT tide.outbox_create('dim-changes', p_retention_hours := 168);
SELECT tide.create_consumer_group('warehouse-loader', 'dim-changes');

-- Pipeline to Kafka (where Kafka Connect or a custom consumer loads into the warehouse)
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'dims-to-kafka',
    'outbox', 'dim-changes',
    'sink_type', 'kafka',
    'config', jsonb_build_object(
      'brokers', 'kafka:9092',
      'topic', 'warehouse.dim-changes',
      'compression', 'zstd',
      'key', '{event_type}'  -- partition by entity type for parallel loading
    ),
    'batch_size', 500
  )
);

Trigger-based publishing

For tables where every change should be captured:

-- Automatically publish changes to the customers dimension
CREATE OR REPLACE FUNCTION publish_customer_change()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
  PERFORM tide.outbox_publish('dim-changes',
    jsonb_build_object(
      'entity', 'customer',
      'operation', TG_OP,
      'data', row_to_json(NEW)::jsonb,
      'changed_at', now()
    ),
    jsonb_build_object(
      'event_type', 'customer.' || lower(TG_OP),
      'table', TG_TABLE_NAME
    )
  );
  RETURN NEW;
END;
$$;

CREATE TRIGGER capture_customer_changes
  AFTER INSERT OR UPDATE ON customers
  FOR EACH ROW EXECUTE FUNCTION publish_customer_change();

Why this works

  • Changes stream in near-real-time (seconds, not hours)
  • The outbox provides a reliable buffer if the warehouse is temporarily unavailable
  • Kafka provides durable, replayable storage for the warehouse loader
  • The trigger captures changes automatically without modifying application code
  • You control exactly what gets published (unlike CDC which captures raw row changes)

Scenario 4: Microservice Choreography (Saga Pattern)

The situation: You're processing an order that requires coordination across multiple services: reserve inventory, charge payment, schedule shipping. Rather than a central orchestrator, you want each service to react to events and publish its own events — choreography style.

Architecture

Each service has its own database with pg_tide. Events flow through NATS:

Order Service                    Inventory Service              Payment Service
┌───────────┐                    ┌───────────┐                 ┌───────────┐
│ outbox:   │──▶ NATS ──▶       │ inbox:    │                 │ inbox:    │
│ "orders"  │  order.confirmed   │ "inv-req" │                 │ "pay-req" │
└───────────┘                    └─────┬─────┘                 └─────┬─────┘
                                       │                             │
┌───────────┐                    ┌─────▼─────┐                 ┌─────▼─────┐
│ inbox:    │◀── NATS ◀──       │ outbox:   │                 │ outbox:   │
│ "results" │  *.completed       │ "inv-out" │                 │ "pay-out" │
└───────────┘                    └───────────┘                 └───────────┘

Order service setup

-- Outbox: publishes order events
SELECT tide.outbox_create('orders', p_retention_hours := 168);
SELECT tide.create_consumer_group('nats-fanout', 'orders');
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-fanout',
    'outbox', 'orders',
    'sink_type', 'nats',
    'config', jsonb_build_object(
      'url', 'tls://nats:4222',
      'subject', 'orders.{event_type}'
    )
  )
);

-- Inbox: receives completion/failure events from other services
SELECT tide.inbox_create('order-results',
  p_max_retries := 10,
  p_processed_retention_hours := 168
);
SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'results-from-services',
    'inbox', 'order-results',
    'source', 'nats',
    'config', jsonb_build_object(
      'url', 'tls://nats:4222',
      'subject', 'orders.*.completed',
      'queue_group', 'order-svc'
    )
  )
);

Inventory service setup

-- Inbox: receives inventory reservation requests
SELECT tide.inbox_create('inventory-requests', p_max_retries := 3);
SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'inv-requests',
    'inbox', 'inventory-requests',
    'source', 'nats',
    'config', jsonb_build_object(
      'url', 'tls://nats:4222',
      'subject', 'orders.order.confirmed',
      'queue_group', 'inventory-svc'
    )
  )
);

-- Outbox: publishes reservation results
SELECT tide.outbox_create('inventory-results', p_retention_hours := 72);
SELECT tide.create_consumer_group('inv-nats', 'inventory-results');
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'inv-results-out',
    'outbox', 'inventory-results',
    'sink_type', 'nats',
    'config', jsonb_build_object(
      'url', 'tls://nats:4222',
      'subject', 'orders.inventory.completed'
    )
  )
);

The flow

  1. Order service publishes order.confirmed → NATS
  2. Inventory service receives it in its inbox, reserves stock, publishes inventory.completed
  3. Payment service receives the original event, charges the card, publishes payment.completed
  4. Order service receives both completion events in its inbox and updates order status

Each step is independently reliable:

  • If the inventory service is down, messages accumulate in its inbox
  • If a payment fails, it's retried up to max_retries times
  • The order service's inbox deduplicates if any message is delivered twice
  • Every service can be independently deployed, scaled, and debugged

Scenario 5: Audit Trail and Compliance Logging

The situation: You need an immutable audit trail of every significant business action for regulatory compliance. The audit log must be tamper-resistant, queryable, and forwarded to long-term archival storage (S3, GCS, or a compliance platform).

Architecture

-- Dedicated outbox for audit events (long retention, never disabled)
SELECT tide.outbox_create('audit-log',
  p_retention_hours := 8760,       -- 365 days local retention
  p_inline_threshold := 1000000    -- very high threshold (never pause auditing)
);

-- Forward to cloud storage via webhook (to an internal archival service)
SELECT tide.create_consumer_group('archive-relay', 'audit-log');
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'audit-to-archive',
    'outbox', 'audit-log',
    'sink_type', 'webhook',
    'config', jsonb_build_object(
      'url', 'https://compliance-archiver.internal/ingest',
      'timeout_ms', 30000,
      'headers', '{"Authorization": "Bearer ${ENV:ARCHIVE_TOKEN}"}'
    ),
    'batch_size', 100
  )
);

-- Also forward to Kafka for real-time compliance monitoring
SELECT tide.create_consumer_group('compliance-kafka', 'audit-log');
SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'audit-to-kafka',
    'outbox', 'audit-log',
    'sink_type', 'kafka',
    'config', jsonb_build_object(
      'brokers', 'kafka:9092',
      'topic', 'compliance.audit-events',
      'acks', 'all'
    ),
    'batch_size', 200
  )
);

Publishing audit events

Create a helper function that standardizes the audit event format:

CREATE OR REPLACE FUNCTION audit_log(
  p_action TEXT,
  p_actor TEXT,
  p_resource_type TEXT,
  p_resource_id TEXT,
  p_details JSONB DEFAULT '{}'
) RETURNS void LANGUAGE plpgsql AS $$
BEGIN
  PERFORM tide.outbox_publish('audit-log',
    jsonb_build_object(
      'action', p_action,
      'actor', p_actor,
      'resource_type', p_resource_type,
      'resource_id', p_resource_id,
      'details', p_details,
      'timestamp', now(),
      'ip_address', inet_client_addr()::text
    ),
    jsonb_build_object(
      'event_type', 'audit.' || p_action,
      'compliance_class', 'SOC2'
    )
  );
END;
$$;

Use it throughout your application:

BEGIN;
  UPDATE users SET email = 'new@example.com' WHERE id = 42;
  SELECT audit_log('user.email_changed', 'admin-jane',
    'user', '42',
    '{"old_email": "old@example.com", "new_email": "new@example.com"}'::jsonb
  );
COMMIT;

BEGIN;
  DELETE FROM api_keys WHERE id = 7;
  SELECT audit_log('api_key.revoked', 'user-42',
    'api_key', '7',
    '{"reason": "compromised"}'::jsonb
  );
COMMIT;

Why this works for compliance

  • Atomicity: Audit events are committed with the action they describe. It's impossible to perform an action without creating an audit record.
  • Immutability: The outbox table is append-only from the application's perspective. Once committed, an audit event cannot be altered.
  • Durability: Messages are replicated to multiple destinations (archive + Kafka). Even if one destination fails, the other captures the event.
  • Queryability: The audit log is a PostgreSQL table — you can run SQL queries for investigation.
  • Tamper detection: Compare the local outbox with the archived copy to detect any discrepancies.

Common Patterns Across Scenarios

Pattern: Use headers for routing

All scenarios use the headers JSONB for metadata that controls routing, filtering, and versioning:

'{"event_type": "order.confirmed", "schema_version": "2.0", "tenant_id": "acme"}'

This keeps the payload clean (business data only) while providing rich metadata for infrastructure decisions.

Pattern: One outbox per bounded context

Rather than one giant outbox for everything, create outboxes aligned with your domain boundaries:

  • orders — order lifecycle events
  • inventory — stock level changes
  • payments — payment processing events
  • audit-log — compliance events

This provides independent backpressure, monitoring, and retention per domain.

Pattern: Multiple consumer groups for fan-out

A single outbox can serve many purposes. Each consumer group tracks its own position independently, so a slow consumer doesn't block fast ones.

Pattern: Structured event schemas

Version your event payloads with a schema_version header. This allows consumers to handle schema evolution gracefully:

SELECT tide.outbox_publish('orders',
  '{"order_id": 1, "total": 99.99, "currency": "USD"}'::jsonb,
  '{"event_type": "order.confirmed", "schema_version": "2.0"}'::jsonb
);

Tutorial: Singer/Meltano ETL Pipelines

This tutorial shows how to use pg_tide with Singer taps and targets to build ETL pipelines. You'll extract data from a SaaS API (HubSpot), load it into PostgreSQL, transform it, and export results to a data warehouse.

What You'll Build

HubSpot API  →  tap-hubspot  →  pg_tide inbox  →  Transform  →  pg_tide outbox  →  target-snowflake

Prerequisites

  • PostgreSQL with pg_tide installed
  • Python 3.8+ (for Singer taps/targets)
  • A HubSpot account with API access (or substitute any Singer tap)

Step 1: Install Singer Tap

pip install tap-hubspot

Step 2: Configure Extraction into pg_tide

CREATE EXTENSION pg_tide;
SELECT tide.inbox_create('hubspot_contacts');

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'hubspot-extraction',
    'inbox', 'hubspot_contacts',
    'source', 'singer',
    'config', '{
        "tap_command": "tap-hubspot",
        "tap_config": {
            "api_key": "${env:HUBSPOT_API_KEY}",
            "start_date": "2024-01-01T00:00:00Z"
        },
        "stream_filter": ["contacts", "companies", "deals"],
        "state_persistence": true
    }'::jsonb
  )
);

Step 3: Start the Relay

export HUBSPOT_API_KEY="your-api-key"
pg-tide --postgres-url "postgres://user:pass@localhost/mydb"

The relay runs the tap, captures its output, and writes records into the inbox. STATE messages are persisted for incremental syncs.

Step 4: Process Inbox Data

Query the inbox to see extracted records:

SELECT id, payload->>'email' as email, payload->>'company' as company
FROM tide.inbox_pending('hubspot_contacts')
WHERE payload->>'stream' = 'contacts'
LIMIT 10;

Process and transform:

-- Create a materialized view for analytics
CREATE MATERIALIZED VIEW contact_summary AS
SELECT 
    payload->>'company' as company,
    count(*) as contact_count,
    max((payload->>'last_activity_date')::date) as last_active
FROM tide.inbox_all('hubspot_contacts')
WHERE payload->>'stream' = 'contacts'
GROUP BY payload->>'company';

-- Mark processed
SELECT tide.inbox_mark_processed('hubspot_contacts', id)
FROM tide.inbox_pending('hubspot_contacts');

Step 5: Export to Data Warehouse

Create an outbox for warehouse loading:

SELECT tide.outbox_create('warehouse_events');

-- Publish transformed data
SELECT tide.outbox_publish('warehouse_events', 'contacts', jsonb_build_object(
    'company', company,
    'contact_count', contact_count,
    'last_active', last_active
))
FROM contact_summary;

Configure Singer target export:

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'to-snowflake',
    'outbox', 'warehouse_events',
    'sink_type', 'singer',
    'config', '{
        "target_command": "target-snowflake",
        "target_config": {
            "account": "${env:SNOWFLAKE_ACCOUNT}",
            "user": "${env:SNOWFLAKE_USER}",
            "password": "${env:SNOWFLAKE_PASSWORD}",
            "database": "ANALYTICS",
            "schema": "RAW"
        }
    }'::jsonb
  )
);

Step 6: Schedule Incremental Syncs

Since pg_tide persists Singer STATE, each run only extracts new/changed records. Schedule periodic syncs with cron or a workflow orchestrator:

# Run every hour - only extracts changes since last run
0 * * * * pg-tide --postgres-url "..." --run-once

Or keep the relay running continuously — it will re-run the tap at configurable intervals.

Available Taps (Examples)

TapData SourceInstall
tap-hubspotHubSpot CRMpip install tap-hubspot
tap-salesforceSalesforcepip install tap-salesforce
tap-stripeStripe paymentspip install tap-stripe
tap-githubGitHub repospip install tap-github
tap-postgresPostgreSQL DBpip install tap-postgres
tap-mysqlMySQL DBpip install tap-mysql
tap-google-analyticsGA4pip install tap-google-analytics
tap-shopifyShopifypip install tap-shopify

Browse 500+ taps at hub.meltano.com.

Further Reading

Tutorial: Microservice Event Bus

This tutorial shows how to use pg_tide as a reliable event bus between microservices. Instead of direct service-to-service HTTP calls (which create tight coupling and cascade failures), services publish events to their local outbox and subscribe to events from other services via inboxes.

Architecture

┌─────────────────┐         ┌──────────────────┐         ┌───────────────────┐
│  Order Service  │         │  Payment Service │         │  Shipping Service │
│                 │         │                  │         │                   │
│  outbox: orders │──┐  ┌──→│  inbox: payments │    ┌──→│  inbox: shipping  │
└─────────────────┘  │  │   └──────────────────┘    │   └───────────────────┘
                     │  │                            │
                     ↓  │                            │
              ┌─────────────┐                        │
              │    NATS     │────────────────────────┘
              │  (or Kafka) │
              └─────────────┘
                     ↑
                     │
┌─────────────────┐  │
│ Inventory Svc   │  │
│                 │  │
│ outbox: stock   │──┘
└─────────────────┘

What You'll Build

  • Order Service publishes order.created, order.cancelled events
  • Payment Service subscribes to order events and processes payments
  • Shipping Service subscribes to order events and initiates fulfillment
  • Each service has its own PostgreSQL database with pg_tide

Step 1: Order Service Setup

-- In the order service's database
CREATE EXTENSION pg_tide;
SELECT tide.outbox_create('order_events');

Application code publishes events within the order transaction:

BEGIN;
INSERT INTO orders (id, customer_id, total, status)
VALUES ('ORD-001', 'CUST-42', 149.99, 'created');

SELECT tide.outbox_publish('order_events', 'orders', jsonb_build_object(
    'event_type', 'order.created',
    'order_id', 'ORD-001',
    'customer_id', 'CUST-42',
    'total', 149.99,
    'items', jsonb_build_array(
        jsonb_build_object('sku', 'WIDGET-A', 'qty', 2),
        jsonb_build_object('sku', 'GADGET-B', 'qty', 1)
    )
));
COMMIT;

Configure the relay to publish to NATS:

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'orders-to-nats',
    'outbox', 'order_events',
    'sink_type', 'nats',
    'config', '{
        "url": "tls://nats:4222",
        "subject_template": "events.orders.{op}"
    }'::jsonb
  )
);

Step 2: Payment Service Setup

-- In the payment service's database
CREATE EXTENSION pg_tide;
SELECT tide.inbox_create('payment_triggers');

Configure an inbox pipeline that subscribes to order events:

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'orders-for-payments',
    'inbox', 'payment_triggers',
    'source', 'nats',
    'config', '{
        "url": "tls://nats:4222",
        "subject": "events.orders.>",
        "consumer_group": "payment-service",
        "durable_name": "payment-service"
    }'::jsonb
  )
);

Process incoming events:

-- Payment service worker queries pending inbox messages
SELECT id, payload
FROM tide.inbox_pending('payment_triggers')
LIMIT 10;

-- After processing, mark as done
SELECT tide.inbox_mark_processed('payment_triggers', 42);

Step 3: Shipping Service Setup

-- In the shipping service's database
CREATE EXTENSION pg_tide;
SELECT tide.inbox_create('shipping_triggers');

SELECT tide.relay_set_inbox_v2(
  jsonb_build_object(
    'name', 'orders-for-shipping',
    'inbox', 'shipping_triggers',
    'source', 'nats',
    'config', '{
        "url": "tls://nats:4222",
        "subject": "events.orders.>",
        "consumer_group": "shipping-service",
        "durable_name": "shipping-service",
        "transform": {
            "filter": "payload.event_type == '"'"'order.created'"'"'"
        }
    }'::jsonb
  )
);

The shipping service only processes order.created events (not cancellations) thanks to the transform filter.

Step 4: Start Relays

Each service runs its own relay instance:

# Order service relay
pg-tide --postgres-url "postgres://user:pass@orders-db/orders"

# Payment service relay
pg-tide --postgres-url "postgres://user:pass@payments-db/payments"

# Shipping service relay
pg-tide --postgres-url "postgres://user:pass@shipping-db/shipping"

Benefits of This Architecture

Loose coupling: Services don't know about each other. The order service publishes events without knowing who consumes them. New consumers can subscribe without changing the producer.

Reliability: The transactional outbox guarantees events are published if and only if the business transaction commits. No dual-write problems.

Independent scaling: Each service scales independently. The payment service can process events at its own pace without affecting the order service.

Resilience: If the payment service is down, events queue in NATS (with durable consumers) and are delivered when it recovers. No lost events, no cascading failures.

Further Reading

Wire Format: Canal

The Canal wire format decodes messages produced by Alibaba Canal, a MySQL/MariaDB CDC tool popular in the Chinese technology ecosystem. pg_tide can ingest Canal change streams into a PostgreSQL inbox for cross-database replication, data consolidation, or event-driven processing.

Note: Canal is decode-only. pg_tide can consume Canal messages but does not produce them.

Message Shape

Canal produces JSON messages with this structure:

{
  "id": 1,
  "database": "myapp",
  "table": "orders",
  "pkNames": ["id"],
  "isDdl": false,
  "type": "INSERT",
  "es": 1714029482000,
  "ts": 1714029483000,
  "data": [
    {
      "id": "42",
      "status": "confirmed",
      "total": "99.95"
    }
  ],
  "old": null
}

For UPDATE operations:

{
  "id": 2,
  "database": "myapp",
  "table": "orders",
  "pkNames": ["id"],
  "isDdl": false,
  "type": "UPDATE",
  "es": 1714029484000,
  "ts": 1714029485000,
  "data": [
    {
      "id": "42",
      "status": "shipped",
      "total": "99.95"
    }
  ],
  "old": [
    {
      "status": "confirmed"
    }
  ]
}

Important: Canal serializes all column values as strings, regardless of their original MySQL type.

Decoded Fields

Inbox FieldCanal Source
event_idMessage key or generated UUID
event_type{database}.{table}
opFrom type: INSERT→insert, UPDATE→update, DELETE→delete
payloadFirst element of data array
old_payloadFirst element of old array (updates only)
commit_tsFrom es (event timestamp, milliseconds)
source_positionFrom id field

Configuration

[[pipelines]]
name = "canal-ingest"
wire_format = "canal"

[pipelines.wire_config]
skip_ddl = true

Configuration Reference

ParameterTypeDefaultDescription
skip_ddlbooltrueSkip DDL events (CREATE TABLE, ALTER TABLE, etc.)

DDL Events

Canal captures DDL (Data Definition Language) statements like ALTER TABLE and CREATE INDEX. These events have isDdl: true. By default, pg_tide skips them since they don't represent data changes. Set skip_ddl: false if you want to capture schema changes as events in your inbox.

String-Typed Values

Canal represents all MySQL column values as JSON strings. A numeric column total DECIMAL(10,2) arrives as "99.95" rather than 99.95. Your downstream processing should account for this — you may want to use a JMESPath transform to cast values back to their intended types.

Further Reading

Wire Format: CDC JSON

The CDC JSON wire format is a universal decoder that maps any JSON-based change data capture format into pg_tide's internal model using JSONPath expressions. Instead of being tied to a specific CDC tool's output shape, you define paths that tell pg_tide where to find the operation type, payload, timestamps, and other fields within your custom message format.

This is the format to use when your source produces CDC-like messages but doesn't match Debezium, Maxwell, or Canal exactly.

Note: CDC JSON is decode-only. pg_tide can consume custom CDC messages but does not produce them.

How It Works

You provide JSONPath expressions that map fields from your message format to pg_tide's internal representation:

Your custom message            JSONPath config             pg_tide inbox row
─────────────────────          ─────────────────           ─────────────────
{                                                          event_id: "evt-42"
  "event_type": "created",     op_path: "$.event_type"    op: insert
  "occurred_at": "2024...",    commit_ts_path: ...        commit_ts: 2024-...
  "data": {                    payload_path: "$.data"     payload: {id: 7}
    "id": 7,
    "name": "alice"
  }
}

Configuration

[[pipelines]]
name = "custom-cdc-ingest"
wire_format = "cdc_json"

[pipelines.wire_config]
op_path = "$.event_type"
payload_path = "$.data"
commit_ts_path = "$.occurred_at"
commit_ts_format = "rfc3339"

[pipelines.wire_config.op_map]
created = "insert"
modified = "update"
removed = "delete"

Configuration Reference

ParameterTypeDefaultDescription
op_pathstring"$.op"JSONPath to the operation field
op_mapobject{}Map source values to pg_tide ops
payload_pathstring"$"JSONPath to new row / event data
old_payload_pathstringnullJSONPath to before-state (optional)
event_id_pathstringnullJSONPath to deduplication key
event_type_pathstringnullJSONPath to event type (defaults to topic)
commit_ts_pathstringnullJSONPath to commit timestamp
commit_ts_formatstring"rfc3339"Timestamp format: "rfc3339", "unix_seconds", "unix_millis"
source_position_pathstringnullJSONPath to source position / offset

JSONPath Syntax

pg_tide supports simple dot-notation JSONPath expressions:

  • $ — The entire message (root)
  • $.field — Top-level field
  • $.field.nested — Nested field access

Array indexing is not supported. If your messages use arrays, consider preprocessing or using a JMESPath transform.

Operation Mapping

The op_map configuration translates your source's operation names into pg_tide's standard operations (insert, update, delete):

[pipelines.wire_config.op_map]
# Map custom names to pg_tide standard ops
"CREATED" = "insert"
"UPDATED" = "update"
"DELETED" = "delete"
"SNAPSHOT" = "insert"

If op_map is empty and op_path points to a field that already contains insert/update/delete, no mapping is needed.

Examples

Stripe-style Events

{
  "id": "evt_1234",
  "type": "invoice.paid",
  "created": 1714029482,
  "data": {
    "object": { "id": "in_5678", "amount": 5000 }
  }
}
[pipelines.wire_config]
event_id_path = "$.id"
event_type_path = "$.type"
payload_path = "$.data.object"
commit_ts_path = "$.created"
commit_ts_format = "unix_seconds"
# No op_path needed — all events are treated as inserts by default

Custom Microservice Events

{
  "action": "user.updated",
  "timestamp": "2024-04-25T14:30:00Z",
  "correlation_id": "corr-abc-123",
  "before": { "name": "Alice", "role": "user" },
  "after": { "name": "Alice", "role": "admin" }
}
[pipelines.wire_config]
op_path = "$.action"
op_map = { "user.created" = "insert", "user.updated" = "update", "user.deleted" = "delete" }
event_id_path = "$.correlation_id"
event_type_path = "$.action"
payload_path = "$.after"
old_payload_path = "$.before"
commit_ts_path = "$.timestamp"
commit_ts_format = "rfc3339"

Further Reading

Wire Format: Debezium

The Debezium wire format produces and consumes messages in the same shape as Debezium, the popular open-source CDC platform. This means pg_tide can be a drop-in replacement for Debezium in existing architectures — your Kafka consumers, ksqlDB queries, Flink jobs, and stream processors continue working without modification.

Encoded Format (Outbox → Sink)

For an INSERT operation:

{
  "schema": { ... },
  "payload": {
    "before": null,
    "after": {
      "order_id": "ORD-001",
      "status": "confirmed",
      "total": 99.95
    },
    "op": "c",
    "ts_ms": 1714029482000,
    "source": {
      "version": "pg-tide",
      "connector": "postgresql",
      "name": "production",
      "ts_ms": 1714029482000,
      "db": "mydb",
      "schema": "public",
      "table": "orders",
      "lsn": 12345678
    }
  }
}

For a DELETE operation with tombstones enabled, two messages are produced:

  1. The delete event (with before populated and after as null)
  2. A tombstone message (null value with the same key) for log compaction

Operation Mapping

pg_tide opDebezium opNotes
insertc (create)before = null, after = new row
updateu (update)before = old row, after = new row
deleted (delete)before = old row, after = null

Decoded Format (Source → Inbox)

When consuming Debezium messages (e.g., from an actual Debezium deployment feeding Kafka), pg_tide extracts:

FieldSource
event_idFrom message key or generated UUID
event_type{source.db}.{source.table}
opMapped from payload.op: c→insert, u→update, d→delete, r→insert/upsert
payloadFrom payload.after (or payload.before for deletes)
old_payloadFrom payload.before (for updates)
commit_tsFrom payload.source.ts_ms
source_positionFrom payload.source.lsn

Snapshot reads (op: "r") are treated as inserts by default, configurable via snapshot_op_treatment.

Configuration

[[pipelines]]
name = "orders-to-kafka"
wire_format = "debezium"

[pipelines.wire_config]
server_name = "production"
emit_tombstones = true
envelope = "json"
tombstone_handling = "delete"
key_strategy = "primary_key"
snapshot_op_treatment = "insert"
heartbeat_interval_ms = 10000

Configuration Reference

ParameterTypeDefaultDescription
server_namestring"pg-tide"Logical name in source.name field
envelopestring"json"Envelope type: "json" or "avro"
emit_tombstonesbooltrueEmit null-value tombstone after DELETE
tombstone_handlingstring"delete"How to handle incoming tombstones: "delete" or "drop"
key_strategystring"primary_key"Message key: "primary_key" or "message_key"
snapshot_op_treatmentstring"insert"Treat op=r as: "insert" or "upsert"
heartbeat_interval_msint10000Heartbeat emission interval (0 = disabled)
schema_registry_urlstringnullConfluent Schema Registry URL (for Avro)

Avro Support

When envelope is set to "avro", messages are serialized using Apache Avro with schemas registered in a Confluent-compatible Schema Registry. This provides:

  • Compact binary encoding (smaller messages)
  • Schema evolution with compatibility checks
  • Integration with the Confluent ecosystem
[pipelines.wire_config]
envelope = "avro"
schema_registry_url = "http://schema-registry:8081"

Schema Evolution

The Debezium format tracks schema changes. When a new column appears in the outbox, it's added to the Avro schema or JSON structure automatically. Incompatible changes (column removal) are detected and reported.

Tombstones and Log Compaction

Kafka topic compaction uses null-value messages (tombstones) to signal that a key should be removed. When emit_tombstones is true, a DELETE operation produces two messages:

  1. Delete event — Contains the old row state in before
  2. Tombstone — Null value with the same key, enabling compaction to remove the key

This is essential for Kafka topics configured with cleanup.policy=compact.

Migrating from Debezium to pg_tide

If you're currently using Debezium and want to switch to pg_tide:

  1. Configure pg_tide with wire_format = "debezium" and matching server_name
  2. Consumers see identical message shapes — no changes needed
  3. The source.version field changes to "pg-tide" but this rarely matters
  4. You lose Debezium-specific features (schema history topic) but gain transactional outbox guarantees

Further Reading

Wire Format: Maxwell

The Maxwell wire format decodes messages produced by Maxwell's Daemon, a MySQL CDC tool. This allows pg_tide to ingest MySQL change streams into a PostgreSQL inbox — useful for migrating data from MySQL to PostgreSQL, building cross-database event pipelines, or consolidating changes from multiple MySQL instances.

Note: Maxwell is decode-only. pg_tide can consume Maxwell messages but does not produce them.

Message Shape

Maxwell produces JSON messages with this structure:

{
  "database": "myapp",
  "table": "users",
  "type": "insert",
  "ts": 1714029482,
  "xid": 12345,
  "data": {
    "id": 7,
    "name": "alice",
    "email": "alice@example.com"
  }
}

For UPDATE operations, an old field contains the previous values of changed columns:

{
  "database": "myapp",
  "table": "users",
  "type": "update",
  "ts": 1714029482,
  "xid": 12346,
  "data": {
    "id": 7,
    "name": "alice_new",
    "email": "alice@example.com"
  },
  "old": {
    "name": "alice"
  }
}

Decoded Fields

Inbox FieldMaxwell Source
event_idMessage key or generated UUID
event_type{database}.{table}
opFrom type: insert, update, delete
payloadFrom data field
old_payloadFrom old field (updates only)
commit_tsFrom ts (Unix seconds)
source_positionFrom xid or position

Configuration

[[pipelines]]
name = "mysql-to-postgres"
wire_format = "maxwell"

[pipelines.wire_config]
treat_bootstrap_as_insert = true

Configuration Reference

ParameterTypeDefaultDescription
treat_bootstrap_as_insertbooltrueMap bootstrap-insert events as INSERT operations

Bootstrap Events

Maxwell supports "bootstrapping" — bulk-loading existing table data. These events have type: "bootstrap-insert". With treat_bootstrap_as_insert: true (the default), they're treated as normal inserts, allowing you to perform initial data loads through the same pipeline.

Further Reading

Wire Format: Native

The native wire format is pg_tide's default. It passes outbox rows through with minimal transformation, producing clean JSON that contains all the information needed to reconstruct the event on the receiving side. If you control both the producer and consumer, native is the simplest and most transparent choice.

Encoded Format (Outbox → Sink)

When encoding an outbox row for delivery, the native format produces:

{
  "outbox_id": 42,
  "op": "insert",
  "stream_table": "order_events",
  "payload": {
    "order_id": "ORD-001",
    "status": "confirmed",
    "total": 99.95
  }
}

The message key is set to the outbox row's routing key (if configured) or the outbox ID.

Decoded Format (Source → Inbox)

When decoding incoming messages, the native format expects JSON payloads. It extracts:

FieldSource
event_idFrom message key, or generated UUID
event_typeFrom stream_table field or message topic
opFrom op field (insert, update, delete)
payloadFrom payload field (or entire message)

Configuration

No configuration is needed — native is the default when no wire_format is specified:

[[pipelines]]
name = "orders"
# wire_format defaults to "native"

Or explicitly:

[[pipelines]]
name = "orders"
wire_format = "native"

When to Use Native

  • Both producer and consumer are pg_tide (e.g., outbox → inbox replication)
  • You control the consumer and can parse the simple JSON envelope
  • You want maximum transparency — what goes in is what comes out
  • You're debugging or developing and want to see raw messages clearly

When to Use Something Else

  • Your consumer needs standard event metadata → use CloudEvents
  • Your consumer needs a custom envelope → adapt it at the destination boundary

Further Reading

Wire Formats

A wire format defines the serialized message envelope sent by the relay. v0.49.0 supports native pg_tide JSON and CloudEvents for outbound delivery.

FormatUse case
NativeDefault pg_tide envelope with stable event identity
CloudEventsStandard event metadata for HTTP and broker consumers

Select a format with the pipeline's wire_format key. If omitted, the relay uses native.

{
  "wire_format": "cloudevents",
  "sink_type": "kafka"
}

Both formats preserve the outbox operation, subject, payload, and deduplication identity. Delivery remains at-least-once.

PostgreSQL Inbox Compatibility Alias

pg_outbox is a compatibility alias for the remote PostgreSQL inbox sink. It does not replicate into a remote outbox and is not counted as a separate supported destination. New configurations should use sink_type = "inbox".

When to Use This Sink

Use the alias only while migrating an existing remote inbox configuration.

Configuration

SELECT tide.relay_set_outbox_v2(
  jsonb_build_object(
    'name', 'replicate-to-eu',
    'outbox', 'orders',
    'sink_type', 'pg_outbox',
    'config', '{
        "postgres_url": "${env:EU_DB_URL}",
        "inbox": "orders_eu_events",
        "batch_size": 200
    }'::jsonb
  )
);

Configuration Reference

ParameterTypeDefaultDescription
sink_typestring—Must be "pg_outbox"
postgres_urlstring—PostgreSQL URL for the remote target instance
inboxstring—Target inbox name on the remote instance
batch_sizeint100Messages per batch

Further Reading

Architecture

pg_tide consists of two components that work together: a PostgreSQL extension that manages the outbox/inbox catalog, and a relay binary that bridges messages to external systems.


High-Level Overview

┌─────────────────────────────────────────────────────────┐
│                    PostgreSQL 18                          │
│                                                          │
│  ┌──────────────┐   ┌──────────────┐   ┌────────────┐  │
│  │ tide_outbox   │   │ tide_inbox    │   │ relay_     │  │
│  │ _config       │   │ _config       │   │ *_config   │  │
│  └──────┬───────┘   └──────┬───────┘   └─────┬──────┘  │
│         │                   │                  │         │
│  ┌──────▼───────┐   ┌──────▼───────┐         │         │
│  │ tide_outbox   │   │ {name}_inbox  │         │         │
│  │ _messages     │   │  (per inbox)  │         │         │
│  └──────┬───────┘   └──────▲───────┘         │         │
│         │                   │                  │         │
└─────────┼───────────────────┼──────────────────┼─────────┘
          │                   │                  │
          │  LISTEN/NOTIFY    │                  │
          ▼                   │                  ▼
┌─────────────────────────────────────────────────────────┐
│                   pg-tide relay binary                    │
│                                                          │
│  ┌────────────┐        ┌────────────┐                   │
│  │   Source    │───────▶│    Sink     │                   │
│  │ (outbox    │        │ (NATS,     │                   │
│  │  poller)   │        │  Kafka,    │                   │
│  └────────────┘        │  Redis…)   │                   │
│                         └────────────┘                   │
│  ┌────────────┐        ┌────────────┐                   │
│  │   Source    │───────▶│    Sink     │                   │
│  │ (NATS,     │        │ (inbox     │                   │
│  │  Kafka…)   │        │  writer)   │                   │
│  └────────────┘        └────────────┘                   │
└─────────────────────────────────────────────────────────┘
          │                                     │
          ▼                                     ▼
┌──────────────┐                    ┌──────────────────┐
│  External     │                    │  External         │
│  Systems      │                    │  Systems          │
│  (consumers)  │                    │  (producers)      │
└──────────────┘                    └──────────────────┘

The Extension Layer

The pg_tide extension installs into the tide schema and provides:

  • Catalog tables — configuration for outboxes, inboxes, consumer groups, and relay pipelines
  • Message storage — a shared tide_outbox_messages table for all outboxes, individual {name}_inbox tables for each inbox
  • SQL API — functions for publishing, consuming, and managing the lifecycle
  • NOTIFY triggers — real-time notifications when relay config changes

The extension has no background workers and no shared memory. All state is purely relational, making it compatible with connection poolers (PgBouncer, PgCat) and managed PostgreSQL services.


The Relay Binary

The pg-tide binary is a standalone Rust process that:

  1. Connects to PostgreSQL and reads pipeline configurations from the relay catalog
  2. Acquires advisory locks for each pipeline (enabling multi-relay HA deployments)
  3. Polls outbox tables for new messages (forward mode)
  4. Subscribes to external sources for incoming messages (reverse mode)
  5. Delivers messages to configured sinks with retry and stable identities
  6. Commits offsets after durable sink acknowledgment (at-least-once transport; destination deduplication can provide an effectively exactly-once outcome)
  7. Exposes Prometheus metrics and a health endpoint

The relay supports hot-reload via LISTEN tide_relay_config — when you update pipeline config in the database, the relay picks up changes without restart.


Forward Mode (Outbox → External)

Application   ──INSERT──▶  tide_outbox_messages
                                   │
                                   │ (relay polls)
                                   ▼
                             pg-tide relay  ──publish──▶  NATS / Kafka / Redis / …
                                   │
                                   │ (on success)
                                   ▼
                          commit offset + mark consumed

Reverse Mode (External → Inbox)

NATS / Kafka / Redis / …  ──subscribe──▶  pg-tide relay
                                                  │
                                                  │ (dedup + insert)
                                                  ▼
                                           {name}_inbox table
                                                  │
                                                  │ (application reads)
                                                  ▼
                                            Your application

Deployment Topologies

Single relay (simplest)

One relay instance handles all pipelines. Suitable for low-to-medium throughput.

Multiple relays (HA)

Multiple relay instances connect to the same database. PostgreSQL advisory locks ensure each pipeline is owned by exactly one relay — automatic failover when a relay dies.

Sidecar pattern

Deploy the relay as a sidecar container alongside your application pod in Kubernetes. Each pod handles its own subset of pipelines.

Architecture Decision Records

This page documents the key architectural decisions made in pg_tide's design, their rationale, and the alternatives that were considered.

ADR-1: Transactional Outbox over WAL-Based CDC

Decision: pg_tide uses the transactional outbox pattern rather than WAL (logical replication) for change capture.

Context: Most CDC tools (Debezium, pgoutput) read the PostgreSQL WAL to capture changes. This is transparent to the application but has limitations: it captures all changes (including internal ones), can't easily enrich events with application context, and requires careful management of replication slots.

Rationale:

  • Applications control exactly what events are published and when
  • Events are guaranteed to be published if and only if the business transaction commits
  • No replication slot management or WAL retention concerns
  • Events can include derived data not present in any single table
  • Schema is explicit and application-controlled

Trade-offs:

  • Applications must explicitly call tide.outbox_publish() (not transparent)
  • Slightly more application code vs. transparent CDC
  • Cannot capture changes from direct SQL or other tools (unless triggers are used)

ADR-2: PostgreSQL Advisory Locks for HA Coordination

Decision: Use pg_try_advisory_lock() for pipeline ownership coordination rather than external consensus (etcd, ZooKeeper) or leader election.

Context: Multiple relay instances need to coordinate which instance processes which pipeline without double-processing.

Rationale:

  • Zero additional infrastructure — PostgreSQL is already required
  • Advisory locks are automatically released on connection close (crash safety)
  • Non-blocking pg_try_advisory_lock prevents deadlocks
  • Well-understood PostgreSQL primitive with decades of production use

Trade-offs:

  • Requires all relay instances to connect to the same PostgreSQL instance
  • Discovery interval determines failover speed (not instant)
  • Lock granularity is per-pipeline (cannot split a single pipeline across instances)

ADR-3: Pipeline Configuration in PostgreSQL Catalog

Decision: Store pipeline configurations in PostgreSQL tables (tide.relay_outbox_config, tide.relay_inbox_config) rather than in TOML/YAML files or environment variables.

Context: The relay needs to know which pipelines to run and how to configure each one.

Rationale:

  • Configuration changes via SQL (hot-reload without restart)
  • LISTEN/NOTIFY enables instant propagation
  • Configuration is transactional (rollback on error)
  • All relay instances see the same configuration (single source of truth)
  • Easy to manage programmatically (Terraform, application code)

Trade-offs:

  • Requires database access to view/change configuration
  • Secrets must use ${env:...} substitution (not stored in catalog)
  • Slightly less familiar than file-based config for ops teams

ADR-4: Single Binary Relay

Decision: The relay is a single statically-linked binary rather than a framework, library, or JVM application.

Context: The relay needs to be deployed easily across diverse environments.

Rationale:

  • Single binary deployment (no runtime dependencies)
  • Small container images (~20 MB)
  • Fast startup time (< 1 second)
  • Low resource consumption (Rust, no GC pauses)
  • Cross-compilation for Linux/macOS/ARM

Trade-offs:

  • Feature-gated compilation (some sinks/sources require build flags)
  • Rust ecosystem less familiar than Java/Python for some teams
  • Plugin system not possible (all sinks compiled in)

ADR-5: JMESPath for Transforms

Decision: Use JMESPath (not JSONPath, jq, or a custom DSL) for message transforms and filters.

Context: Messages need lightweight filtering and reshaping without external tools.

Rationale:

  • Well-specified language with formal grammar
  • Deterministic evaluation (no side effects)
  • Good balance of power and simplicity
  • Fast compiled evaluation
  • Familiar from AWS CLI and other tools

Trade-offs:

  • Less powerful than jq (no recursion, limited array manipulation)
  • No support for array indexing in field paths
  • Users must learn JMESPath syntax

ADR-6: At-Least-Once Delivery

Decision: pg_tide provides at-least-once relay transport by default, not unqualified cross-system exactly-once delivery.

Context: Distributed systems cannot provide exactly-once delivery without end-to-end coordination.

Rationale:

  • At-least-once is achievable without two-phase commit
  • Simpler implementation, more reliable operation
  • The inbox provides destination-side deduplication for effectively exactly-once processing when application work is transactional and idempotent
  • Most sinks (Kafka, NATS) inherently provide at-least-once anyway
  • Idempotent consumers are a well-understood pattern

Trade-offs:

  • Consumers may receive duplicate messages (rare, only on failure/recovery)
  • Applications that need an effectively exactly-once outcome must implement durable deduplication and idempotent processing
  • The inbox pattern adds complexity for cross-system exactly-once

ADR-7: Canonical Outbox Storage and Native Relay Polling

Decision: The native relay polls the single shared table tide.tide_outbox_messages with a static, parameterized query keyed by outbox_name, and tracks offsets by (relay_group_id, pipeline_id, outbox_name).

Context: The native write path (tide.outbox_publish()) always wrote to tide.tide_outbox_messages, but the relay's native source historically polled a dynamically-named per-outbox relation (tide."outbox_<name>") that native installs never create. That relation naming belongs to pg_trickle compatibility, not native pg_tide.

Rationale:

  • The read and write paths must address the same table
  • A static WHERE outbox_name = $1 AND id > $2 ORDER BY id LIMIT $3 query with an unconditional (outbox_name, id) index needs no per-outbox DDL
  • Per-pipeline offsets make fan-out and restart correct without relying on the global consumed_at timestamp
  • pg_trickle compatibility remains available behind an explicit source_type = "pg_trickle_outbox" mode

Trade-offs:

  • The offset key change ((relay_group_id, pipeline_id) → (relay_group_id, pipeline_id, outbox_name)) requires a stop-upgrade-start migration
  • Global identity gaps within one outbox are expected; ordering is strictly increasing but not contiguous
  • consumed_at and consumer groups remain but are non-authoritative for native delivery

See ADR-011 for the full record.

ADR-012: Relay Delivery Acknowledgment and Offset State Machine

Decision: Advance a source checkpoint only after a complete polled batch reaches a durable terminal disposition: connector acknowledgment, atomic DLQ storage, intentional filtering, or consuming dry-run observation.

The relay is at-least-once transport. Downstream success before checkpoint commit can duplicate with the same stable event identity, but cannot silently lose the event. Effectively exactly once requires durable destination deduplication and idempotent/transactional application processing.

See ADR-012 for the transition matrix, connector boundaries, ownership-session lifecycle, and observability contract.

The canonical delivery vocabulary is Polled -> Encoded -> PublishStarted -> SinkAccepted -> SinkAcknowledged -> CheckpointCommitted -> CleanupEligible. Dry-run and intentional filtering branch from Encoded; failed publishing branches through PublishFailed -> DlqPersisted. The pure executable model in pg-tide-relay/src/delivery_model.rs tests these transitions without I/O.

Further Reading