Query icon
Request icon
If icon
Fail icon
OutputValues icon
Log icon
SlackIncomingWebhook icon
Pause icon
Loop icon
Put icon
Schedule icon

Elasticsearch vs PostgreSQL Search Index Reconcile Guard

Find Elasticsearch docs orphaned, stale or missing versus a PostgreSQL source of truth, alert Slack, delete and reindex them, then fail if any remain.

Categories
DataInfrastructure

A search index drifts from the table it is built from in three ways that neither system can see alone. A row deleted in PostgreSQL can leave its document behind in Elasticsearch, so search keeps returning a record that no longer exists. A row updated in PostgreSQL can leave an older copy in the index, so search returns a document that is behind the truth. A new row may never reach the index, so it cannot be found at all.

This blueprint reconciles the two. It reads the authoritative keyset and a per-row version from PostgreSQL first, then reads the indexed documents from Elasticsearch and diffs both sides. PostgreSQL is the source of truth, so the keyset is driven from it and every run is deterministic. It reports the divergence, alerts Slack and on request deletes the orphans with one _delete_by_query and reindexes each stale or missing document from the database row with a Put. Every write sits behind a Pause for human approval. After the writes it reads both sides again and fails the run if any divergence remains. PostgreSQL is never written.

This blueprint was created by zkasuran.

Findings

Finding Meaning Fix
ORPHAN The document key is gone from PostgreSQL (the row was deleted) but the document is still indexed delete the document
STALE The row is live but the document version is behind the database version reindex the document at the current database version and payload
MISSING The row is live but is not indexed, so it cannot be found index the document from the database row

A deleted row with no document is already correct and is not flagged. The gate that must reach zero is the orphan plus stale plus missing count.

How it works

  1. pg_read (io.kestra.plugin.jdbc.postgresql.Query, read-only) returns every live row with its key, its version and the payload column, in key order, up to batch_limit rows.
  2. es_read (io.kestra.plugin.elasticsearch.Request, read-only) runs one _search that returns every document id with its version field. index_check fails the run if the read is not HTTP 200, because the Request task reports success on any status. limit_check fails it when a read reaches batch_limit, since a partial keyset reports live documents as orphans.
  3. diff compares the two. An orphan is a document whose key is not in the PostgreSQL keyset. A stale document is one whose version is below the database version. A missing row is one in PostgreSQL with no document. plan builds the orphan id list and the reindex list. summary logs the counts.
  4. route (io.kestra.plugin.core.flow.If):
    • clean: logs it, nothing to do, no alert.
    • divergence: alert posts to Slack.
      • remediate_gate runs only when auto_remediate is true and dry_run is false.
      • approval (io.kestra.plugin.core.flow.Pause) holds the run. It resumes only when a human sets approved true, so an unanswered or declined resume applies nothing.
      • delete_orphans (io.kestra.plugin.elasticsearch.Request, _delete_by_query with refresh) removes the orphan documents. reindex (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) rebuilds each stale and missing document with io.kestra.plugin.elasticsearch.Put at refreshPolicy: IMMEDIATE.
      • reverify_pg and reverify_es read both sides again, reverify_diff re-runs the diff and verify_result fails the run if any orphan, stale or missing document is left.
  5. errors alerts Slack when the flow fails.

What you get

  • A per-key reconcile across two live systems, with PostgreSQL as the source of truth, not a scan of Elasticsearch on its own.
  • The orphaned, stale and missing documents named, with the database version next to the indexed version.
  • Deletes and reindexes applied only behind auto_remediate, dry_run and a human approval, with a second read of both sides as proof.

Who it's for

  • Teams that build an Elasticsearch index from a PostgreSQL table and have served a deleted record or a stale result in search.
  • SREs who want a scheduled check that the search index has not drifted from its database.
  • Teams who want one flow that reads PostgreSQL and writes only to the index.

Why orchestrate this with Kestra

A search index drifts quietly and the drift spans two systems that each look healthy alone. Kestra reads the authoritative keyset from PostgreSQL, reads the documents from Elasticsearch, sends the divergence to Slack, deletes and reindexes only behind two flags and an approval, verifies the result and keeps a history of every reconcile.

Tested end to end

On Kestra 2.0.5 against PostgreSQL 16 and Elasticsearch 8.15.3, with a local HTTP sink standing in for Slack. The source table held 5 live rows (1 v5, 2 v5, 3 v7, 4 v3, 5 v2). The index held 6 documents (1 v5, 2 v5, 3 v4, 4 v2, 6 v9, 7 v4), so 3 and 4 were stale, 6 and 7 were orphaned and 5 was missing.

Run Inputs Result
1 defaults 5 divergences (orphan 6, 7; stale 3 db=7 idx=4, 4 db=3 idx=2; missing 5). Alert sent. The index was unchanged
2 auto_remediate: true, dry_run: true Same 5 divergences, the gate stayed closed, the index was unchanged
3 auto_remediate: true, dry_run: false, approved Deleted 2 orphans, reindexed 2 stale and 1 missing document, re-read reported 0 remaining. _search after: 6 and 7 gone, 3 now v7, 4 now v3, 5 indexed v2, 1 and 2 untouched. psql confirmed the table unchanged
4 clean index, auto_remediate: true, dry_run: false 0 divergences, clean branch, no alert
5 auto_remediate: true, dry_run: false, approval declined 5 divergences, no write, the index was unchanged
6 auto_remediate: true, dry_run: false, approved, with a writer indexing a new orphan during the pause Re-read still found the new orphan, verify_result failed the run rather than reporting success
7 unreachable Elasticsearch host es_read failed, the run failed, the errors block posted to Slack

Detector proof: the degraded index reported 5 and the clean index reported 0, both matching the counts measured straight from psql and the Elasticsearch _count and _search APIs. PostgreSQL held 5 rows before and after every run.

Prerequisites

  • A PostgreSQL table that is the source of truth, with a key column, a version that increases on every update and a hard delete that removes the row.
  • An Elasticsearch index whose document _id is the row key, carrying a version field it was indexed at and a payload field.
  • For the audit, a PostgreSQL role that can read the table and an Elasticsearch user that can search the index. For remediation, an Elasticsearch user allowed to delete and index documents.
  • Local testing:
    • docker run -d --name pg --network kw7 -e POSTGRES_PASSWORD=pw postgres:16;
    • docker run -d --name es --network kw7 -e discovery.type=single-node -e xpack.security.enabled=false docker.elastic.co/elasticsearch/elasticsearch:8.15.3;
    • seed a few rows, index some at the right version, index others a version behind, leave a document for a deleted row and leave one row unindexed.

Secrets

  • POSTGRES_PASSWORD: the password for pg_user, read by every query.
  • ELASTICSEARCH_HOST: the index URL including scheme and port, for example http://host:9200.
  • ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD: the Elasticsearch credentials.
  • SLACK_WEBHOOK_URL: used by alert and the errors block.
  • In Kestra OSS, provide each one as a base64-encoded environment variable prefixed SECRET_.

Inputs

Input Default Purpose
pg_host / pg_port / pg_db / pg_user localhost, 5432, postgres, postgres PostgreSQL connection
pg_password secret('POSTGRES_PASSWORD') PostgreSQL password
pg_table product Source of truth table
pg_key_column / pg_version_column / pg_payload_column product_id, version, title Row key, version and payload
es_host / es_user / es_password secret(...) Elasticsearch connection
es_index products Index reconciled against the table
doc_version_field / doc_payload_field version, title Document version and payload fields
batch_limit 5000 Upper bound on each read. The run fails if one reaches it
auto_remediate false Allow deletes and reindexes
dry_run true Must be false for a change to apply

Quick start

  1. Add the five secrets listed above.
  2. Import the flow and set the connection inputs and the field names to match your index.
  3. Run it once and read the orphaned, stale and missing documents.
  4. Run it with auto_remediate: true and dry_run: false, approve the pause, then read the remediated log for the proof.
  5. Enable the hourly trigger, which always runs in safe mode.

How to extend

  • Compare on updated_at instead of a numeric version by returning it from the query and storing it in the document.
  • Create the index from a mapping first when it may not exist, then let the missing rows fill it.
  • Page through a large table by ordering on the key and carrying a cursor in a KV store, so an index larger than index.max_result_window is reconciled in slices.
  • Reconcile several indices by looping over a list of tables and indices.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.