Every site that shows a list of “popular” things (stories, links, posts, products, tags) has to decide what popular means. The simplest answer is to count: the item with the most likes, up-votes, clicks or shares is on top.
But counts only grow. An item that collected a thousand likes last month stays ahead of one that fifty people liked in the last hour, and a list ranked by counts fills up with yesterday’s news. What readers usually want is what’s popular now.
TimeScore fixes this by letting every like fade with age. A like is worth one point when it happens, half a point one half-life later, a quarter after two half-lives, and so on. An item’s score is the sum of its faded likes, so the top of the list is whatever has been getting attention lately. And each item’s score is kept as a single number that never has to be updated as time passes.
To see it on real data, TimeScore Demos ranks movies by their new IMDb ratings and TMDB popularity, and Wikipedia articles by their pageviews, with half-lives of a day, a week, a month and a year. It updates every day.
Try it
Here are three posts and a clock that runs at 3600 times real time (one second is one hour). Likes fade with a half-life of eight hours. When the clock starts, Red has the most likes, but they’re two days old. Blue got its likes over the past half day, and Green just got three in the last two hours.
Click Like under a post and watch its line jump. Stop clicking and it falls by half every eight hours. At the start, Red has the most likes, and yet it ranks last.
- Likes
- 0
- TimeScore
- 0.00
- Likes
- 0
- TimeScore
- 0.00
- Likes
- 0
- TimeScore
- 0.00
- Ranked by TimeScore
- Ranked by likes
On real data
The posts above are made up. Here’s TimeScore on real activity: the weekly views of eight English Wikipedia articles, from TimeScore Demos, updated every day. The eight are picked from the latest data: the four with the most views since the data begins, and the four with the highest TimeScore now. Each week’s views of an article count as one event, worth the number of views.
On the left, the articles are ranked by their total views so far, the way a plain count would rank them. On the right, they’re ranked by TimeScore. It runs ten weeks a second; drag the slider to move through time yourself.
The totals only grow, so the left side favors the articles people read week after week, and an article that had one huge week stays near the top long after readers have moved on. On the right, each burst of attention lifts an article and then fades, so the top is whatever has been read lately. Pick a one-year half-life to see the right side settle toward the totals, or one month to see it react to every busy week.
Total so far
TimeScore, half-life
How it works
The TimeScore
Say an item gets events (likes, here), numbered . Event happens at time and has a score (1 for a like). With a half-life , the item’s TimeScore now, at time , is the sum of its events’ scores so far, each halved for every half-life since it happened:
The trouble is that this changes every moment, even when nothing happens. To keep a list sorted by it, you’d have to recompute every item’s score as the clock moves, or at least every time you show the list.
The time-invariant TimeScore
But every item’s score fades at the same rate. Between events, all the scores shrink by the same factor, so their order never changes. Only a new event can move an item up the list.
So TimeScore keeps a second score that doesn’t fade at all. Instead of shrinking old events, it grows new ones: each event’s score is multiplied by , where time is measured from some fixed starting time (). An event one half-life later counts twice as much, two half-lives later four times as much, and so on. Call that event’s grown score ; the hat marks a score scaled to time 0. The time-invariant TimeScore is the sum of the events so far, each scaled that way:
Here’s how it relates to the TimeScore. Starting from the TimeScore’s definition, each step rewrites it until appears:
So : the TimeScore times a factor that, at any moment, is the same for every item. That means it ranks items in the same order. And since nothing in its terms depends on the current time , it changes only when an event is added. Adding an event just adds one more term to the sum:
Storing the log
There’s one catch. doubles every half-life. With an eight-hour half-life, it passes the largest number a double can hold () in less than a year. So I store its log, , instead, which only grows by per half-life.
An item with no events has , so it starts at . (Any base of logarithm would do: changing the base just multiplies every item’s stored log by the same constant, which doesn’t change their order. The natural log keeps the code simplest.)
Updating means taking the log of the update above. But that can’t be computed as written: it needs itself, the very number that overflows. What’s needed is a way to add two numbers that are stored as logs, without ever computing the numbers themselves:
With that, the update takes three steps. The first two write both terms of the sum as powers of , and the last uses the sidebar’s formula:
Here is the log score the new event would have on its own, and it never overflows either:
So adding an event is the larger of the item’s log score and the event’s, plus a correction between 0 and . One more like on an item that already has a high score barely moves it. A second like at the same moment as an item’s only like doubles its score, adding exactly . And an item’s first event () simply sets to .
Back to the current score
To show an item’s current score, start from the end of the first derivation:
That’s all there is to it. Each item stores one number. Adding an event needs only that number, the event’s score and the event’s time. Events can even be added out of order. And sorting by the stored number, say with an index in a database, ranks items by their current TimeScore.
The code
Here is TimeScore in JavaScript and in Python. The JavaScript module is the
one the demo above uses. Both work for any half-life, in any unit of time.
The update follows the derivation: eventScore computes , combine is
the sidebar’s formula (its high and low are and ), and
addEvent combines the two. Math.log1p(x) is , computed
accurately even when is tiny, and Math.LN2 is .
// TimeScore: a time-weighted score, stored as a single number per item.
//
// Every event (a like, a click, a share) is worth its full value when it
// happens, half as much one half-life later, a quarter after two, and so on.
// An item's score at any moment is the sum of its events' faded values.
//
// Rather than fading old events as time passes, each event is boosted by
// 2^(time / halfLife) when it is added, and the item stores the (natural) log
// of the sum. Every item's score fades at the same rate, so the stored numbers
// never change between events, and sorting by them ranks items by their
// current score. (The log keeps the number small: the sum itself would pass
// the largest double after 1024 half-lives.)
//
// Times can be in any unit (hours, seconds, days) measured from any fixed
// epoch, as long as the half-life is in the same unit.
//
// Because the stored score is the log of a plain sum, two scores for the same
// item (say, from two replicas of a database, each counting different
// events) merge with combine().
//
// TimeScore is in the public domain: free for anyone to use. If you use it,
// a credit is appreciated: "TimeScore algorithm courtesy Mike Koss"
// (https://mckoss.com).
/** The stored score of an item with no events yet. */
export const EMPTY = -Infinity;
/**
* The stored score of a single event: log(value * 2^(time / halfLife)).
*
* @param {number} value the event's value, greater than 0 (1 for a like)
* @param {number} time when the event happened
* @param {number} halfLife the time it takes an event's value to halve
* @returns {number} the event's score, ready to combine with an item's
*/
export function eventScore(value, time, halfLife) {
if (!(value > 0)) throw new RangeError(`TimeScore values must be greater than 0, not ${value}`);
return Math.log(value) + time * Math.LN2 / halfLife;
}
/**
* Two stored scores merged into one, as if one item had had both scores'
* events: log(e^a + e^b), computed without leaving the log domain.
*
* @param {number} a a stored score (EMPTY for none)
* @param {number} b another stored score with the same half-life
* @returns {number} the merged score
*/
export function combine(a, b) {
const high = Math.max(a, b);
const low = Math.min(a, b);
if (low === -Infinity) return high;
return high + Math.log1p(Math.exp(low - high));
}
/**
* Add an event to an item's stored score.
*
* @param {number} logScore the item's stored score (EMPTY if it has none)
* @param {number} value the event's value, greater than 0 (1 for a like)
* @param {number} time when the event happened
* @param {number} halfLife the time it takes an event's value to halve
* @returns {number} the item's new stored score
*/
export function addEvent(logScore, value, time, halfLife) {
return combine(logScore, eventScore(value, time, halfLife));
}
/**
* An item's score at a given time, at or after its latest event: the sum of
* its events' values, each halved for every half-life since it happened.
*
* @param {number} logScore the item's stored score
* @param {number} time the time to score it at
* @param {number} halfLife the same half-life its events were added with
* @returns {number} the item's score at that time
*/
export function scoreAt(logScore, time, halfLife) {
return Math.exp(logScore - time * Math.LN2 / halfLife);
}
"""TimeScore: a time-weighted score, stored as a single number per item.
Every event (a like, a click, a share) is worth its full value when it
happens, half as much one half-life later, a quarter after two, and so on.
An item's score at any moment is the sum of its events' faded values.
Rather than fading old events as time passes, each event is boosted by
2 ** (time / half_life) when it is added, and the item stores the (natural)
log of the sum. Every item's score fades at the same rate, so the stored numbers
never change between events, and sorting by them ranks items by their
current score. (The log keeps the number small: the sum itself would pass
the largest float after 1024 half-lives.)
Times can be in any unit (hours, seconds, days) measured from any fixed
epoch, as long as the half-life is in the same unit.
Because the stored score is the log of a plain sum, two scores for the same
item (say, from two replicas of a database, each counting different events)
merge with combine().
TimeScore is in the public domain: free for anyone to use. If you use it,
a credit is appreciated: "TimeScore algorithm courtesy Mike Koss"
(https://mckoss.com).
"""
import math
EMPTY = -math.inf
"""The stored score of an item with no events yet."""
LN2 = math.log(2)
def event_score(value: float, time: float, half_life: float) -> float:
"""The stored score of a single event: log(value * 2 ** (time / half_life)).
value: the event's value, greater than 0 (1 for a like)
time: when the event happened
half_life: the time it takes an event's value to halve
"""
if not value > 0:
raise ValueError(f"TimeScore values must be greater than 0, not {value}")
return math.log(value) + time * LN2 / half_life
def combine(a: float, b: float) -> float:
"""Two stored scores merged into one, as if one item had had both scores'
events: log(e**a + e**b), computed without leaving the log domain.
a: a stored score (EMPTY for none)
b: another stored score with the same half-life
"""
high = max(a, b)
low = min(a, b)
if low == -math.inf:
return high
return high + math.log1p(math.exp(low - high))
def add_event(log_score: float, value: float, time: float, half_life: float) -> float:
"""Add an event to an item's stored score, and return the new stored score.
log_score: the item's stored score (EMPTY if it has none)
value: the event's value, greater than 0 (1 for a like)
time: when the event happened
half_life: the time it takes an event's value to halve
"""
return combine(log_score, event_score(value, time, half_life))
def score_at(log_score: float, time: float, half_life: float) -> float:
"""An item's score at a given time, at or after its latest event: the sum
of its events' values, each halved for every half-life since it happened.
log_score: the item's stored score
time: the time to score it at
half_life: the same half-life its events were added with
"""
return math.exp(log_score - time * LN2 / half_life)
Using it in JavaScript, liking a post adds an event to its stored score, and the list sorts on it:
import { EMPTY, addEvent, scoreAt } from './timescore.js';
const HALF_LIFE = 8 * 60 * 60 * 1000; // 8 hours, in milliseconds like Date.now()
post.timeScore ??= EMPTY;
post.timeScore = addEvent(post.timeScore, 1, Date.now(), HALF_LIFE);
posts.sort((a, b) => b.timeScore - a.timeScore); // hottest first
const shown = scoreAt(post.timeScore, Date.now(), HALF_LIFE);
Times can be passed straight from the clock, as long as the half-life is in
the same units: milliseconds for Date.now(), or seconds for Python’s
time.time(). Only the ratio of the two matters, and the stored log grows
by just per half-life. With an eight-hour half-life
it’s about 43,000 today, and a double holds that to within about
, so the scores stay accurate to about eleven significant
digits.
In a database
TimeScore is especially handy in a database.
An index that hardly moves
Put an index on the score column and the database keeps every item in TimeScore order. A like changes one number in one row, so it moves just that row’s entry in the index, and only past the items it overtakes. No other row changes. Nothing needs rescoring as time passes, so there’s no batch job re-ranking everything every hour. And the list of hottest items is the top of the index.
The update can even be done in SQL, as one atomic statement, so two likes
that arrive at once can’t overwrite each other. The application computes
the like’s own score with eventScore and passes it in:
-- TimeScore in SQL, as written for SQLite. In PostgreSQL, write GREATEST in
-- place of the two-argument max.
--
-- TimeScore is in the public domain: free for anyone to use. If you use it,
-- a credit is appreciated: "TimeScore algorithm courtesy Mike Koss"
-- (https://mckoss.com).
-- Each post stores its TimeScore as one number, NULL until its first like.
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
title TEXT,
time_score REAL
);
-- The index keeps the posts in TimeScore order. A like moves only its own
-- post's entry, and only past the posts it overtakes.
CREATE INDEX posts_by_time_score ON posts (time_score DESC);
-- Add a score to a post, in one atomic statement. :score is either a like's
-- own score, from eventScore(), or another replica's score for the post, to
-- merge it in. This is combine() from timescore.js.
UPDATE posts
SET time_score = CASE
WHEN time_score IS NULL THEN :score
ELSE max(time_score, :score) + ln(1 + exp(-abs(time_score - :score)))
END
WHERE id = :id AND :score IS NOT NULL;
-- The hottest posts right now.
SELECT id, title
FROM posts
WHERE time_score IS NOT NULL
ORDER BY time_score DESC
LIMIT 20;
Since many databases (and JSON) can’t hold , the table uses
NULL for a post with no likes yet.
Merging scores
is a plain sum, so two scores for the same item can be
added, and adding is just what the sidebar’s formula does with their logs.
That’s combine. It gives exactly the score the item would have had if one
database had counted all the events, in any order, without needing to know
when either score was last updated.
That makes TimeScore easy to spread across machines:
- Replicas that sync now and then. Each replica counts the likes it
takes into its own score for each post. When they sync, each post’s score
from one replica is combined into the other’s. The SQL update above does
it: pass the other replica’s score as
:score. - Very popular items. Instead of every like updating one hot row, the likes can go to several rows (shards) for the same item, with the item’s score being those rows combined when it’s read.
- Totals. An author’s score is all of their posts’ scores combined, and a tag’s is all of its posts’ combined. They rank just like posts do.
The one rule is that every event must be counted once. combine adds, so a
replica should send only the score of the likes it took since its last sync,
not a score that already includes the other replica’s likes.
Try it with two replicas of the same three posts. Like posts on either one,
and each replica ranks them by the likes it has seen. Sync sends each
replica the scores of the likes the other took since the last sync, merged
in with combine. After that, both replicas match one database that took
every like, down to the last digit.
Replica A
- Red 0.00
- Blue 0.00
- Green 0.00
Likes not yet sent: 0
Replica B
- Red 0.00
- Blue 0.00
- Green 0.00
Likes not yet sent: 0
One database with every like:
Compared with Reddit
Reddit’s “hot” ranking, in the code it published as open source, works in much the same way:
order = log10(max(abs(ups - downs), 1))
seconds = post_time - 1134028003
hot = sign * order + seconds / 45000
That’s the log of a post’s votes, plus a term that grows steadily with time: just like above, with base-10 logs. A post needs ten times the votes to make up for being 45,000 seconds (12.5 hours) older. That makes it a TimeScore with a half-life of hours.
The difference is which time each vote counts at. Reddit counts every vote at the time the post was submitted, however much later it’s cast. TimeScore counts each like at the time it happens. That matters in two ways:
- An old post can come back. With Reddit’s formula, a day-old post needs about 80 times the votes of a new one to rank beside it, even if every one of those votes came in the last hour. Under TimeScore, a post that’s being liked right now is hot again, whatever its age.
- Reddit’s hot score only works for posts. It needs a post time. TimeScore needs only events, so it can rank anything people act on over time: links shared again and again, tags, search results people click, users' reputations, even the IP addresses sending a server the most requests.
Compared with Hacker News
Hacker News ranks its front page with a different formula. Here it is in the Hacker News source code Paul Graham released with the Arc language (as kept in the community’s Anarki repository):
(= gravity* 1.8 timebase* 120 ...)
(def frontpage-rank (s (o scorefn realscore) (o gravity gravity*))
(* (/ (let base (- (scorefn s) 1)
(if (> base 0) (expt base .8) base))
(expt (/ (+ (item-age s) timebase*) 60) gravity))
; ...times penalties for posts without a link,
; "lightweight" posts and flame wars
...))
With for a story’s points and for its age in hours, that’s
Like Reddit, it counts every vote the same, however long after the story was posted. But it also fades stories differently: by a power of their age, not by half-lives. With a power, the ratio between two stories’ ranks keeps changing as they age, so they can swap places with no new votes at all. A story with 100 points posted 10 hours ago ranks below one with 30 points posted 2 hours ago (0.45 against 1.22). Eight hours later, with no votes for either, the older one is ahead (0.180 against 0.169).
So Hacker News can’t simply keep its stories in sorted order. Its source says as much, and fixes it by re-ranking one of the top 50 stories, chosen at random, every 30 seconds:
; If something rose high then stopped getting votes, its score would
; decline but it would stay near the top. Newly inserted stories would
; thus get stuck in front of it. I avoid this by regularly adjusting
; the rank of a random top story.
(defbg rerank-random 30 (rerank-random))
Halving with a fixed half-life is the one way of fading scores where this can’t happen. Over any stretch of time, every score shrinks by the same factor, however old it is, so two items only change places when one of them gets a vote. That’s why TimeScore’s stored numbers can sit in a sorted index and stay sorted. (Hacker News’s live ranking has changed over the years, and moderators adjust it by hand, so the published code shows the idea rather than today’s exact numbers. Ken Shirriff compared the two in 2013.)
The patent
I filed a patent on this method in September 2009, and it was granted in March 2012 as U.S. Patent 8,140,541, “Time-weighted scoring system and method” (also on Google Patents).
I’ve placed TimeScore in the public domain: anyone is free to use it, and I won’t enforce the patent. If you do use it, I’d appreciate a credit such as “TimeScore algorithm courtesy Mike Koss.”
The patent also describes keeping more than one score per item, with different half-lives, such as a day and a week. Comparing them shows what’s trending: an item whose one-day score is high compared with its one-week score is getting more attention than usual.
As I described it in the patent, each item kept three values: its faded score, the time that score was last updated, and the log score. I realized later that the log score is all you need: the update above works from it alone, with no record of when the item last changed.