Full answer
Simple window-based score:
text
SELECT post_id, COUNT(*) AS recent_likes
FROM likes WHERE created_at >= now() - interval '24 hours'
GROUP BY post_id ORDER BY recent_likes DESC LIMIT 50;A decay score smooths the cliff at 24 hours:
text
score = SUM(power(0.5, extract(epoch FROM now() - created_at) / 21600)) -- 6-hour half-lifeAlternatively, the common 'gravity' formula divides total points by (age in hours + 2) raised to a power, so newer posts rise faster.
Implementation:
- A job every few minutes recomputes scores for posts with recent activity into
trending(post_id, score, computed_at)with an index on score. - Only posts with activity in the last few days need recomputing.
- Guard against manipulation: count distinct users, weight new accounts lower.
The exact formula is a product decision; the database part is efficient incremental aggregation. The SQL shown is illustrative and was not run here.
Key points
- Weight interactions by recency
- Window counts or decaying sums
- Precompute scores periodically
- Recompute only active posts
- Count distinct users to resist gaming
Common mistakes
- Recomputing decay over all history on each request
- Counting raw likes without recency
Follow-ups
- How would you personalise trending?
- How would you choose the half-life?
Tips
- Explain the half-life idea