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.

SqlData Fetching

Code

snippet
-- 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

FAQ

What are the relations in play here?
`posts` — referenced directly, no join needed.