Building a Search Engine for Social Media Posts
System DesignModel answerLast updated
Design a search system that indexes post content, handles include/exclude queries, and ranks matches by term frequency across distributed infrastructure.
You're building the search infrastructure for a social media platform. Users need to search through post content using text queries and receive relevant results ordered by match quality.
Your system must handle:
- Efficiently locating posts containing specific terms without scanning the entire corpus
- Query logic that requires certain terms while forbidding others (e.g., must contain "coffee" but exclude "decaf")
- Ranking matched posts by how frequently query terms appear in each document
What You Need to Design
Describe the complete architecture including:
- How newly created or modified posts become searchable
- How search queries are processed and answered
- Deep technical details on indexing, query execution with exclusions, and frequency-based ranking
Questions to Consider
Scale and performance:
- What are your assumptions about corpus size, write rate, read rate?
- What latency target are you designing for?
- How quickly must new posts appear in search results?
Search semantics:
- How do you tokenize and normalize text (case, punctuation, stemming)?
- Are query terms individual words or can they be phrases?
- With multiple inclusion terms, do you require all or any?
- Can a query contain only exclusion terms with no required terms?
Access control:
- Must search respect post visibility and user permissions?
Part 1: Term-to-Document Index
Explain how you locate all posts containing a given term without full corpus scans. Cover index construction, maintenance as posts change, storage requirements, and horizontal partitioning.
Part 2: Exclusion Logic
Support queries with both required and forbidden terms. Address evaluation order, performance when excluded terms are common, correct pagination behavior, and edge cases like unknown terms.
Part 3: Frequency-Based Ranking
Return results ordered by relevance measured through term frequency. Explain score computation for multi-term queries, efficient top-K selection without full sorts, result merging across machines, pagination consistency, and limitations of raw frequency counts.
Hints
Hint 1
Build an inverted index mapping each term to the list of documents containing it, with frequency metadata.
Hint 2
Evaluate required terms first to get candidates, then filter out exclusions before pagination to avoid incorrect page sizes.
Hint 3
Use heap-based top-K selection per partition, then merge sorted streams; store frequency counts in the index for scoring without document retrieval.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Strong Candidate Response
Initial Clarifications
Before designing, I'd establish:
Scale assumptions: 100M posts, 1K writes/sec, 10K queries/sec, p99 query latency under 200ms, new posts searchable within 30 seconds.
Search semantics: Case-insensitive token matching with basic stemming; queries are space-separated words (no phrase support initially); multiple inclusion terms use AND logic; exclusion-only queries rejected as too expensive.
Simplifications: No access control initially; focus on text search over post body.
High-Level Architecture
Components:
- Indexing pipeline: Consumes post events (create/update/delete), tokenizes content, updates inverted index
- Inverted index storage: Distributed key-value store mapping terms to posting lists
- Query service: Receives search requests, executes against index, merges and ranks results
Part 1: Inverted Index Design
Index structure: For each term, maintain a posting list containing document IDs and metadata:
term → [(docId, frequency, positions), ...]
For 100M posts averaging 50 unique terms each, storing 32-bit doc IDs and 8-bit frequencies: ~20GB uncompressed. With compression (delta encoding for sorted doc IDs), under 10GB.
Write path:
- Post service publishes create/update/delete events to message queue
- Indexer workers consume events, tokenize text (lowercase, remove punctuation, stem)
- For each term, append to or update posting list in distributed storage
- Delete operations mark entries as tombstones, periodically compacted
Freshness: With 30-second SLA, use near-real-time indexing. Each indexer batch processes events every 5-10 seconds, updating index segments that become queryable immediately.
Partitioning: Hash-partition the index by term across N machines (e.g., 10 shards). Each shard stores ~1GB and handles ~1K QPS. Query fan-out: every search hits all shards since we don't know which contains our terms.
Read path:
- Query coordinator tokenizes search input identically to indexing
- Sends term lookups to all index shards in parallel
- Each shard returns matching doc IDs for its terms
- Coordinator intersects results (AND logic) and returns top matches
Part 2: Exclusion Query Execution
Approach: Evaluate inclusions first to build candidate set, then filter exclusions.
Algorithm:
candidates = intersection(postingLists[includedTerms])
for excludedTerm in excludedTerms:
candidates = candidates - postingList[excludedTerm]
return candidates
Evaluation order optimization: Process inclusion terms from rarest to most common to minimize intermediate set size. For exclusions, apply them after all inclusions but before ranking/pagination.
Common term problem: If excluding "the" (appears in 90% of posts), the exclusion list is massive. Mitigation: perform exclusion filtering after taking top-K candidates from inclusion matches, trading perfect recall for performance. Alternatively, maintain bloom filters for quick negative membership tests.
Pagination correctness: Exclusions must run before pagination. If we paginate first then exclude, page 2 might have fewer results than page size, breaking user experience. Flow:
- Get all candidates matching inclusions (limit to top 10K)
- Filter out exclusions
- Rank remaining results
- Paginate ranked list
Edge cases:
- Unknown terms: Return empty posting list, handle gracefully in intersection
- Term both included and excluded: Treat as contradiction, return no results
- Exclusion-only: Reject query or require at least one inclusion term for bounded cost
Part 3: Frequency-Based Ranking
Score computation: For single-term queries, score = term frequency in document. For multi-term queries:
score(doc, query) = sum(frequency(term, doc) for term in query)
Store frequencies in posting lists so scoring doesn't require fetching documents.
Efficient top-K selection: Each shard maintains posting lists sorted by document ID. To get top results by score:
- Each shard scans its matched documents, computes scores, keeps top K in a min-heap (K=100)
- Return K results per shard to coordinator
- Coordinator merges N×K results (1000 total) into final top K
Avoid sorting millions of matches by doing top-K locally first.
Stable pagination: Include document ID as tiebreaker in score tuple: (frequency, docId). This ensures deterministic ordering across requests. For deeper pagination, use cursor-based approach with last seen (score, docId) rather than offset, handling edge case where scores change between page requests.
Distributed merging: Coordinator performs K-way merge of sorted result streams from shards using a heap. Each shard streams results in score order, coordinator pulls next-best until K results accumulated.
Weaknesses of raw frequency:
- Long documents naturally have higher counts (solution: normalize by document length)
- Keyword stuffing (solution: use logarithmic or capped frequency)
- Common words dominate rare ones (solution: TF-IDF weighting)
Improvement: Use TF-IDF scoring:
score = sum(tf(term, doc) × idf(term) for term in query)
Precompute IDF values (log(N/df)) where df is document frequency. Store during index build. This amplifies rare term matches while diminishing common terms.
Metrics and monitoring:
- Index lag: time from post creation to searchability
- Query latency: p50, p95, p99
- Shard health: detect slow or unresponsive nodes
- Result quality: track null result rate, click-through on top results
Failure handling:
- Indexer lag: Monitor queue depth, auto-scale workers, alert if lag exceeds SLA
- Slow shard: Set per-shard timeout (100ms), return partial results if one shard times out, log degraded response
- Dead shard: Query coordinator retries once, then excludes failed shard from results, alerts for manual intervention
This design handles billions of posts with sub-second query latency using standard distributed systems patterns.