Skip to content
Personalisation

Trending

Show what is popular right now. Everyone gets the same list.

The algorithm

Based on the aggregated watch history of all users, the algorithm finds currently most popular content. The assumption is that the more popular the content is, the more users will find it personally relevant. Moreover, public broadcasters produce a lot of content relevant to everyone independently of their tastes (such as news content).

Warning

Trending is an algorithm which provides non-personalised recommendations, i.e. all users get the same content recommended. Individual preferences are not taken into account.

Like collaborative filtering or diversified algorithm, trending does not use content metadata and computes recommendations based on user watch history only.

Note

This algorithm is commonly used as a fallback algorithm in case the main recommendation algorithm does not return any result for some reason.

The structure

Trending is the simplest complete PEACH feature, and the same shape as every other one: a task computes the list on a schedule, Dragonfly holds the result, and an endpoint reads it back.

[play events]  →  [task: count and rank]  →  [Dragonfly]  →  [endpoint: read and serve]

The task considers an item current if it was played in the last week, and ranks items by how many distinct users played them. Counting users instead of plays stops one person replaying an item from pushing it up the list.

Summary

Only two things are specific to your organisation: where the play events come from, and what an event looks like. Everything else below can be used as it is.

The workflow

All of it fits in one file, peach/trending.py, using the decorators. The build your first feature guide explains the project layout and how it gets deployed.

Step 1 · Load

Read the play events

Write load_play_events() so that it returns the plays of the last WINDOW_DAYS days as dictionaries with item_id, user_id and timestamp. How you query the events depends on where they are stored, see querying event data.

Step 2 · Compute

Count distinct users per item

compute_trending() is plain Python. If your events carry other fields, such as a media type, filter on them here.

Step 3 · Store

Save the list in Dragonfly

The task writes the ranked list to one key. The key includes your codops and the algorithm name, so lists from different organisations or algorithms never collide.

Step 4 · Serve

Return the first N items

The endpoint reads the same key and returns the first amount items. It does no computing, so it stays fast.

import json
from collections import defaultdict
from datetime import datetime, timedelta, timezone

from pipe_algorithms_lib.compute import peach
from pipe_algorithms_lib.connections import get_redis_client_v2

CODOPS = "your_codops"
ALGORITHM = "trending"
KEY = f"{CODOPS}:{ALGORITHM}"   # the task writes it, the endpoint reads it
WINDOW_DAYS = 7
KEEP = 100


def load_play_events(since: datetime):
    """Step 1. Return dicts with item_id, user_id and timestamp."""
    raise NotImplementedError("query your play events here")


def compute_trending(events, keep: int = KEEP):
    """Step 2. Rank items by distinct users."""
    users = defaultdict(set)
    for e in events:
        users[e["item_id"]].add(e["user_id"])
    ranked = sorted(users.items(), key=lambda kv: len(kv[1]), reverse=True)
    return [{"item_id": i, "score": len(u)} for i, u in ranked[:keep]]


@peach.task(py_env="base", cron="0 * * * *")
def compute_trending_task():
    since = datetime.now(timezone.utc) - timedelta(days=WINDOW_DAYS)
    items = compute_trending(load_play_events(since))
    # Step 3
    get_redis_client_v2(env="prod").set(KEY, json.dumps(items))


@peach.endpoint(name="get-trending", route_prefix="/trending", py_env="base")
def get_trending_endpoint(amount: int = 10):
    # Step 4
    raw = get_redis_client_v2(env="prod").get(KEY)
    return json.loads(raw)[:amount] if raw else []

Helper functions have to stay in the same file as the task and the endpoint. How the client chooses between dev and prod is explained in Dragonfly and in dev and prod environments.

Try it

  1. Run compute_trending_task() from PEACH Lab and check the key with Redis Insight.
  2. Call get_trending_endpoint(amount=5) and check that you get five items.
  3. Push to the default branch. The task is scheduled and the endpoint is deployed to dev, see going to production.

Success

You now have a non-personalised list that updates every hour. Use it as the fallback for your personalised endpoints, and apply business rules such as a kill switch on top.