Design Full-Text and Proximity Search for a Social Feed
System DesignModel answerLast updated
Design a system that indexes hundreds of millions of short posts for keyword search and geolocation queries, meeting tight freshness and latency targets at scale.
Problem
Build a backend service with two complementary capabilities:
-
Post search: Users publish short text updates (up to ~280 characters), optionally tagged with a location. Any user can search the full corpus — including years of history — by keyword. Results should be ranked by relevance and recency, respect privacy settings (public vs. friends-only), and reflect deletions and edits within seconds.
-
Proximity search: Given a coordinate and a radius, return nearby posts, places, or users currently sharing their live location. Geo queries may be combined with keyword filters.
What is expected
Walk through the full design lifecycle:
- Requirements and scale: State your assumptions explicitly. Derive write rates, index sizes, and query rates from first principles.
- API design: Define the key endpoints, pagination strategy, and any rate-limiting concerns.
- Data model: Separate the source of truth from the derived indexes.
- Architecture: Show the write path, the async indexing pipeline, and the read path including fan-out and merge.
- Deep dives: Cover at least (a) how the inverted index is partitioned and tiered by time, (b) how deletes and privacy are handled efficiently, and (c) which spatial indexing scheme you would use for geo and why.
- Trade-offs and failure modes: What degrades gracefully? What breaks hard?
Spend roughly 60% of your time on full-text search and 40% on geo — say so up front.
Hints
Hint 1
Think about the age distribution of queries: the vast majority ask about recent posts. How does that asymmetry let you split the index into a small hot tier and a large cold tier, and what does each tier optimize for?
Hint 2
For full-text, should you partition the inverted index by term or by document? Consider what happens to a shard that owns the term '#worldcup' during a major event, and how multi-term queries behave under each scheme.
Hint 3
For geo, a single bounding cell misses entities sitting just across a cell boundary. What is the minimal set of cells you must query to guarantee no false negatives within radius R, and how does that interact with result ranking?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing and Time Split
This is two indexing problems sharing one ingestion pipeline. Say up front: ~60% on full-text, ~40% on geo. Treating them as separate systems is a common mistake — the geo dimension can be indexed as a field in the same inverted index for static entities, eliminating an entire service.
1. Requirements and Scale
Functional
- Posts up to ~280 chars; optional lat/lng tag; visibility: public or friends-only.
- Keyword search over full history, ranked by relevance + recency, paginated.
- Deletes and edits reflected in results within ~10 seconds.
- Geo: "find posts/places/friends within radius R," optionally plus a keyword.
- Live location: users can share position continuously.
Non-functional
- New posts searchable within 10 s (freshness SLA).
- Search p99 < 300 ms.
- Availability over strict consistency; eventual consistency of the index is acceptable.
- Never lose a post (durable write before indexing).
Scale assumptions (state these explicitly)
| Metric | Estimate |
|---|---|
| DAU | 500 M |
| Posts/day | ~500 M → 6 K/s avg, 20 K/s peak |
| Post size + metadata | ~1 KB → 500 GB/day, ~180 TB/year |
| Search QPS | ~50 K/s peak |
| Index size | ~30–50% of raw text → tens of TB/year |
| Live location updates | 20 M users × 1 update/30 s → ~700 K writes/s |
| Static places | ~200 M |
Key insight: recent data is tiny and hot; historical data is enormous and cold. This asymmetry drives every major architectural decision.
2. API
POST /v1/status {text, visibility, lat?, lng?} -> {status_id}
DELETE /v1/status/{id}
GET /v1/search?q=&cursor=&limit=20&since=&until=
GET /v1/nearby?lat=&lng=&radius_m=&type=status|place|friend&q=
PUT /v1/location {lat, lng} # live sharing, rate-limited per user
Use cursor-based pagination (opaque token encoding the last score + ID). Offset-based pagination requires skipping N rows across every shard on every page flip — prohibitively expensive in a scatter-gather system.
3. Data Model
Source of truth: sharded KV or wide-column store (Cassandra or MySQL sharded by status_id). Use Snowflake-style time-ordered IDs so you can route by time tier without a separate lookup.
Schema: status_id, author_id, text, visibility, lat, lng, geohash, created_at, deleted_at.
Inverted index: term → posting list[(status_id, tf, positions)]. Posting lists sorted descending by status_id (newest first) so early termination works naturally for recency-biased queries.
Geo index: cell_id → set[entity_id]. For live users, keep an in-memory map user_id → (lat, lng, cell, timestamp).
4. Architecture Overview
Client -> API Gateway -> Post Service -> Status DB (durable write first)
-> Kafka "status-events"
Kafka -> Indexer workers -> Realtime index tier (in-memory, ~7 days)
Kafka -> Batch compaction -> Historical index tiers (on-disk segments, by time range)
Kafka -> Geo indexer -> Static geo: field in search index
-> Live geo: Redis / in-memory sharded grid
Search request -> Query Service (parse, rewrite, ACL expansion)
-> Broker (fan-out to shard replicas of relevant tiers)
-> merge top-K -> hydrate from DB/cache -> privacy re-check -> client
The write path commits to the DB first, then emits to Kafka. Indexers consume asynchronously. This decouples indexing outages from posting availability and naturally absorbs burst writes.
5. Full-Text Search Deep Dive
Partition by document, not by term
Term partitioning creates hot shards for popular terms ("#worldcup") and forces multi-term queries to scatter across many shards. Document partitioning (shard by status_id range) puts a mini-index on each shard; queries scatter-gather and each shard returns its local top-K. The broker merges them. This is how Twitter's Earlybird index works.
Time-tiered index — the critical insight
- Realtime tier (0–7 days): Fully in memory. Append-only posting lists; single writer per segment, lock-free readers. Satisfies the vast majority of queries. Segments are small enough to fit in RAM.
- Historical tiers (>7 days): Immutable, compacted on-disk segments (Lucene-style), partitioned by time range (e.g., monthly shards). Built offline from Kafka replay or DB scan, then replicated out. Hit only when the user explicitly filters on old dates or the realtime tier returns fewer than K results.
The effect: a typical query fans out to tens of shards, not thousands.
Ranking
- Per-shard (cheap): BM25 text score × recency decay × cached engagement counts.
- At broker (expensive, small candidate set): ML reranker using author affinity, social graph signals, freshness.
Deletes and edits
- A delete writes a
deleted_attimestamp to the DB and publishes a delete event to Kafka. - Each index shard maintains a deleted-docs bitmap keyed by
status_id. Applied at query time in microseconds. - Compaction purges deleted docs from on-disk segments.
- An edit is a logical delete of the old
status_idplus a new insert.
Privacy
- Public posts are indexed globally.
- For friends-only posts: post-filter at hydration by checking viewer's friendship with the author. For viewers with large friend lists, optionally index
visibilityas a field and pushauthor_id IN friends(viewer)into the query for early pruning. - Always re-check ACLs at hydration as a safety net — index ACLs can lag.
Reliability
- Replicate each shard 2–3×; route reads to the fastest replica via hedged requests.
- Return partial results if a shard times out (degraded is better than failed).
- Cache popular queries for a few seconds with a short TTL.
6. Geolocation Search Deep Dive
Spatial index comparison
| Scheme | Pros | Cons |
|---|---|---|
| Geohash | String prefix = containment; trivial to store in any KV or inverted index | Non-uniform cell shapes; edge effects near poles |
| Quadtree | Density-adaptive (splits dense cities) | Harder to shard and update dynamically |
| S2 / H3 | Uniform area cells; clean circle coverings | Slightly more implementation complexity |
Recommendation: Geohash for simplicity, S2 if uniform cell area matters (e.g., ride-sharing).
Query algorithm
- Pick geohash precision matching the query radius (length 6 ≈ 1.2 × 0.6 km; length 5 ≈ 5 × 5 km).
- Compute the center cell plus its 8 neighbors — this eliminates false negatives for entities just across a cell boundary.
- Fetch candidates from those 9 cells.
- Filter by exact haversine distance ≤ R.
- Rank by distance, or blend with text relevance for combined queries.
For sparse areas with too few results, widen to a coarser precision level. For very dense areas, apply a per-cell candidate cap before exact-distance filtering.
Static places and geotagged posts
Index the geohash prefix as a field in the same inverted index used for text. A combined query ("coffee near me") becomes q=coffee AND geohash_prefix IN {9 cells} — no second system required.
Live user locations (~700 K writes/s)
Persistent storage cannot absorb this write rate with low latency. Instead:
- Maintain a sharded in-memory grid (Redis cluster or a custom service) mapping
user_id → (lat, lng, cell, timestamp). - On a location update, update the in-memory entry; write to persistent store asynchronously at lower frequency (e.g., every 60 s) for recovery.
- Stale entries (no update in >5 min) are evicted and treated as offline.
7. Common Mistakes to Avoid
- Skipping scale math: Without numbers, you cannot justify tiering, sharding counts, or in-memory vs. on-disk decisions.
- Term partitioning: Leads to hot shards and expensive cross-shard intersections.
- Single geo cell per query: Always query the 9-cell neighborhood.
- Synchronous indexing on the write path: Couples index latency to post latency and makes the system fragile.
- Forgetting deletes: An index that cannot tombstone deleted posts violates product and legal requirements.
- ACL enforcement only at index time: Index ACLs lag; always re-check at hydration.