Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Distributed Search
& Learning-to-Rank Engine.

Design a distributed search and Learning-to-Rank (LTR) engine with a CDC-driven Write Path (Inverted Index + Feature Store) and a low-latency Read Path (Query Rewriting -> Scatter-Gather -> LTR).
Start the journey7 stages· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, separate near-real-time document indexing (CDC -> Sharded Inverted Index) from high-churn ranking signals (Feature Store) and close the loop with click/conversion telemetry.

TL;DR30-second simplified summary
▾

Debezium CDC feeds immutable 1s Lucene segments across doc_id-partitioned shards. On reads, Query Understanding rewrites typos/synonyms, hedged scatter-gather merges Top-200 candidates, and the LTR Scoring Service ranks them using Feature Store vectors.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Multi-Stage Search & Learning-to-Rank (BM25 + LTR)
Multi-stage search pairs fast inverted-index retrieval (BM25 + Roaring Bitmaps) over 100M+ documents with expensive Learning-to-Rank (GBDT/Neural) reranking on only the top ~200 candidates.
Full walkthrough · 7 stages
01
foundation

Index Sharding Strategy: Document-Partitioned vs. Term-Partitioned.

Why this matters: Choose document-ID sharding to guarantee balanced shard load and fault-tolerant scatter-gather.

Think of Index Sharding Strategy: Document-Partitioned vs. Term-Partitioned as the intuition layer for Design a Distributed Search & Learning-to-Rank Engine: Choose document-ID sharding to guarantee balanced shard load and fault-tolerant scatter-gather.

Term-partitioned indexes (shard 1 holds 'apple', shard 2 holds 'zebra') create severe hot spots on popular terms and require distributed posting-list intersections across nodes. Document-partitioned sharding (hash(doc_id) % N) spreads hot terms evenly, runs intersections locally on each shard, and tolerates single-shard timeouts gracefully.

FOUNDATION

Document-ID vs. Term Sharding

Doc-ID ShardingstorageTerm ShardingriskScatter-GathercomputeStoreavoids cross-node joins

1.Local Intersections: Multi-word queries (`red running shoes`) intersect locally on each shard.

2.Replica Hedging: Each shard has 2-3 replicas for read scaling and hedged failover.

Document-partitioned sharding prevents hot-term bottlenecks and keeps posting intersections local.

02
foundation

Near-Real-Time (NRT) Write Path: CDC -> Analyzer -> Segments.

Why this matters: Keep newly created or updated documents searchable within 1-2 seconds via immutable LSM segments.

Think of Near-Real-Time (NRT) Write Path: CDC -> Analyzer -> Segments as the intuition layer for Design a Distributed Search & Learning-to-Rank Engine: Keep newly created or updated documents searchable within 1-2 seconds via immutable LSM segments.

Inverting a live B-tree on disk for every document edit thrashes IOPS. Instead, CDC events flow through a Tokenizer/Analyzer (lowercasing, stemming, synonyms) into an in-memory inverted buffer that flushes immutable Lucene-style segments every 1 second, while background compaction merges small segments and tombstones deletes.

FOUNDATION

NRT Immutable Segment Pipeline

CDC StreamingressTokenizer / Analyzercompute1s ImmutableSegmentsstorageStoreflushes searchable segments

1.1s Freshness: In-memory buffers make new items searchable in ~1 second.

2.Zero Read Locks: Immutable segments let readers scan lock-free while merges run.

Immutable 1-second segments give near-real-time search freshness without reader-writer locks.

Engineering Decision Framework
Problem
How to implement Design a Distributed Search & Learning-to-Rank Engine without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, separate near-real-time document indexing (CDC -> Sharded Inverted Index) from high-churn ranking signals (Feature Store) and close the loop with click/conversion telemetry.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Distributed Search & Learning-to-Rank Engine experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

Query Rewriting, Spellcheck & Intent Classification.

Why this matters: Prevent zero-result pages caused by typos, synonyms, or missing structured filters.

Think of Query Rewriting, Spellcheck & Intent Classification as the intuition layer for Design a Distributed Search & Learning-to-Rank Engine: Prevent zero-result pages caused by typos, synonyms, or missing structured filters.

Raw user queries frequently contain typos ('iphnoe 15') or implicit attributes ('mens nike shoes under 100'). A Query Understanding stage runs trie/symspell correction, synonym expansion ('sofa' -> 'couch'), and NER intent tagging (brand=Nike, max_price=100) before scattering to index shards.

INTERMEDIATE

Query Understanding & Expansion

User QueryingressSpellcheck + NERcomputeStructured QueryASToutputStoreadds synonym & filter clauses

1.Precision + Recall: Strict filters (`price <= 500`) run as fast Roaring Bitmap masks.

2.Zero-Result Guard: If strict AND returns 0 hits, relax to spell-corrected OR.

Query rewriting converts messy human typing into structured, high-recall shard queries.

04
intermediate

Scatter-Gather Coordinator, Global IDF & Partial Degradation.

Why this matters: Maintain consistent BM25 scoring across shards and return results even if 1 of 32 shards times out.

Think of Scatter-Gather Coordinator, Global IDF & Partial Degradation as the intuition layer for Design a Distributed Search & Learning-to-Rank Engine: Maintain consistent BM25 scoring across shards and return results even if 1 of 32 shards times out.

If Shard 7 is experiencing a disk stall at 25ms, waiting indefinitely breaks the 50ms search SLA. The Coordinator enforces a strict shard timeout, fires hedged requests to replica nodes at 12ms, and uses periodic global IDF synchronization so scores from Shards 1..31 remain comparable even if Shard 7 is skipped.

INTERMEDIATE

Partial-Degradation Scatter-Gather

CoordinatorcomputeHedged ReplicasstoragePartial ResultsoutputStorereturns available Top-K

1.Availability > Perfection: Serving 31/32 shards in 25ms beats timing out the entire search page.

2.Global IDF: Synchronized term frequencies avoid shard-level score skew.

Hedged replicas and graceful partial degradation protect search p99 latency.

05
intermediate

LTR Scoring Service & Feature Store Integration.

Why this matters: Score merged candidates in <15ms using hydrated Feature Store vectors and compiled GBDT/ONNX models.

Think of LTR Scoring Service & Feature Store Integration as the intuition layer for Design a Distributed Search & Learning-to-Rank Engine: Score merged candidates in <15ms using hydrated Feature Store vectors and compiled GBDT/ONNX models.

After merging shard Top-1,000 lists to Top-200, the LTR Scoring Service fetches real-time item/user features from Redis/Aerospike and runs inference using in-memory compiled LightGBM/ONNX trees. Scoring 200 items in vectorized batches keeps CPU inference under 8ms.

INTERMEDIATE

Vectorized LTR Inference

Merged Top-200ingressFeature StorestorageLTR Scoring ServiceoutputStoreoutputs Top-20 ranked SERP

1.In-Process Inference: Embedding compiled ONNX/Treelite models in the scorer avoids RPC hops.

2.Shadow Canary: New LTR models score in shadow mode to verify latency before traffic shift.

In-process compiled GBDT/ONNX inference + batch Feature Store reads keep LTR under 15ms.

06
advanced

Multi-Layer Caching: Query Result, Posting & Feature Caches.

Why this matters: Absorb head-query Zipfian traffic spikes without hitting shards or LTR models.

Think of Multi-Layer Caching: Query Result, Posting & Feature Caches as the intuition layer for Design a Distributed Search & Learning-to-Rank Engine: Absorb head-query Zipfian traffic spikes without hitting shards or LTR models.

Search queries follow a steep Zipfian distribution: the top 5% of head queries ('iphone', 'laptop') account for 40%+ of QPS. Caching serialized Top-20 SERPs in Redis for 60 seconds (keyed by hash(normalized_query, filter_mask, user_segment)) plus OS page-cache pinning for hot posting lists cuts cluster CPU by half.

ADVANCED

Zipfian SERP & Posting Cache

Head Query (40%QPS)ingressRedis SERP CachecacheShard OS Page CachestorageStorefalls through on long-tail miss

1.Segment Scoping: Never serve personalized/ACL results from an unsegmented cache key.

2.Cache Stampede: Use singleflight coalescing on hot-key expiration.

Segment-scoped SERP caching absorbs Zipfian head queries while long-tail misses hit warm shards.

07
advanced

Click/Conversion Telemetry & Feature Store Feedback Loop.

Why this matters: Feed real-time user clicks, add-to-carts, and conversions back into both the Feature Store and LTR training.

Think of Click/Conversion Telemetry & Feature Store Feedback Loop as the intuition layer for Design a Distributed Search & Learning-to-Rank Engine: Feed real-time user clicks, add-to-carts, and conversions back into both the Feature Store and LTR training.

Every SERP impression and click streams to Kafka. A Flink streaming job updates rolling 1-hour and 24-hour item CTR/conversion counters in the Feature Store within seconds (for trending-item boosts), while daily Parquet snapshots join impressions with debiasing propensities to retrain the LambdaMART model.

ADVANCED

Closed-Loop Telemetry & Feature Update

User Clicks / CartsingressFlink Rolling WindowstreamParquet TrainingLakestorageStorelogs debiased training labels

1.Trending Boost: 1-hour Flink CTR updates let viral items rise within minutes.

2.Data Integrity: Joining by `query_id` guarantees exact feature-at-serve-time logging.

Streaming telemetry simultaneously powers real-time Feature Store updates and offline LTR retraining.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why do distributed search engines partition inverted indexes by `doc_id` rather than by `term`?

Recommended Learning Flow