Queries icon
IonToJson icon
TransformItems icon
Batch icon
Query icon
Find icon
Fail icon
If icon
Set icon
Log icon
SlackIncomingWebhook icon
Trigger icon

Upsert MongoDB Change Stream Events into a PostgreSQL Reporting Table

Replicate a MongoDB collection into a PostgreSQL reporting table with a change stream trigger, ON CONFLICT upserts, ordered tombstones and checks.

Categories
Data

A nightly export of MongoDB orders is late and loses deletes. This flow reads the change stream and keeps reporting.orders in PostgreSQL current, with deletes kept as tombstones.

How it works

  1. The Debezium MongoDB trigger reads the change stream of shop.orders. The first run takes a snapshot.
  2. prepare_reporting_table creates the table and the reporting.orders_live view if they do not exist.
  3. decode_change_events and map_change_events turn each document into one flat row and keep the full document as jsonb.
  4. upsert_orders runs INSERT ... ON CONFLICT DO UPDATE. The WHERE clause compares the MongoDB cluster time, so a late or replayed event does not overwrite a newer row.
  5. find_tombstoned_documents reads MongoDB again. The run fails if a tombstoned order still exists.
  6. watermark_gate stores the last applied cluster time in the KV store only when rows changed.
  7. alert_sync_failure sends a Slack message when a task fails.

What you get

  • Upserted rows, and tombstones with is_deleted and deleted_at.
  • Ordered, idempotent writes. A restart or replay is safe.
  • A KV watermark for freshness checks.

Who it's for

  • Data engineers who feed BI tools from MongoDB.
  • Platform teams that want CDC without Kafka Connect.

Why orchestrate this with Kestra

  • Kestra stores the change stream offset. You do not run a connector cluster.
  • Each batch is one execution with logs and a restart button.
  • concurrency with QUEUE applies batches in order.

Prerequisites

  • MongoDB as a replica set, with changeStreamPreAndPostImages enabled on the collection.
  • A PostgreSQL user that can create the reporting schema.

Secrets

  • MONGODB_CDC_URI: MongoDB connection string with the replica set name.
  • PG_REPORTING_JDBC_URL: JDBC URL of the reporting database.
  • PG_REPORTING_USER: PostgreSQL user.
  • PG_REPORTING_PASSWORD: PostgreSQL password.
  • SLACK_WEBHOOK_URL: Slack incoming webhook for failure alerts.

Quick start

  1. Add the five secrets to the namespace.
  2. Change the collection variables and includedCollections if necessary.
  3. Save the flow. The first execution starts within one minute.
  4. Query reporting.orders_live and compare it with MongoDB.

How to extend

  • Move order lines to a child table with a second Batch task.
  • Add a schedule that purges old tombstones.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.