EXP Decay Scores For Trending Feeds
Rank posts for trending feeds with EXP decay and a gravity denominator, so fresh votes outweigh votes that have aged for days.
Code
-- time-decay ranking for trending feeds: gravity denominator vs exponential decay
CREATE TABLE posts (
post_id int PRIMARY KEY,
title text NOT NULL,
votes int NOT NULL,
posted_at timestamptz NOT NULL
);
INSERT INTO posts (post_id, title, votes, posted_at) VALUES
(1, 'fresh launch', 40, now() - INTERVAL '1 hour'),
(2, 'yesterday hit', 400, now() - INTERVAL '26 hours'),
(3, 'last week recap', 900, now() - INTERVAL '7 days');
-- gravity denominator: (age_hours + 2)^1.5 -- the older the item, the lower the score
SELECT post_id, title, votes,
ROUND(votes / POWER(EXTRACT(EPOCH FROM (now() - posted_at)) / 3600.0 + 2, 1.5)::numeric, 3) AS gravity_score
FROM posts
ORDER BY gravity_score DESC;
-- exponential decay: votes * exp(-age_hours / 6) -- tau = 6 hours, a faster forgetting curve
SELECT post_id, title,
ROUND(votes * EXP(-EXTRACT(EPOCH FROM (now() - posted_at)) / 21600.0)::numeric, 3) AS decay_score
FROM posts
ORDER BY decay_score DESC;How it works
What runs here is SELECT / INSERT / CREATE — posts are the objects involved.
In terms of clauses, the statements use: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The posts table is the working surface here.
Statements that hold the behavior
INSERT INTO posts (post_id, title, votes, posted_at) VALUES
(1, 'fresh launch', 40, now() - INTERVAL '1 hour'),
(2, 'yesterday hit', 400, now() - INTERVAL '26 hours'),
(3, 'last week recap', 900, now() - INTERVAL '7 days');
SELECT post_id, title, votes,
ROUND(votes / POWER(EXTRACT(EPOCH FROM (now() - posted_at)) / 3600.0 + 2, 1.5)::numeric, 3) AS gravity_score
FROM posts
ORDER BY gravity_score DESC;
SELECT post_id, title,
ROUND(votes * EXP(-EXTRACT(EPOCH FROM (now() - posted_at)) / 21600.0)::numeric, 3) AS decay_score
FROM posts
ORDER BY decay_score DESC;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
FAQ
- What are the relations in play here?
- `posts` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.