Sub topic 8
Living with eventual consistency
This chapter assumes you know basic SQL, REST APIs, and message queues. It also assumes you know what replication means. You should have read the previous chapter on syncing data from the source of truth. The goal is to decide what staleness your product can tolerate and to build the search path so that staleness does not become a visible bug.
Why the index is always a little behind
Eventual consistency means that if no new writes arrive, the index will eventually match the primary database. For a short time after a write, the two can disagree. A search service is almost always a derived copy of the data, so it cannot be strictly consistent with the database.
Delay enters at several points:
- Capture. A change must be noticed. Change data capture (reading the database log) usually takes milliseconds to seconds. Polling an
updated_atcolumn takes as long as the polling interval. - Transport. A queue or stream holds the event until a consumer reads it. A backlog after an outage can add minutes or hours.
- Indexing. The consumer sends the document to the search engine, often in batches. Batches trade latency for throughput.
- Refresh. Engines built on Lucene, such as Elasticsearch and OpenSearch, write new documents into an in-memory buffer first. A document becomes searchable only after a refresh creates a new searchable segment. The default refresh interval is about one second.
- Replica propagation. Replicas apply the same change shortly after the primary shard. Two searches in a row can hit different copies and return different results.
Each hop is a place where the lag can grow. The total is the number users feel, so measure it end to end.
Measure freshness instead of guessing
Define an indexing lag: the time between the database commit and the moment the document appears in search results. Track it as a metric with percentiles, not an average. A p50 of 2 seconds and a p99 of 4 minutes describe very different products.
Two cheap ways to measure it:
- Carry the source
updated_attimestamp in every indexed document. The indexer logsnow - updated_atafter each successful write. - Run a canary. A scheduled job writes a marker row, polls the search engine until it appears, and records the elapsed time. This also catches a stalled pipeline when no real traffic is changing.
Set a freshness target for each feature. Product catalog search can usually tolerate tens of seconds. A "my recent orders" search cannot.
Make updates idempotent and ordered
Pipelines deliver events at least once and sometimes out of order. If event version 6 arrives after version 7, a naive indexer overwrites newer data with older data. The index stays wrong until the next change to that row, which may never come.
The fix is to index by the database primary key and pass the source version as an external version. The engine rejects any write whose version is not higher than the stored one.
PUT /products/_doc/42?version_type=external&version=7
{
"name": "Trail running shoes",
"category": "footwear",
"price": 89.0,
"in_stock": true
}Replaying the same event is harmless, because version 7 against stored version 7 is rejected as a conflict. Your indexer should treat that conflict as success and move on. Use a row version column or a monotonically increasing sequence from the database log. Wall-clock timestamps can tie or drift, so avoid them as versions.
Deletes need the same care. If you delete a document and then a late update for the same ID arrives, the update can resurrect it. Either keep a tombstone (a deleted marker with a version) for a retention window, or index a deleted flag and filter on it.
Read-your-writes: the most visible symptom
The complaint users report most often is: "I saved the item and it is not in the search results." You have several options, ordered here from cheapest to most costly:
| Technique | How it works | Cost |
|---|---|---|
| Accept it and tell the user | Show "Changes may take a few seconds to appear." | None, but weak for interactive flows |
| Update the UI locally | After a save, the client adds the item to the list it already shows | Client logic, can diverge from server results |
| Route to the database | For a short window after a user's write, serve that user's list view from the database | More database load, two code paths |
| Wait for refresh | Index synchronously and request that the call return after the next refresh (`?refresh=wait_for` in Elasticsearch) | Slower writes, couples the write path to the search engine |
| Forced refresh | `?refresh=true` makes the document searchable at once | Creates many small segments, hurts throughput. Avoid in production paths |
Most systems combine the second and third. Search stays asynchronous for the general case, and the specific screens where users just made a change get a direct path.
Hydrate results from the source of truth
Stale index data causes a second problem: results that no longer match reality. A product may be deactivated, deleted, or repriced while the index still shows the old state. A common defense is to use the search engine only to find IDs and ranking order, then load the display fields from the database or a cache.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute(
"CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL, active INTEGER)"
)
db.executemany(
"INSERT INTO products VALUES (?, ?, ?, ?)",
[
(1, "Trail running shoes", 89.0, 1),
(2, "Road shoes", 120.0, 0), # deactivated after it was indexed
(3, "Red jacket", 60.0, 1),
],
)
def hydrate(hit_ids):
"""Load current rows for ranked IDs, drop missing or inactive ones, keep order."""
if not hit_ids:
return []
marks = ",".join("?" * len(hit_ids))
rows = db.execute(
f"SELECT id, name, price FROM products WHERE active = 1 AND id IN ({marks})",
hit_ids,
).fetchall()
by_id = {row[0]: row for row in rows}
return [by_id[i] for i in hit_ids if i in by_id]
# IDs as returned by the search engine, best match first.
# 2 is inactive and 99 was deleted; neither appears in the output.
print(hydrate([2, 1, 3, 99]))This prints the current rows for IDs 1 and 3, in search order. The price shown is always the database price, so a stale index cannot display a wrong price.
Hydration has costs:
- It adds a database read per results page. A cache keyed by ID reduces this.
- A page of 10 hits can shrink to 7 after filtering. Fetch a few extra hits, or accept short pages.
- Filtering in the index can still be stale, so a deactivated product may be missing from a filtered query it should appear in, or the reverse. Hydration fixes display, not matching.
Failure modes and how to detect them
| Failure | What users see | Detection | Recovery |
|---|---|---|---|
| Consumer stalled or crashed | New items never appear | Canary timeout, queue depth growing | Restart the consumer and let it catch up. Alert on lag |
| Poison event | Pipeline blocks on one bad message | Same offset retried repeatedly | Send it to a dead-letter queue and continue |
| Lost events | Permanent gaps for some documents | Periodic reconciliation counts differ | Re-send the affected documents, or reindex |
| Out-of-order writes without versions | Old data overwrites new | Spot checks show index older than database | Add external versioning, then repair |
| Dual write drift | Database and index disagree after partial failures | Reconciliation | Move to change data capture or an outbox table |
Reconciliation is the safety net. A scheduled job compares IDs and versions between the database and the index, either over the whole dataset in slices or over rows changed in the last day. Anything that differs is re-indexed. Even a well-built pipeline loses events occasionally, and this job closes the gap without a full rebuild.
Choosing a consistency stance
Decide per feature, and write the decision down in the design:
- List the reads. For each search screen, state how fresh the results must be.
- Set a lag budget. For example, p99 under 30 seconds for catalog search.
- Pick the compensation. Choose local UI update, database routing, hydration, or nothing.
- Add the metrics. Track lag percentiles, queue depth, and reconciliation mismatches.
Exercise
A user edits a product title and immediately searches for the new title. The product is missing from the results, but appears a few seconds later. Name two causes in the pipeline and one low-cost mitigation that does not make writes depend on the search engine.
Show answer
Two causes: the change event is still in the queue or being batched by the indexer, and the engine has not yet refreshed, so the indexed document is not searchable. Replica lag is also acceptable. A low-cost mitigation is for the client to update its own displayed list after the save, or to serve that user's search from the database for a short window after their write. Both keep the write path independent of the search engine.
Exercise
Your indexer receives an update for product 42 with version 6 after it has already indexed version 7. What should happen, and which indexing option provides this behavior?
Show answer
The version 6 write must be rejected so the newer data stays. Indexing with an external version (version_type=external and the database version) provides this. The indexer should treat the resulting version conflict as a successful no-op, not as an error to retry.