Video in progress

Strong Middle 🧩 Microservices

How do you keep an Elasticsearch/OpenSearch index for product search in sync with the service's DB, and how do you do a full reindex?

The DB is the source of truth and the index is a copy derived from it. I pass changes to an indexing consumer through outbox or CDC events and use versions so an old record can't overwrite a newer one. A full reindex goes into a new index, then the alias is swapped in an instant.

📖 Answer

The most common mistake is writing to two places in code:

productRepo.save(p);
searchClient.index(p);   // if this fails, the index goes stale and nobody knows

That is the same dual write. The index falls behind the DB, and search shows deleted products.

A reliable setup:

product DB --(outbox or Debezium)--> Kafka: product-changed --> search-indexer --> ES

The indexer:

  • rewrites the whole document by the event's productId (not a partial update), so ordering and duplicates matter less;
  • passes the version to ES: with the external version type, ES rejects a write with an older version itself;
  • receives deletes as events too and deletes the document.
client.index(i -> i.index("products")
        .id(p.id().toString())
        .version(p.version())
        .versionType(VersionType.External)
        .document(ProductDoc.from(p)));

A full reindex (the mapping changed, the analyzer was updated, the index got corrupted):

  1. A new index products_v8 is created.
  2. A backfill job reads all products from the DB with keyset pagination and writes them. New changes must not be lost in the meantime either: the indexer writes to both indexes, or you remember the offset where the backfill started and replay from that point afterward.
  3. The document counts and random samples are compared.
  4. The products alias is switched from products_v7 to products_v8 with a single atomic request. The search code knows only the alias.
  5. The old index is deleted after a few days, to leave a way back.

Monitoring: the difference in document counts between the DB and the index, and the indexer lag. A daily reconciliation job (comparing 1000 random products in the DB and ES) catches silent drift.