Video in progress
If the primary data is in Postgres and search is in Elasticsearch, how do you keep them in sync, and what do you do when the index gets corrupted?
In the application I don't do "write to the DB, then write to ES". Changes go to a queue through CDC or an outbox, and an indexer writes them with versions. A way to rebuild the index from scratch is always ready: a new index, a full reindex, then swapping the alias.
📖 Answer
Writing to two places from the application gives you the dual write problem mentioned above: one succeeds, the other doesn't. After a few months the index accumulates missing documents and documents that should have been deleted, and nobody ever finds out it broke.
The flow I build:
- Postgres → Debezium → Kafka
productstopic (key isproductId). - The indexer service picks up the event. A document often has to be assembled from several tables, not one row (product + price + stock). So I use the event as a signal and read the full document from the DB, which also reduces ordering problems.
- I write to ES with
version_type=external: an old version can't overwrite a newer one. - Delete events become a
delete. With soft delete, a filter instead.
A rebuild plan has to exist in advance, because the mapping changes, the analyzer gets replaced, or a bug corrupts the index:
- a new index
products_v7is created; - a backfill job reads everything from the DB and writes it; meanwhile the CDC stream writes to both indexes;
- document counts and sampled documents are compared;
- the
productsalias is switched atomically tov7; the old index stays for a few days.
Monitoring: CDC lag, indexer errors, and most useful of all, a nightly job that compares the number of documents (and their hash) in the DB and ES per tenant. If the difference goes over a threshold, alert and reindex that slice.
What to explain to the product side: search results are a few seconds late. If a user must see something they just created in the list right away, that page has to read from the DB, not from search.
Sign up to mark studied questions and save your progress.