Route queries across shards, merge local candidates and make partial failure visible instead of presenting an incomplete answer as complete.
Retrieval shards: fanout, replica lag and incomplete top-K results
Split a corpus without splitting the answer contract
A sharded index places different documents on different serving units. A coordinator asks each relevant shard for local top-K candidates and merges them into a global top-K. This distributes storage and search work, but a query that fans out to every shard can become slower as the shard count rises. Tenant-aware or time-aware routing may reduce fanout when its key is a real query constraint. Routing by guessed topic is dangerous: one mistaken guess can make the answer-bearing shard invisible. Federated retrieval handles unlike sources; shard fanout concerns partitions of one logical index.
Merge with stable identity
Each shard returns a score, a stable passage ID, its index generation and the applied authorization scope. The coordinator must compare scores only when every shard uses the same model, scoring rules and compatible index generation. It then sorts by score and a deterministic tie key, deduplicates repeated passages, and clips to the requested count. One shard returning K candidates is sufficient for a global top-K when scores are comparable and each shard has the same eligibility filter; returning fewer can discard a candidate that belongs in the global result.
Replicas improve availability, not automatic freshness
A replica can answer a read while a primary is unavailable, but it may lag behind an update or permission withdrawal. Query routing should select only a replica that has applied the required source offset and revocation watermark; otherwise wait within budget, use an eligible replica, or fail closed. A generic 'healthy' check does not establish the freshness needed by this query. Index watermarks state what each serving copy has actually applied.
Treat a missing shard as missing evidence
If one of four required shards times out, the coordinator cannot claim that its top result is the best document in the corpus. For low-stakes exploratory search it may return explicitly labeled partial results; for an answer requiring complete policy coverage, abstention or retry is safer. Log shard IDs, generations, missing partitions, timeout budgets and candidate counts. Never hide a partial result behind a normal 200 response without a machine-readable completeness field. Evidence-bound answers should refuse to synthesize a confident claim from a known incomplete search.
Size and test the fanout budget
More small shards increase coordinator work, per-shard overhead and the chance that at least one request misses its deadline. Fewer large shards can create memory pressure and longer recovery. Benchmark representative query slices as shard count, replica count and local candidate window change. Inject a slow shard, one stale replica and a node loss; verify that global ranking is stable when complete and that the incomplete path reports precisely what was missed. Retrieval traces should make this diagnosis possible without replaying private query text.
Worked contract
from dataclasses import dataclass
@dataclass(frozen=True)
class ShardReply:
shard_id: str
generation: int
candidates: tuple[tuple[str, float], ...]
def merge_complete(replies: list[ShardReply], required_shards: set[str],
generation: int, limit: int) -> list[tuple[str, float]]:
if limit < 1 or {reply.shard_id for reply in replies} != required_shards:
raise ValueError("incomplete shard set")
if any(reply.generation != generation for reply in replies):
raise ValueError("mixed index generations")
best: dict[str, float] = {}
for reply in replies:
for passage_id, score in reply.candidates:
best[passage_id] = max(best.get(passage_id, float("-inf")), score)
return sorted(best.items(), key=lambda item: (-item[1], item[0]))[:limit]
responses = [ShardReply("north", 47, (("pump-p47", .82),)),
ShardReply("south", 47, (("pump-p48", .71),))]
assert merge_complete(responses, {"north", "south"}, 47, 1) == [("pump-p47", .82)]
try:
merge_complete(responses[:1], {"north", "south"}, 47, 1)
except ValueError:
pass
else:
raise AssertionError("missing shard was accepted")Performance and operating cost
With S shards each returning at most K candidates, this simple merge reads O(SK) entries, stores O(SK) unique IDs and sorts them in O(SK log(SK)) time. A bounded heap can reduce ranking work when SK is large. Network latency is controlled by the slowest required shard, not the average shard; replicas consume extra storage and indexing capacity. Reducing fanout is useful only if routing cannot exclude eligible evidence.
Common Mistakes
- Treating a missing shard as an empty shard.
- Merging scores from different model or index generations as if comparable.
- Reading from a stale replica after a permission withdrawal.
- Increasing shard count without measuring coordinator and tail-latency costs.
Validation drill
Partition 59 documents across three shards. Remove one reply and delay another, then verify complete top-K ordering, generation checks and explicit partial-result behavior under a fixed latency budget.
