Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 5 · Concept · 20 min · revision 1

Ranking, media and graceful degradation

Add ranking as a pipeline of narrowing stages, fit it into a latency budget with a timeout and a newest-first fallback (simulated), keep media bytes off the feed path with object storage and a CDN, and order the feed's degraded modes by what each one sacrifices.

Contentsand lesson path

What you will learn

  • Add ranking and media to the feed without breaking latency targets, and describe the degraded modes.

Prerequisites: Caching Strategies

01. Why it matters

The feed from lesson 3 shows posts newest first, as text. Product now wants two things: the most relevant posts near the top, and photos and videos in posts. Both sit on the read path, which has a 300 ms p99 target, and both add services that can be slow or fail. So the questions are how to add them without breaking the target, and what the feed does when one of them is in trouble. This lesson answers both, and ends with a list of degraded modes you can put in a design doc.

02. Ranking as a pipeline of narrowing stages

The first idea is to score every recent post from every followed account with the best model you have. For a reader who follows 20 quiet accounts, that is fine. For one who follows 300 accounts, including a few that post all day, it can mean thousands of model calls per feed open, and a heavy model's time per candidate multiplied by thousands can easily exceed a few hundred milliseconds.

The way out is to spend little effort on many posts and much effort on few. Ranking becomes a pipeline in which each stage narrows the list for the next, more expensive one:

Diagram · a ranked feed read, stage by stage
candidate generation   timeline ids + big-account outboxes      ~500 posts, cheap
        |
feature hydration      author affinity, post age, engagement    per candidate
        |
scoring                a model scores each post on its own      ~500 scores
        |
re-ranking             diversity, seen-post removal, blocks     one ordered list
        |
page                   post bodies + media URLs (lesson 3)      20 posts

Candidate generation gathers a few hundred posts cheaply; here, that is lesson 3's timeline and outboxes. Feature hydration fetches what the model needs about each candidate. Scoring gives each candidate a number, one at a time. Re-ranking works on the whole scored list: it enforces rules that only make sense for a list, such as no more than two posts in a row from one author, and removes posts the reader has already seen or should not see.

This shape is published, not guessed. A 2016 paper by YouTube engineers described a candidate-generation network that picks hundreds of videos out of millions and a separate ranking network that scores them with richer features. The home-mixer service in the recommendation code X published in 2023 lists candidate generation, feature hydration, scoring, filters and heuristics (author diversity, deduplication, visibility) and mixing. Neither tells you what any company runs today; the stages are what to borrow, not the models.

Ranking also changes pagination. A ranked list is not ordered by post id, so lesson 3's id cursor no longer works. One approach is to rank once per session, keep the ranked list of ids for a few minutes, and page through that stored list: positions in a list that no longer changes do not shift.

03. Fitting ranking into the latency budget

A latency budget splits the p99 target between stages, so each team knows its share. Scoring is the stage most likely to blow it, and the usual protection is a timeout with a fallback: if features and scoring are not done in time, serve the candidates newest first. The script below simulates 100,000 reads with stage times drawn from seeded distributions. The times are invented stand-ins for measurements, not benchmarks. Before running it, predict: when 25% of scoring calls take about 300 ms, does a read without a timeout stay under the 300 ms target at p99?

Python · budget.py
"""A ranked feed read, simulated with and without a ranking timeout (Python 3.12).

Stage times come from seeded lognormal draws. They are invented stand-ins for
measurements, chosen to show the shape of the problem, not benchmarks."""
import math
import random
import statistics

REQUESTS = 100_000
rng = random.Random(11)


def ms(median: float, spread: float) -> float:
    return rng.lognormvariate(math.log(median), spread)


def feed_read(slow_share: float, timeout: float | None) -> tuple[float, bool]:
    """Return (milliseconds, served without ranking?) for one feed read."""
    ids = ms(6, 0.4)  # timeline ids plus big-account outboxes
    features = ms(15, 0.4)  # features for a few hundred candidates
    slow = rng.random() < slow_share  # the ranking service is in trouble
    scoring = ms(300, 0.3) if slow else ms(30, 0.35)
    rerank = 2.0  # diversity rules and visibility filters (blocks, removals)
    posts = ms(10, 0.4)  # post bodies and media URLs for one page
    ranked = features + scoring
    if timeout is not None and ranked > timeout:
        return ids + timeout + rerank + posts, True  # newest first, still filtered
    return ids + ranked + rerank + posts, False


print(f"{'ranking health':<16}{'timeout':>8}{'p50':>6}{'p99':>6}{'p99.9':>7}"
      f"{'unranked':>10}")
for label, slow_share in (("normal", 0.002), ("25% calls slow", 0.25)):
    for timeout in (None, 120.0, 80.0):
        runs = [feed_read(slow_share, timeout) for _ in range(REQUESTS)]
        q = statistics.quantiles([t for t, _ in runs], n=1000)
        unranked = sum(fell_back for _, fell_back in runs) / REQUESTS
        shown = "none" if timeout is None else f"{timeout:.0f} ms"
        print(f"{label:<16}{shown:>8}{q[499]:>6.0f}{q[989]:>6.0f}{q[998]:>7.0f}"
              f"{unranked:>10.1%}")
Terminal
python3 budget.py
Expected output (simulated milliseconds, seeded)
ranking health   timeout   p50   p99  p99.9  unranked
normal              none    66   111    354      0.0%
normal            120 ms    66   110    139      0.2%
normal             80 ms    66   103    112      2.5%
25% calls slow      none    72   547    699      0.0%
25% calls slow    120 ms    72   150    159     24.9%
25% calls slow     80 ms    72   110    119     26.8%

It does not: without a timeout, p99 reaches 547 ms. With an 80 ms timeout it is 110 ms, because no read waits longer than 80 ms for features and scoring, at the price of 26.8% of reads served unranked. The fallback is not free on a healthy day either: at 80 ms, 2.5% of normal reads lose their ranking, because ordinary variation in scoring crosses the line. At 120 ms that falls to 0.2%, and the incident p99 is 150 ms, still well inside the target. The timeout is a dial: set it from the measured p99 of the stage it protects, with room left for the stages after it, and recheck it when the model changes. A circuit breaker, as in circuit breakers, bulkheads and load shedding, can then stop calling a scorer that keeps timing out.

The simulation leaves out queuing: in a real incident, slow calls also hold threads and connections, which makes things worse than independent draws suggest.

04. Media: keep the bytes off the feed path

A feed page of 20 posts is a few kilobytes of ids, text and counters. Its photos can be megabytes, and a video far more. If those bytes travel through the feed service, the service's network and memory are spent on copying files, and every feed read gets slower. So the bytes take another path:

  1. The app uploads the file straight to object storage with a short-lived signed URL, as in large uploads and post-processing pipelines.
  2. A background job checks the file and makes variants once: a few image sizes, or video renditions at several bitrates.
  3. The post row stores only the object keys and sizes, as in blobs in object storage, metadata in a database.
  4. The feed response carries URLs that point at a CDN, and the app picks the variant that fits the screen, for example with the srcset attribute on the web. Each variant gets a new URL rather than being overwritten, so CDN copies can be kept for a long time.

In this design the feed service does not touch media bytes, and its latency stays tied to metadata. Private media needs signed URLs checked at the edge, covered in invalidation, versioned assets and signed URLs.

05. Degraded modes, from mildest to most drastic

Graceful degradation means doing less work, at lower quality, instead of failing. Google's SRE book gives a search example: answer from a subset of data held in memory, or use a less accurate but faster ranking algorithm when overloaded. For a feed, each degraded mode gives up something different, and that is how to order them:

  1. Serve stale. If fan-out workers fall behind, serve timelines as they are. The feed is minutes old but complete and in order. This gives up freshness.
  2. Drop ranking. If scoring is slow or down, serve candidates newest first, as the timeout above does. This gives up order, and every post is still there.
  3. Lower media quality. If the CDN or origin struggles, send smaller variants or placeholders. This gives up quality.
  4. Skip the big-account merge. If outbox reads overload, serve the pushed timeline alone. Posts from big accounts disappear entirely, because they were never pushed. Use it briefly, with an alert, and say so in the app if you can.
  5. Keep the last page and shed load. If the timeline cache itself is down, let the app keep showing the page it already has, rebuild timelines from the database at a capped rate, and reject excess requests quickly so that the rest can be served, as in how cascading failures happen.

Some work should not be degraded at all. Visibility filters for blocks and removed posts are a safety rule, not a quality feature: a fallback that skips them shows people content they asked not to see. That is why the fallback in budget.py still pays for re-ranking.

The SRE book adds two cautions. A degraded mode is a code path that rarely runs, so it may not work when you need it; exercise it on purpose, for example by running a few servers near overload. And monitor and alert when many servers enter a degraded mode, so a fallback does not silently become the normal path.

06. Check your understanding

Practice check · 3 questions

Ranking and degradation

Apply the pipeline, the budget and the degraded modes to new cases.

Q1. Product wants no more than two posts in a row from the same author. Where in a candidate, score and re-rank pipeline should this rule live?
Q2. A feed read spends up to 20 ms fetching candidates and up to 30 ms loading posts. Scoring usually takes 60 ms but sometimes 2 s, and has a 100 ms timeout with a newest-first fallback. About how long can the slowest read take?
Q3. Which degraded mode hides posts entirely, rather than delaying, reordering or shrinking them, and so needs a short time limit and an alert?
Practice only: not graded, not saved, not evidence.

07. Apply it

Finish the design doc for this skill's practice task with two sections:

  1. A latency budget. List every stage of your feed read with its share of the p99 target, the timeout of each call to another service, and the fallback when it fires. Change budget.py to your stages, and pick each timeout from the simulated trade-off between p99 and the share of degraded reads on a normal day.
  2. A degraded-mode table. For each mode, write what triggers it, what it gives up (freshness, order, quality or completeness), how users can tell, which alert fires, how it ends, and how often you will exercise it. Mark the work that must never be degraded.

Then compare your celebrity threshold from lesson 2 with your budget: does a read that merges the p99 number of big-account outboxes still fit?

08. Review prompt

Without looking back, explain in your own words:

  1. Why ranking is split into narrowing stages, and which kind of rule belongs in re-ranking rather than scoring.
  2. How a timeout with a fallback bounds the p99, and what it costs on a healthy day.
  3. Why media bytes never pass through the feed service, and what the post row stores instead.
  4. The degraded modes in order, what each gives up, and which work is never degraded.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check