Recipe: Typeahead ranking strategy
Build a fast, relevance-sorted autocomplete that scales to millions of entries without melting your Redis bill.
Ingredients
- Upstash KV or Redis with sorted sets
- Edge-friendly prefix index (ZRANGEBYLEX)
- Frequency decay function
- Client-side debounce (120ms)
Strategy
- Index on write. When a user submits a query, insert every prefix of the normalized string into a sorted set with a score derived from recency and frequency.
- Score formula. Use
score = log(freq + 1) + (now_epoch / 86400)so recent terms float up naturally. - Query path. On each keystroke, issue
ZRANGEBYLEXwith the current prefix, limit 8, then ZREVRANGEBYSCORE to re-rank by score. - Eviction. Cap each prefix set at 50 members. Trim lowest scores on insert with ZREMRANGEBYRANK.
Edge tip
Run the ZRANGEBYLEX + ZREVRANGEBYSCORE pipeline inside a Lua script to avoid the extra round-trip. At 10k QPS, that saves ~3ms per request.