Sub topic 12
Failure modes and fallback behavior
This chapter assumes you know how the search service sits next to the primary database (see the earlier chapters on syncing and consistency), and that you are comfortable with timeouts, retries, and message queues. The goal is to decide, before an incident, what your product does when search is slow, wrong, or gone.
Why search needs its own failure plan
A search service is a derived system. The primary database is the source of truth, and the index is a copy built for fast reads. That has two consequences for reliability.
- The index can be lost and rebuilt. Losing it hurts availability, but it should not lose data.
- Search often sits on the critical path of the page. A product listing, a help center, or an order lookup may all call search before they render anything.
So you need to answer two questions for every feature that uses search. How bad is it if results are missing, stale, or slow? And is there a cheaper way to answer the same request?
The main failure modes
| Failure | What users see | Typical cause |
|---|---|---|
| Search unavailable | Errors or an empty page | Cluster down, network partition, bad deploy |
| Search slow | Spinners, timeouts | Expensive query, hot shard, garbage collection, overload |
| Partial results | Some documents missing | A shard is unavailable and the query tolerates it |
| Stale results | Old prices, deleted items still shown | Sync lag, failed indexing, consumer stuck |
| Wrong results | Irrelevant or missing matches | Bad mapping, analyzer change, broken reindex |
| Index corrupted or lost | Everything above, for all queries | Disk failure, accidental delete, bad snapshot restore |
The first three are availability problems. The last three are correctness problems. Availability problems are loud, because monitoring catches them. Correctness problems are quiet, because the service responds with HTTP 200 and the results are simply wrong. Plan for both.
Partial results
Most engines can return results when some shards fail. In Elasticsearch-style engines the response includes a flag such as timed_out and a _shards section with a count of failed shards. If your client ignores those fields, users silently get an incomplete list. Decide per feature whether partial results are acceptable. A "recent articles" list can tolerate them. A compliance search that must find every matching record cannot.
Slow queries and overload
A search cluster rarely fails all at once. It usually degrades first. Common triggers include:
- Leading wildcard queries and very large
sizevalues. - Deep pagination, where each shard must sort and return
from + sizehits. - Aggregations over high-cardinality fields.
- A reindex or bulk import competing with live queries for CPU and disk.
Slow requests hold connections and threads. Callers retry, which adds more load, which makes the cluster slower. This is a retry storm, and it turns a small slowdown into an outage.
Protecting the caller
Fallbacks only work if the caller notices trouble quickly. Four mechanisms do most of the work.
- Timeouts. Set a short client timeout on search calls, based on what the page can tolerate. If a search normally takes 50 ms, a 500 ms to 1 s timeout is reasonable. Also set the engine's own query timeout so the cluster stops work the client has already abandoned.
- Limited retries. Retry only idempotent reads, at most once or twice, with exponential backoff and jitter. Never retry in a tight loop.
- Circuit breaker. After a threshold of failures or slow responses, stop calling search for a cool-down period, then let a few probe requests through. This protects the cluster while it recovers and gives users a fast fallback instead of a slow error.
- Bulkheads. Limit how many concurrent search calls one feature can make, so a slow search cannot use up every worker thread in your service.
Here is a small circuit breaker with a fallback wrapper. It is a sketch you can run as is.
import time
class CircuitBreaker:
def __init__(self, max_failures=3, reset_after=10.0):
self.max_failures = max_failures
self.reset_after = reset_after
self.failures = 0
self.opened_at = None
def allow(self):
if self.opened_at is None:
return True
# Half-open: allow a probe after the cool-down.
return time.monotonic() - self.opened_at >= self.reset_after
def record_success(self):
self.failures = 0
self.opened_at = None
def record_failure(self):
self.failures += 1
if self.failures >= self.max_failures:
self.opened_at = time.monotonic()
breaker = CircuitBreaker()
def search_with_fallback(query, search_fn, fallback_fn):
if not breaker.allow():
return fallback_fn(query), "fallback"
try:
result = search_fn(query)
breaker.record_success()
return result, "search"
except Exception:
breaker.record_failure()
return fallback_fn(query), "fallback"
def failing_search(q):
raise TimeoutError("search timed out")
def db_fallback(q):
return [f"db result for {q}"]
for _ in range(5):
print(search_with_fallback("shoes", failing_search, db_fallback))The function returns a label alongside the result. Keep that label. You will want it for metrics and, in some cases, for telling the user that results are limited.
Choosing a fallback
A fallback is a degraded answer that is better than an error. The right one depends on the feature.
| Fallback | Works well for | Cost or risk |
|---|---|---|
| Database query (`LIKE`, prefix match, or the database's full-text feature) | Small catalogs, admin screens | Poor ranking, slow on large tables, can overload the database |
| Cached results for popular queries | Public search with repeated queries | Stale, and misses on long-tail queries |
| Static or precomputed lists (popular, recent, category pages) | Storefronts, content sites | Not tailored to the query |
| Secondary search cluster or cross-region replica | Business-critical search | Cost and extra operations |
| Clear error with retry option | Features where wrong answers are worse than none | Visible downtime |
Two warnings apply to the database fallback.
Tell the user when results are degraded. A short notice such as "Showing basic results" avoids confusion when ranking or filters look different.
Handling stale and missing data
When the sync pipeline fails, the search service stays up but drifts away from the source of truth. Defend against this with these practices.
- Dead letter queue. Events that fail indexing repeatedly go to a separate queue for inspection and replay. Do not drop them and do not block the main queue forever.
- Idempotent, versioned writes. As shown earlier with external versioning, a replayed or late event cannot overwrite newer data.
- Lag metrics. Track the time between a change in the database and its appearance in the index. Alert on a threshold that matches the product's freshness promise.
- Re-check at read time. For fields that must be correct, such as price or availability, fetch the current value from the database for the page of results you are about to show. Search decides which items to show, and the database decides what is true about them.
- Reconciliation job. A periodic job compares IDs and update timestamps between the database and the index, and repairs differences. It catches events that were lost without any error being recorded.
The second-to-last point also handles deletes. A deleted product may still be in the index for a short time. Loading it from the database at render time lets you drop the missing rows instead of showing a dead link.
Recovering the index
Because the index is derived, recovery has two paths. Choose based on how long you can be without it.
- Restore from a snapshot. Engines can take snapshots to object storage. Restoring is fast, but the snapshot is only as fresh as its last run. After restoring, replay events from the queue or the database from the snapshot time onward to catch up.
- Rebuild from the source of truth. Read every record from the database and bulk index it, using the same reindexing process described in the previous chapter. This is slower, and it competes with the database for read capacity. Do it from a replica when you can.
Test both. A snapshot you have never restored is a hope, not a backup. A rebuild that takes 14 hours is a very different recovery plan from one that takes 20 minutes, and you should know which one you have.
For large indexes, keep an alias that points at the live index. You can build a fresh index beside it and switch the alias when it is ready, so recovery does not require taking search offline.
Replication and cluster-level safeguards
Replicas protect against node loss, not against bad data. If a bad deploy writes wrong values, every replica holds them. Pair replication with the following.
- At least one replica per shard, placed in separate failure zones.
- Enough spare capacity that losing one node does not push the rest past their limits.
- Disk watermarks and alerts. Many engines make shards read-only when disks fill, and writes then fail while reads continue. That is a quiet failure, since the cluster looks healthy and the sync pipeline silently backs up.
- Limits on query cost, such as maximum result window, maximum bucket count, and query timeouts.
What to monitor
Monitor from the user's side and from the cluster's side.
- Search latency at the 50th, 95th, and 99th percentiles, and error rate.
- Rate of fallback use, using the label returned earlier.
- Rate of queries returning zero results. A sudden rise often signals a broken mapping or a stale index.
- Indexing lag, dead letter queue depth, and counts of failed shards.
- Document count in the index compared with the source table.
Alert on symptoms first (latency, errors, lag), then on causes (disk, heap, queue depth).
Design checklist
- For each feature, state whether stale, partial, or missing results are acceptable.
- Set timeouts, limited retries, and a circuit breaker on every search call.
- Pick a fallback per feature and cap the load it can put on the database.
- Make sync idempotent, versioned, and observable, with a dead letter queue and a reconciliation job.
- Rehearse a snapshot restore and a full rebuild, and record how long each takes.
- Alert on user-visible symptoms.
Exercise
Your product page calls search to list related items. Search starts responding in 8 seconds instead of 80 ms, and the database CPU then spikes shortly after. Give two likely causes of the database spike and two changes that prevent it.
Show answer
Likely causes: (1) the fallback path sends every failing or timed-out search to the database, so database load grows with search traffic; (2) callers retry timed-out requests, and each retry may also hit the fallback. Prevention: add a circuit breaker so most requests skip search and go straight to a cheap fallback, and rate-limit or cap the database fallback (smaller page size, fewer fields, or a cached or precomputed list instead of a live query). Shorter timeouts with limited retries and backoff also help.
Exercise
Search returns HTTP 200 with fewer results than expected, and no alert fires. Name two possible reasons and the signal that would have caught each.
Show answer
One reason is a failed shard returning partial results, which is caught by checking the shard failure count or timed_out flag in the response and alerting on it. Another is a stuck sync consumer that leaves the index stale or missing new documents, which is caught by an indexing lag metric, dead letter queue depth, or a document count comparison between the index and the database. A rise in zero-result queries could also point to either cause.