Building a Live Hashtag Popularity Ranking Service
System DesignModel answerLast updated
Design a backend that ingests social media posts at scale, computes time-sensitive popularity scores for hashtags, and serves a constantly updated list of what's trending.
You're building a service that identifies and surfaces currently popular hashtags from a high-volume social media platform. Users create posts that may include hashtags, and your system must continuously determine which hashtags are gaining traction right now and expose them through an API.
The core challenge is balancing three qualities in your ranking:
- Recency — surface hashtags while the underlying activity is still happening. A hashtag surge should appear in your results within roughly 60 seconds. Your system looks at activity from the past 24 hours, with recent activity weighted more heavily.
- Reach — prioritize hashtags that are reaching a broad audience, not just being repeated by a small group of highly active users.
- Emergence — highlight hashtags that represent something new or unusual, not topics that consistently generate steady background activity.
Design how posts enter your system, how you calculate a ranking score incorporating these three factors, and how you store and deliver the ranked list to clients at scale.
Scale Parameters
Use these numbers to inform your design; you'd clarify them in a real conversation.
- Post volume: several billion per day, translating to roughly 50,000–80,000 posts/second on average, with spikes reaching 3–5× baseline during major events. Around 15% of posts include hashtags, averaging 2 per post, yielding approximately 15,000–40,000 hashtag mentions/second in normal conditions.
- Distinct hashtags in a 24-hour window: tens of millions exist, but most are rare. Only thousands are realistic contenders for trending status at any given moment.
- Latency target: when a hashtag starts surging, it should appear in the trending list within ~60 seconds (99th percentile).
- Query load: the trending list (global or segmented by geography/language) is requested at very high rates with a target response time under 100ms.
- Consistency: the list can be eventually consistent and approximate — exact precision isn't required.
Questions You Should Explore
- Does the service provide a single global list, or do you need per-region or per-language lists (which multiplies the aggregation work)?
- How do you measure "reach" — by counting unique post authors, unique viewers, or raw post volume? This choice affects what data structures you need.
- Are exact counts required, or can you use probabilistic approximations for speed and memory efficiency?
- What's the ratio of writes (hashtag events) to reads (API queries)?
- Should the design account for spam or coordinated manipulation (which affects how you measure both reach and emergence)?
- How should hashtags be normalized — handling case differences, special characters, or near-duplicates like
#WorldCupversus#World_Cup?
Part 1 — Ingestion Architecture
Outline the complete data flow from post creation to a queryable trending list. Identify the main system components, the streaming infrastructure, how you partition or shard the work, and a rough calculation of event rates and per-hashtag memory requirements.
Part 2 — Scoring Algorithm
Define a concrete numerical score for each hashtag that captures recency, reach, and emergence, updated at least every minute over the 24-hour observation window. Explain how each of the three required properties is measured and how they combine into a single value you can rank by.
Additional Questions for Scoring
- What reference period defines "before" for emergence detection — recent hours, the same time period on previous days, or a long-term average? This affects whether a hashtag that trends every weekend should be surfaced each time.
- Should scores be regionally segmented so a locally surging topic isn't hidden by global volume?
Part 3 — Storage, API, and Reliability
Describe how computed scores become a top-K list delivered through your API within the latency budget, and how the system handles failures, delayed or out-of-order events, and potential abuse.
Hints
Hint 1
Break the problem into a streaming pipeline: ingestion → aggregation → scoring → serving. Each stage has different scaling characteristics.
Hint 2
Use time-bucketed counters and probabilistic data structures (HyperLogLog for unique authors, Count-Min Sketch for the long tail) to keep memory manageable across millions of hashtags.
Hint 3
The scoring function needs exponential time decay for recency, a measure of distinct authors for reach, and a comparison against historical baseline for emergence. Combine them multiplicatively so steady high-volume hashtags don't dominate.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Live Hashtag Popularity Ranking
Step 1: Clarify Scope and Calculate Scale
Begin by nailing down what you're building and sizing the workload.
Core Requirements:
- Functional: Accept all posts, extract and normalize hashtags, deliver a ranked top-K list (global and potentially per-region/language) refreshed every minute.
- Non-functional: ~60 second latency from surge to visibility, sub-100ms read latency at high query rates, eventual consistency and approximate results are acceptable.
Capacity Estimation:
-
Write throughput: 50–80k posts/sec baseline. With 15% containing hashtags at 2 per post, that's roughly 15–40k hashtag events/sec average, peaking at ~150–200k/sec. At ~100 bytes per event, peak throughput is around 20 MB/sec — easily handled by a message queue like Kafka with partitioning.
-
State storage: Storing full per-minute granularity naively would be 1,440 minutes × 4 bytes ≈ 6 KB per hashtag. Across tens of millions of hashtags, that's 60+ GB, mostly wasted on rarely-used tags. The solution is tiered storage:
- Long-tail hashtags: Use a Count-Min Sketch for approximate per-minute counts plus coarser hourly aggregates. This costs a few hundred MB per shard.
- Candidate hashtags (~100k that cross an activity threshold): Keep full granular state—1,440 minute buckets, HyperLogLog sketches of unique authors at multiple time granularities (~1.5 KB each), and baseline statistics. Total per tag: ~60 KB, or ~6 GB cluster-wide, trivially sharded.
-
Read path: The final list is small (few KB) and identical for all users in a segment, making it a caching problem rather than a database problem.
API Shape:
GET /trending?region=US&language=en&limit=20
Response:
{
"timestamp": 1735689640,
"version": 92447,
"trends": [
{"hashtag": "#worldcup", "rank": 1, "score": 38.7, "estimated_authors_1h": 145000}
]
}
Step 2: System Architecture (Part 1)
Build a streaming pipeline with these components:
1. Post Ingestion → Message Queue
Posts flow from the application into a Kafka topic (posts), which serves as the durable event log.
2. Hashtag Extraction (Stateless Processors) Consumer workers read posts and:
- Parse and extract hashtags
- Normalize (Unicode normalization, case folding, alias resolution)
- Filter spam accounts
- Emit
HashtagEventrecords to a second topic (hashtag-events), keyed byhash(normalized_hashtag)so all events for a given hashtag route to the same partition.
3. Stateful Aggregation (Stream Processor) Use a framework like Flink with keyed state. Each hashtag is owned by one task, enabling local aggregation without coordination. Every minute, on the watermark boundary:
- Seal the completed minute bucket
- Update HyperLogLog sketches for unique author counts
- Recalculate scores for candidate hashtags
- Emit the task's local top-K (K ≈ 500)
4. Global Merge A single lightweight task per segment (global, or per-region/language) merges the N local top-K lists into a final global top-K. Since each hashtag exists on exactly one shard and its score is computed there, this merge is exact for the top-K.
5. Snapshot Publisher
Write the versioned ranked list to Redis (key pattern trending:{segment}:latest) and archive to object storage for analysis.
6. Trending API Stateless servers read from Redis, backed by in-process caching and a CDN with 30–60 second TTL. Reads never touch the aggregation pipeline.
Hot Key Handling: A hashtag going viral can overwhelm a single partition. Mitigate with:
- Key salting for hot tags (e.g.,
tag#0throughtag#7) - Pre-aggregate within each salt, then merge in a second stage (HyperLogLog and counts are mergeable)
- Local combiner in each consumer that batches events per hashtag every second before emitting
Step 3: Scoring Function (Part 2)
Work with per-minute buckets rather than individual events. For hashtag h at minute t:
Let a_t = approximate distinct authors in minute t (from HyperLogLog). Counting unique authors rather than raw posts naturally incorporates reach.
Recency: Exponential Time Decay
Compute a recency-weighted sum:
R(h) = Σ(i=0 to 1439) a_(t−i) · exp(−λ·i)
where λ = ln(2) / half-life, with half-life around 30–60 minutes.
This can be maintained incrementally: R ← R·exp(−λ) + a_t each minute. The full bucket history allows recomputation with different parameters and clean expiration of the oldest bucket.
Reach: Breadth Over Volume
P(h) = distinct authors in the last hour (union of 5-minute HyperLogLog sketches)
Apply filters:
- Minimum threshold: P must exceed P_min (e.g., 200 authors in the segment)
- Diversity check: D = distinct authors / total posts. Low values indicate spam or bot activity.
- Optionally weight authors by account age or reputation.
Emergence: Deviation from Baseline
Maintain a slow-moving baseline using exponential weighted moving average over several days:
- Track hourly distinct-author rate: mean μ_h and variance σ²_h
- Make it seasonality-aware: blend the same hour-of-week from recent weeks with the immediate past, so predictable patterns (like
#MondayMotivationevery Monday) don't appear as anomalies.
Compute novelty score:
N(h) = (r_current − μ_h) / (σ_h + c·√(μ_h) + ε)
The √μ term models Poisson noise, preventing tiny hashtags from showing huge relative spikes. New hashtags with μ ≈ 0 score high only after crossing the reach threshold.
Combined Score:
Score(h) = indicator[P ≥ P_min] · indicator[D ≥ D_min] · (w₁·log(1+R) + w₂·log(1+P)) · sigmoid(N − N₀)
- The sigmoid on novelty means steady high-volume tags like
#lovescore near zero regardless of volume - Logarithms prevent one massive tag from dominating the entire ranking
- Weights (w₁, w₂, N₀) are tuned using offline evaluation and historical data
State Management:
- Tail hashtags stay in the Count-Min Sketch
- Promotion to candidate status: When a hashtag's approximate count crosses a threshold over 5 minutes, promote it to full state tracking, bootstrapping its history from sketch data
Step 4: Serving, Storage, and Fault Tolerance (Part 3)
Serving Infrastructure:
The trending list is tiny (few KB per segment). Redis holds replicated copies across regions. API servers cache the list in-process.
- CDN and edge caching with short TTL (30–60s)
- p99 read latency well under 10ms; the 100ms budget is mostly network
- Atomic updates: Write to a versioned key, then atomically swap the
latestpointer so readers never see partial updates - If the pipeline stalls, continue serving the last valid snapshot and alert if
timestampfalls >3 minutes behind wall clock
Fault Tolerance:
- Checkpointing: Stream processor checkpoints state and Kafka offsets every ~30 seconds. On failure, tasks restore from the last checkpoint and replay from the saved offset.
- Idempotency: HyperLogLog sketches naturally handle duplicate author IDs. Counts tolerate small duplication, but for stricter requirements, deduplicate on
post_idusing a short-TTL Bloom filter.
Late and Out-of-Order Events:
- Use event-time processing with watermarks. Accept events up to ~5 minutes late.
- Very late events (beyond the watermark) are either dropped or trigger recomputation of affected minute buckets if business-critical.
Handling Abuse:
- Pre-filter known spam accounts during extraction
- The diversity metric (D) naturally penalizes coordinated posting
- Monitor for suspicious patterns (sudden spikes from new accounts, identical post text) and apply dynamic filtering or score dampening
- Human review queue for borderline cases before surfacing to users
Monitoring and Quality:
- Track end-to-end latency from event timestamp to list appearance
- Compare online rankings against offline batch computations to detect drift
- A/B test scoring parameter changes by serving different weights to user cohorts
- Alert on anomalies: missing updates, stale timestamps, score distribution shifts
Common Mistakes to Avoid
- Using raw post counts instead of unique authors — makes the system vulnerable to spam and bot manipulation
- No time decay — old activity continues influencing rankings long after relevance has passed
- Ignoring baseline comparison — perennially popular hashtags dominate the list, hiding new events
- Synchronous aggregation — trying to query and aggregate on-demand at read time doesn't scale; pre-compute and cache
- Exact counts everywhere — storing precise counters for millions of hashtags exhausts memory; use probabilistic structures for the long tail
- No normalization —
#WorldCup,#worldcup,#world_cupare treated as different hashtags
Complexity Analysis
- Write path: O(1) per event after partitioning (local updates only)
- Score computation: O(K) per shard per minute where K is candidate count per shard
- Global merge: O(N·K·log K) where N is number of shards (typically small, ~10–100)
- Read path: O(1) cache lookup
- Space: O(M) for long-tail sketch + O(C·1440) for candidates, where C << M
Follow-Up Questions
How would you support personalized trending lists? Maintain per-user-interest-segment rankings by routing events through an additional dimension. Use a lightweight ML model to classify each user's interest profile, then aggregate and serve per-segment. This multiplies state and compute proportionally.
How would you detect emerging hashtags even faster (sub-10 second latency)? Reduce aggregation window to 10-second micro-batches. Use a two-tier system: a fast approximate tier (simple thresholding on raw counts) feeds a "breaking" section, while the full scoring logic runs every minute for the main list.
What if you need to support historical queries ("what was trending last Tuesday")? Archive each minute's snapshot to a data warehouse. Build a separate batch pipeline that reconstructs historical rankings from the raw event log stored in Kafka (with longer retention) or object storage.
How do you tune the scoring weights? Run offline experiments with historical data and known ground-truth events. Use metrics like nDCG (normalized discounted cumulative gain) if you have labeled examples, or proxy metrics like "time to surface" for known viral events. A/B test weight changes in production with small user percentages.