Sub topic 7
Keeping the index in sync with the source of truth
This chapter assumes you know basic SQL transactions, how message queues deliver messages (at-least-once, possible reordering), and the index and mapping design from the previous chapter. It covers how changes in the primary database reach the search index, and which failure modes the pipeline must handle.
The index is derived data
The primary database is the source of truth. The search index is a copy, shaped for queries and rebuildable from the database. This has two consequences:
- The index can be wrong, but the database should never be wrong because of the index.
- Every sync design should answer one question: if the index is lost or corrupted, how do we rebuild it?
Keeping a copy in sync is a distributed systems problem. The database and the search engine do not share a transaction, so you can't commit to both atomically.
Four ways to move data
| Approach | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Dual write | The application writes to the database, then to the index, in the same request | Simple, low latency | If one write fails, the two stores diverge. Concurrent requests can apply writes in different orders. |
| Periodic batch | A job queries rows with `updated_at` after the last run and indexes them | Easy to build and to reason about | Freshness is limited by the interval. Hard deletes are invisible. |
| Change data capture (CDC) | A connector reads the database's transaction log and publishes each change to a stream | No application changes, captures every write including deletes | Extra infrastructure. Events mirror table structure, not search documents. |
| Transactional outbox | The application writes a row to an outbox table in the same transaction as the change. A relay publishes the outbox rows. | Atomic with the business write, and you control the event shape | You write and maintain the outbox and the relay. |
Dual write is the usual first attempt and the least safe. A crash between the two writes leaves the index permanently stale, and nothing records that anything went wrong. Prefer CDC or an outbox for anything beyond a prototype. Keep a periodic batch job anyway, as a repair mechanism (see below).
The outbox pattern
The outbox solves the atomicity gap. The business change and the record of "this needs indexing" commit together or not at all.
BEGIN;
UPDATE products SET price = 89.00, version = version + 1 WHERE id = 42;
INSERT INTO search_outbox (product_id, created_at) VALUES (42, now());
COMMIT;A relay process reads unsent outbox rows, publishes them to a queue, and marks them sent. Indexer workers consume the queue and update the search engine.
The relay can crash after publishing but before marking the row sent. It will then publish the event again. The queue is at-least-once, so the indexer must tolerate duplicates.
Send an id, not the whole document
An event can carry the full new document or only the id of the changed entity. Sending only the id has these advantages:
- The indexer always reads the latest state, so a delayed or reordered event still produces correct output.
- The event stays small, and the indexer is the one place that builds the search document.
- Changing the document shape does not require changing producers.
The cost is one extra database read per event, which you can reduce by batching ids. Full-document events avoid the read but risk indexing stale data when events are reordered. For most systems, id-only events with a read-back are the safer default.
Make updates idempotent and ordered
Two properties make the pipeline safe to retry:
- Use the database primary key as the document id. Indexing the same id twice replaces the document instead of creating a duplicate.
- Attach a version from the source database, and tell the search engine to reject older versions.
Elasticsearch supports this with external versioning:
PUT /products/_doc/42?version_type=external&version=7
{
"name": "Trail running shoes",
"category": "footwear",
"price": 89.0,
"in_stock": true
}The request succeeds only if version 7 is greater than the stored version. Otherwise the engine returns a 409 conflict. The indexer should treat that 409 as success, because it means a newer state is already there. The version must come from a monotonic source, such as a row version column or the log sequence number, not from the indexer's clock.
This self-contained simulation shows the rule applied to duplicated and out-of-order events:
index = {} # doc_id -> (version, document)
def index_doc(doc_id, version, doc):
current = index.get(doc_id)
if current is not None and current[0] >= version:
return False # like an HTTP 409 version conflict
index[doc_id] = (version, doc)
return True
events = [
(42, 7, {"name": "Trail running shoes", "price": 89.0}),
(42, 6, {"name": "Running shoes", "price": 99.0}), # late, older
(42, 7, {"name": "Trail running shoes", "price": 89.0}), # duplicate
]
for doc_id, version, doc in events:
print(doc_id, version, index_doc(doc_id, version, doc))
print(index[42])It prints True for the first event and False for the other two. The index ends with version 7.
Deletes need special care
Deletes are where sync pipelines most often leak bad data.
- A batch job that queries
updated_at > last_runnever sees a deleted row. Use soft deletes (adeleted_atcolumn) so the job can see the change, or run a periodic comparison of ids. - CDC captures deletes natively, but the indexer must turn them into delete requests.
- Delete requests use versions too. Elasticsearch keeps a record of deletes for a short window (the
index.gc_deletessetting, 60 seconds by default). A late, older update that arrives after that window can resurrect a deleted document. Reading current state from the database before indexing, and deleting when the row is gone, closes most of this gap.
Also decide what "deleted" means for visibility. An unpublished, archived, or hidden item usually should leave the index, not stay in it with a flag that every query must remember to filter.
Denormalization and fan-out
Search documents often embed data from several tables, such as a product with its brand name and category path. When a brand is renamed, every product document that embeds it is stale.
- Record which documents depend on which source rows, or query the database for affected product ids.
- Emit one reindex event per affected document, in batches, at lower priority than user-driven updates.
- Keep embedded data small. Embed only what search needs for matching, filtering, and display, and fetch the rest from the database after search returns ids.
A single rename that touches a million documents can flood the pipeline, so rate-limit this kind of fan-out.
Batching and backpressure
Indexing one document per request is slow. Use the bulk API and group events, for example 500 to 1000 documents per request or a few megabytes. Bulk responses report per-item results, so read them. A bulk call can return HTTP 200 while some items failed.
Search engines also apply backpressure. When the cluster is overloaded it returns 429 responses. The indexer should back off with jittered retries and slow its consumption, not drop events. The queue absorbs the burst, and its depth is a useful alert signal.
Failure handling
| Failure | Typical response |
|---|---|
| Search engine unavailable | Retry with backoff. Events accumulate in the queue and drain when the engine recovers. |
| Event refers to a row that no longer exists | Delete the document from the index and acknowledge. |
| Document that the engine rejects (for example, a mapping error) | Retry a few times, then send it to a dead-letter queue and alert. Do not block the partition behind one bad event. |
| Indexer bug wrote wrong data | Fix the code and reindex from the database. |
Ordering matters per entity, not globally. Partition the queue by document id so all events for one product reach the same consumer in order. Versioning still protects you if ordering breaks.
Repair and backfill
Even a well-built pipeline drifts: a bug, a missed event, a manual database fix. Plan for it:
- Run a full backfill job that streams every row from the database and indexes it with its version. You need it for the first load and for every schema change.
- Run a reconciliation job that compares counts, or ids and versions, between the database and the index, and reindexes differences.
- Track indexing lag: the time between a database commit and the document becoming searchable. Alert when it exceeds your freshness target.
These repair tools matter more than the fast path. The fast path decides how stale the index usually is. The repair path decides whether it stays correct over months.
Exercise
An indexer receives the events "product 42 version 9" and then "product 42 version 8" because of a queue retry. It uses external versioning and treats 409 responses as success. What ends up in the index, and why is treating the 409 as success correct?
Show answer
The index keeps version 9. The version 8 request is rejected with a 409 because 8 is not greater than 9. The 409 only means a newer state is already stored, so there is nothing left to do, and retrying it would loop forever for no benefit.
Exercise
Your nightly batch job indexes rows where updated_at is later than the last run. Users report that deleted products still appear in search results. Why does this happen, and name two ways to fix it.
Show answer
A hard-deleted row no longer exists, so the updated_at query can never return it and the job never removes its document. Fixes: use soft deletes with a deleted_at column so the job sees the change and deletes the document, or switch to CDC or an outbox that emits delete events. A periodic id comparison between the database and the index also finds orphaned documents.