Sub topic 12
Catalog, search and recommendations
This chapter assumes you have read the storage and metadata chapter. It also assumes you know basic SQL, how a message queue delivers events, and how to read short Python snippets. The chapter covers the discovery layer of the platform: how viewers find something to watch before the player ever requests a segment.
Why discovery is a separate subsystem
The upload, transcoding and delivery chapters move bytes. Discovery moves decisions: which titles exist, which a viewer may see, which match a query, and which to show first. These workloads differ from video delivery in three ways.
- Requests are small JSON responses, not large media segments, so they hit application servers and databases rather than the CDN's bulk path.
- Read traffic is far higher than write traffic, but writes must become visible quickly. A new upload should be searchable within seconds or minutes.
- Correctness has several layers. A title must not appear if it is unpublished, geo-blocked or taken down, even if a stale index still contains it.
Plan for three components that share one source of truth: a catalog store, a search index, and a recommendation service.
The catalog
The catalog is the system of record for video metadata. Keep it in a relational database, or in a document store if your metadata varies a lot by content type. It holds the fields the playback and discovery paths need.
CREATE TABLE videos (
video_id BIGINT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
uploader_id BIGINT NOT NULL,
duration_s INTEGER,
language VARCHAR(8),
status VARCHAR(16) NOT NULL, -- uploaded, processing, published, removed
published_at TIMESTAMP,
manifest_url TEXT -- master playlist, set when packaging finishes
);
CREATE TABLE video_tags (
video_id BIGINT REFERENCES videos(video_id),
tag VARCHAR(64),
PRIMARY KEY (video_id, tag)
);
CREATE TABLE video_regions (
video_id BIGINT REFERENCES videos(video_id),
region CHAR(2),
PRIMARY KEY (video_id, region)
);The status column links discovery to the transcoding pipeline. A video moves to published only after the pipeline has produced a playable manifest. Search and recommendations must then filter on status = 'published'. Otherwise a viewer clicks a result and gets a playback error.
Serving catalog reads
A browse page or title page reads the same rows again and again. Use a cache in front of the database, keyed by video_id, with a short TTL (time to live) of a few minutes. Invalidate the key when the row changes. Use read replicas for list pages. For a catalog of tens of millions of titles, a single primary can handle the writes, because writes come from uploads and edits rather than viewers.
Pagination
Avoid OFFSET pagination on large lists, because the database still scans the skipped rows. Use keyset pagination. The client sends the last seen sort key, and the query continues from there with WHERE (published_at, video_id) < (?, ?) ORDER BY published_at DESC, video_id DESC LIMIT 20. This stays fast on page 500 and gives stable results while new titles arrive.
Search
A relational LIKE '%term%' query cannot use an ordinary index and does not rank results. Use a search engine built on an inverted index. An inverted index maps each term to the list of documents that contain it. OpenSearch and Elasticsearch are common choices, and many managed services exist.
Keeping the index in sync
The catalog stays the source of truth. The index is a derived copy, built from change events.
- A service writes a change to the catalog database.
- The change is published to a queue, either by the application after commit or by change data capture from the database log.
- An indexer consumes events and updates the search document.
- If the index is damaged or its mapping changes, a full rebuild reads the catalog and reindexes everything.
Make the indexer idempotent: applying the same event twice must give the same result. Use the video_id as the document ID and include a version, such as an update timestamp. Then out-of-order events cannot overwrite newer data with older data.
Querying
Searchable fields are usually title, description, tags, and cast or creator names. Give them different weights. A match in the title is worth more than a match in the description. Filters such as region and status do not affect ranking, so put them in a filter clause.
{
"query": {
"bool": {
"must": {
"multi_match": {
"query": "space documentry",
"fields": ["title^3", "tags^2", "description"],
"fuzziness": "AUTO"
}
},
"filter": [
{ "term": { "status": "published" } },
{ "term": { "regions": "DE" } }
]
}
},
"size": 20
}The query contains a deliberate typo. fuzziness lets the engine match documentary anyway. Add an autocomplete field, usually built from edge n-grams or a completion suggester, because viewers type short prefixes on TV remotes and phones.
Ranking beyond text match
Text relevance alone ranks poorly for video. Blend it with signals such as recent popularity, completion rate, freshness, and whether the viewer has already watched the title. Start with a simple weighted sum. Move to a learning-to-rank model only when you have click and play logs to train it.
Recommendations
Recommendations answer "what should this viewer watch next?" without a query. The common building blocks, from simplest to most involved, are:
| Approach | Idea | Strength | Weakness |
|---|---|---|---|
| Popularity | Show what is most watched, per region or genre | Works for everyone, trivial to build | Not personal |
| Item-to-item co-watch | Titles watched together by the same users are similar | Easy to explain, works for new users on a title page | Needs enough history per title |
| Matrix factorization | Learn vectors for users and titles from watch history | Captures taste patterns | Needs training pipeline and tuning |
| Content-based | Match on genre, tags, cast, text embeddings | Handles new titles | Can be too narrow |
The cold start problem affects every approach. A new title has no watch history, and a new user has no profile. Fall back to popularity for new users, and to content-based similarity for new titles.
A co-watch example
This script builds item-to-item similarity from watch histories using cosine similarity on co-occurrence counts. Each pair's count is divided by the square root of the product of the two titles' totals, so very popular titles do not dominate every list.
import math
from collections import defaultdict
from itertools import combinations
def build_cooccurrence(histories):
counts = defaultdict(lambda: defaultdict(int))
totals = defaultdict(int)
for history in histories:
items = set(history)
for item in items:
totals[item] += 1
for a, b in combinations(sorted(items), 2):
counts[a][b] += 1
counts[b][a] += 1
return counts, totals
def similar(item, counts, totals, k=3):
scores = {
other: c / math.sqrt(totals[item] * totals[other])
for other, c in counts[item].items()
}
ranked = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
return [(other, round(score, 3)) for other, score in ranked[:k]]
histories = [
["a", "b", "c"],
["a", "b"],
["a", "c", "d"],
["b", "c"],
["d", "e"],
]
counts, totals = build_cooccurrence(histories)
print(similar("a", counts, totals))
# [('b', 0.667), ('c', 0.667), ('d', 0.408)]At real scale this runs as a batch job (for example Spark) on a daily or hourly schedule. It does not run in the request path.
Online and offline split
Do the expensive work offline and serve precomputed results online.
- Offline: train models, compute similar-title lists and per-user candidate lists, and write them to a key-value store or cache.
- Online: the API fetches the candidate list for the viewer, removes titles that are unpublished, blocked in the viewer's region or already watched, applies light re-ranking, and returns the page.
This keeps response time in the tens of milliseconds and means a model outage degrades results instead of breaking the home page. If the personalized list is missing, return the popularity list.
Edge cases and common errors
- Stale results. The index and recommendation cache can lag behind the catalog. Always re-check
statusand region against the catalog, or a fast cache of it, before returning results. Take-downs for legal reasons must take effect immediately, so do not rely on the next reindex. - Duplicates. Several uploads of the same title, or several seasons, clutter results. Group by a series or canonical ID in the index.
- Feedback loops. If you only recommend popular titles, they get more views and become more popular. Reserve a small share of slots for exploration, such as new or niche titles.
- Privacy. Watch history is personal data. Store it under the same access controls and retention rules as account data, and honor deletion requests in the training pipeline too.
- Region and language. Filter by licensing region before ranking, not after. Otherwise a page of 20 results can shrink to 3.
Exercise
A video is taken down for a legal reason at 10:00. The search indexer is running about 5 minutes behind, and the recommendation cache refreshes hourly. How do you make sure viewers stop seeing the video at 10:00, and why is reindexing alone not enough?
Show answer
Set the catalog status to removed at 10:00 and check it at request time. The API gateway should filter every search and recommendation result against the catalog, or a short-TTL cache of it, before responding. Reindexing alone leaves two gaps: the index lags by 5 minutes, and the recommendation cache can hold the title for up to an hour. The request-time check closes both gaps. The indexer and the next cache refresh then remove the title permanently.
Exercise
Your catalog list page uses OFFSET 100000 LIMIT 20 and is slow. What do you change, and what does the client send for the next page?
Show answer
Switch to keyset pagination. The query becomes WHERE (publishedat, videoid) < (?, ?) ORDER BY publishedat DESC, videoid DESC LIMIT 20, backed by an index on (publishedat, videoid). The client sends the publishedat and videoid of the last item on the current page, and the database seeks directly to that position instead of scanning and discarding 100000 rows.