Designing an information retrieval system means turning a body of documents and a stream of user queries into a ranked list that puts the right answer near the top. The core recipe is stable regardless of scale: define what “relevant” means for your users, choose an index structure that fits your corpus, pick a retrieval method (lexical, vector, hybrid, or a re-ranker on top), then measure quality against a test set before and after every change. The hard part isn’t the algorithm—it’s matching the architecture to your data, latency budget, and what your users actually accept as a good result.
This guide walks through the design decisions in the order you’ll face them, from scoping the problem through deploying and monitoring. It’s written for someone who has to make real trade-offs, not just publish a demo.
Start With the Query and the Corpus, Not the Model
Before writing a line of code, answer three questions in writing.
Who asks what, and what does “good” look like to them? An e-commerce search box, an internal document search, a legal discovery tool, and a chatbot’s retrieval layer all use different relevance. For product search, exact matches on model numbers matter enormously and users expect results in milliseconds. For a research assistant, semantic recall of a paraphrased idea matters more than keyword hits. Write down 20–50 realistic queries your users will type, along with the documents you’d expect at rank 1–3 for each. This set becomes your evaluation reference—not a formal benchmark, but a working test you’ll grow.
What is the corpus, exactly? Record the document count, average length, language mix, media types (plain text, PDFs, tables, images), and how frequently it changes. A 10,000-document knowledge base fits comfortably in memory with a simple index. A billion web pages requires distributed infrastructure and careful sharding. The update rate matters too: a corpus that changes hourly needs an incremental indexing path, while a static archive can be reindexed in batch.
What are the hard constraints? Typical enterprise expectations are sub-200 ms search latency, but that varies by context. Note your budget for compute, whether results must be filtered by permissions per user, and any compliance rules about where data can live. These constraints eliminate whole classes of design early.
The mistake at this stage is jumping to a fashionable embedding model before knowing whether your users need exact matching, fuzzy matching, or semantic recall. Each points toward a different architecture.
Build the Ingestion and Preprocessing Pipeline First
Retrieval quality is capped by what goes into the index. A brilliant ranking model fed garbage text produces garbage results, and preprocessing bugs are notoriously hard to trace once documents are indexed.
Collection. Pull documents from every source with a documented schema: file stores, databases, web crawls, APIs. Attach stable identifiers and source metadata, plus an ingestion timestamp. Normalization at this stage—consistent encoding (UTF-8), unified date formats, stripped boilerplate—prevents silent mismatches later.
Parsing and segmentation. Extract clean text from PDFs, HTML, Office files, and images (with OCR where needed), then split long documents into retrievable units. For most text systems, chunk sizes of roughly a paragraph to a few hundred words work well; overlap between adjacent chunks (say 10–20%) helps queries that straddle boundaries. The right chunk size is empirical: test it. Too small and you lose context; too large and you dilute the signal and waste index space.
Cleaning. Remove navigation chrome, repeated headers and footers, and near-duplicate documents. Deduplication matters more than people expect: copies of the same page crowd out diversity in the top-k results.
Enrichment. Consider language detection, entity extraction, and topical tags if your users filter by them. Metadata is what lets filters (date ranges, departments, product categories) narrow the candidate set before ranking, which is both faster and often more accurate than ranking everything.
Validation check. After the pipeline runs, sample 50 documents and confirm the extracted text is readable, the metadata is populated, and chunk counts look sane. A quick spot check catches encoding errors and empty extractions before they poison the index.
Choose an Index and Retrieval Approach That Fits the Job
Two broad families dominate, and most production systems blend them.
Inverted index (lexical retrieval). An inverted index maps each term to the documents containing it, enabling fast exact-term lookup with standard ranking functions like BM25, which weighs term frequency against document length and rarity. It excels at precise queries—names, codes, jargon, quoted phrases—and is cheap to run. Its weakness is vocabulary mismatch: a user searching “how do I cancel my subscription” won’t match a doc titled “Terminating recurring billing” unless terms overlap.
Vector index (dense retrieval). Documents and queries are converted into embedding vectors, and similarity is computed by nearest-neighbor search with structures like HNSW or IVF that keep search sublinear on large corpora. This captures paraphrase and conceptual similarity, so “cancel subscription” and “terminate recurring billing” land close together. The costs are real: embedding every document and query requires a model and compute, the index is memory-hungry, and vectors are opaque—hard to debug when they go wrong. Approximate nearest-neighbor search also introduces recall loss that you must measure, not assume.
Sparse learned representations (like SPLADE-style models) sit between the two, expanding queries and documents with learned term weights while keeping an inverted index. They’re worth evaluating if exact matching matters but vocabulary mismatch is hurting you, though they add model complexity.
The practical default is hybrid retrieval. Run a lexical query and a vector query in parallel, then merge results, usually with Reciprocal Rank Fusion (RRF): each document’s fused score is the sum over result lists of 1/(k + rank), where k is a small constant like 60 (the value used in the widely cited RRF paper). RRF is appealing because it needs no score normalization across two very differently scaled systems—it just combines ranks. For a 100,000-document corpus, a workable starting point is lexical top-100 and vector top-100, fused to top-50, then re-ranked. Tune the candidate depths against your evaluation set; deeper candidates cost latency and often yield diminishing returns.
| Approach | Strength | Weakness | Typical fit |
|---|---|---|---|
| Inverted index + BM25 | Fast, exact, interpretable, cheap | Vocabulary mismatch | Product catalogs, code search, compliance lookup |
| Dense vectors + ANN | Paraphrase and concept matching | Cost, opacity, recall loss from approximation | Q&A, support content, exploratory search |
| Hybrid + fusion | Covers both; robust baseline | Two systems to operate | Most general-purpose search |
| Hybrid + re-ranker | Best accuracy per query | Highest latency and cost | High-value queries where top-3 precision pays |
Add Query Understanding Without Overbuilding It
Raw queries are messy. A modest amount of query processing pays off, but beyond a point it creates fragility.
Normalization and spelling. Lowercase, strip punctuation where appropriate, and handle common typos. Light stemming or lemmatization helps lexical matching (“running” matches “run”). Be careful with aggressive stemming on codes and product identifiers—it can corrupt them.
Tokenization for mixed content. Split camelCase and alphanumerics consistently so that “iPhone15Pro” is findable as “iPhone 15 Pro” and vice versa.
Stopword handling. Modern ranking functions handle frequent words reasonably; removing them can hurt phrase queries. Treat stopword removal as optional rather than default.
Query expansion and rewriting. Synonym lists, acronym dictionaries, and learned query rewriting can rescue recall. Keep expansion conservative—over-expansion drifts results away from what the user meant. If you use a language model to rewrite queries, evaluate it on your query set; improvements on benchmarks don’t always transfer to your domain.
Filters, intent, and routing. Extract obvious filters—dates, categories, authors—from the query or from UI state, and apply them before ranking. If you have distinct content types, route queries by intent (e.g., navigational product queries to catalog search, question-form queries to a document index). Routing logic should be simple and testable.
Rank, Re-rank, and Blend Signals
First-stage retrieval casts a wide net; ranking decides what the user sees first. A layered design works best.
Baseline scoring. Start with BM25 on the lexical side and cosine similarity on the vector side; combine via fusion. Resist the urge to hand-tune weights before you have an evaluation set. Once you do, tune fusion parameters and candidate depths systematically.
Cross-encoder re-ranking. A cross-encoder model scores each query–document pair jointly, which is far more accurate than comparing independent embeddings but too slow to run over the whole corpus. Apply it to the top 25–100 candidates from the first stage. It’s the highest-leverage accuracy improvement for most systems, at a latency cost you should measure. Expect tens of milliseconds per batch of candidates on GPU hardware; on CPU, it may be too slow for interactive search at high query rates.
Business and freshness signals. Blend in recency, popularity, document authority, or user permissions. These are often as important as textual relevance in real deployments—a slightly less on-topic but current policy page beats a perfect but obsolete one. Weight them deliberately, and log their contribution so you can explain rankings when asked.
Diversity. For broad queries, near-duplicate results waste the top-k slots. MMR-style reranking (maximal marginal relevance) trades a little relevance for variety by penalizing documents similar to ones already selected. Use it when the corpus has heavy duplication.
Check. For ten sample queries, read the top-5 results by hand. If you can’t articulate why each result is there, inspect the score components before tuning further.
Evaluate With a Small, Honest Test Set
Retrieval evaluation has well-established measures, and using them beats vibes.
Precision@k: fraction of the top k results that are relevant. Matters when slots are scarce, like a search sidebar showing five results. Recall@k: fraction of all relevant documents appearing in the top k. Critical when missing something is costly, such as compliance or legal search. Mean Reciprocal Rank (MRR): average of 1/rank of the first relevant result. Well suited to navigational queries with one right answer. NDCG@k: normalized discounted cumulative gain; rewards relevant results appearing higher and supports graded relevance (perfect, partial, irrelevant).
Build your test set from real queries—ideally from logs—and have a human label the top results for each. Fifty to a few hundred queries is enough to detect meaningful differences; more is better. Re-run the whole suite after every change to indexing, chunking, fusion weights, or the re-ranker. Record the version and date with each score, because metrics drift as the corpus grows.
A worked example of reading these numbers: suppose a change lifts Recall@20 from 0.72 to 0.80—eight points—while NDCG@10 stays flat. That suggests the new method finds relevant documents that were previously missed, but doesn’t rank them high. The next step isn’t “revert”; it’s investigate whether the re-ranker is undervaluing them. Percentage points and percent changes are different things; state which you mean.
Finally, sanity-check for position bias if you ever learn from click logs: users click what’s on top regardless of quality, so raw clicks overstate top-ranked documents’ relevance. Pairwise comparisons or randomized result interleaving avoid this trap.
Tune Latency, Cost, and Scale Together
Quality, latency, and cost trade against each other constantly, so design for the budget you actually have.
Latency budget. Break the target down: query parsing (a few ms), first-stage retrieval (tens of ms for both lexical and vector), fusion (negligible), re-ranking (tens of ms), response assembly. If you’re over budget, the usual culprits are deep candidate lists, large embedding dimensions, and CPU-only re-ranking.
Index memory. Dense vectors are the biggest cost driver: a million 768-dimension float32 vectors occupy roughly 3 GB before index overhead. Quantization (float16 or int8) and dimensionality reduction cut this significantly at some recall cost—measure the recall loss rather than assuming it’s acceptable.
Sharding and replication. Beyond a few million documents, partition the index by shard and query in parallel, merging top-k results. Keep document IDs consistent across shards so fusion and deduplication work.
Caching. Cache frequent queries and their results, and consider caching embeddings for queries you’ve seen. Respect freshness requirements—a stale cache on a support search page can surface obsolete answers.
Incremental updates. Decide how new documents enter the index: scheduled batch reindex, near-real-time incremental inserts, or a hybrid. Test that deletions actually remove documents from all result paths—a classic failure mode is a deleted document surviving in a vector index while disappearing from the lexical one.
Stop condition. If latency targets require architectural changes beyond these levers—like moving from a single node to a distributed cluster—validate capacity with realistic query volume before committing. If you lack the expertise to operate a distributed index safely, that’s a signal to evaluate a managed search service rather than build one.
Deploy, Monitor, and Improve in a Loop
Retrieval systems decay silently. Documents age, vocabulary shifts, and user expectations change. Instrument the system from day one.
Log everything needed to reproduce a result: query text, normalized query, filters applied, candidate counts, fused scores, re-ranker scores, and the final ranking. Without this, debugging a bad result means guessing.
Watch quality proxies. Zero-result queries, result click-through, reformulation rate, and abandonment tell you where retrieval fails even when formal metrics aren’t available. Zero-result rate is the cheapest early warning.
Rebuild the evaluation set periodically. Sample new queries from recent logs, label them, and keep the benchmark current. A test set from two years ago measures relevance to a different user population.
Version the pipeline. Chunk boundaries, embedding model versions, fusion constants, and re-ranker weights all affect results. Store a configuration fingerprint with each index build so a regression can be traced to a specific change.
Roll out changes gradually. Compare a new ranking model against the current one on live traffic, ideally with interleaving or a small A/B test, before full switchover. Offline metrics are a filter, not proof.
A Concrete Starting Configuration
If you’re building your first system and want a defensible default for a corpus under a million documents, consider this stack:
1: Chunk documents into roughly 200–400 word passages with modest overlap. 2: Index with an inverted index using BM25 and, in parallel, embed chunks with a general-purpose sentence embedding model into a vector index using HNSW. 3: At query time, normalize and tokenize, run both retrievers at top-100, fuse with RRF (k = 60), and take the top 50. 4: Apply a cross-encoder re-ranker to those 50 and present the top 10, blending in recency and permission filters as needed. 5: Measure Precision@10, Recall@50, and NDCG@10 on 100 labeled queries; iterate on chunk size, fusion depth, and re-ranker before touching anything else.
This configuration is a starting point, not an optimum. Every parameter above should be validated against your own queries and constraints—and the evaluation can be a simple spreadsheet comparing metrics against a labeled query set, without much tooling. The gap between a demo and a production system is almost entirely made of that evaluation loop, honest latency measurement, and a pipeline you can trust to put clean text into the index.
Scale up only after the basics are measurable. A small system with a real evaluation set will outperform an elaborate one tuned by intuition, because it tells you when you’re wrong.