Backend Engineer: Building Real-Time Search Indexes by Syncing PostgreSQL to Elasticsearch Asynchronously

Dual-writing to PostgreSQL and Elasticsearch / OpenSearch inside an HTTP request handler is a classic distributed systems anti-pattern: if the database commit succeeds but the Elasticsearch HTTP call times out—or if two concurrent requests arrive at Elasticsearch out of order—your search index diverges permanently from your relational source of truth. As a Backend Engineer, I architect eventually consistent, strictly ordered PostgreSQL-to-Elasticsearch indexing pipelines using transactional outbox relays, Bulk API `_Main` version guards (`version_type=external`), and zero-downtime alias reindexing.

1. Preventing Out-of-Order Document Overwrites with `version_type: external`

Every mutable row in PostgreSQL carries a monotonically increasing `updated_revision` integer (or commit LSN). When our async outbox worker flushes a batch of 500 document updates to the Elasticsearch `_bulk` API, passing `version: row.updated_revision` and `version_type: "external"` guarantees that if an older update arrives after a newer one, Elasticsearch safely rejects the stale write with `409 VersionConflict` rather than overwriting newer data:

import json
from typing import Iterable

def build_elasticsearch_ndjson_bulk_payload(
    index_alias: str,
    records: Iterable[dict],
) -> str:
    lines: list[str] = []
    for row in records:
        action_meta = {
            "index": {
                "_index": index_alias,
                "_id": str(row["id"]),
                "version": int(row["updated_revision"]),
                "version_type": "external",
            }
        }
        doc_source = {
            "tenant_id": str(row["tenant_id"]),
            "sku": row["sku"],
            "title": row["title"],
            "category": row["category"],
            "price_cents": int(row["price_cents"]),
            "updated_at": row["updated_at"],
        }
        lines.append(json.dumps(action_meta, separators=(",", ":")))
        lines.append(json.dumps(doc_source, separators=(",", ":")))
    return "
".join(lines) + "
"

2. Zero-Downtime Analyzer Upgrades via Index Aliases

Changing an Elasticsearch custom tokenizer or field mapping requires creating a new physical index (`catalog_v2026_11`). By binding search queries to a read alias (`catalog_read`) and bulk indexing to a write alias (`catalog_write`), we backfill the new index via our bounded asyncio bulk ingestion engine and atomically swap the `_aliases` pointer in a single sub-millisecond API call—complementing our PostgreSQL transactional outbox architecture.

Need a Backend Engineer to build reliable PostgreSQL-to-Elasticsearch or OpenSearch synchronization pipelines? Book a 1-Day Engineering Sprint.


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs