At Brotes, photos took up 600 times more than text. At Savia Play, a platform of gardening and nature courses and documentaries, that ratio falls short: a single episode weighs more than all of Verdalia's product pages put together. In this lesson you will apply the eight-step method to a system dominated by storage and bandwidth. You will learn how a video is processed from the moment the editorial team uploads it until it can be watched, how quality adapts to each viewer's connection, how traffic is distributed with a CDN, and how content that costs money to produce is protected. The lesson ends by comparing the four systems of the module.

Óscar, architect at Savia Play, tells the story at the Valencia meetup. Savia Play is a fictitious company. A word of caution: copyright, content licenses, and viewing data, which is personal data, must be reviewed with legal and compliance professionals.

Step 1: Functional Requirements and Scope

Function Description Who uses it
Upload and ingest The editorial team uploads the original file of each title 12 people
Processing The original is converted to several qualities and split up The system
Catalog and search Courses by episode, documentaries, title pages, and a search engine Subscribers
Playback On television, computer, tablet, and phone, at the quality the connection allows Subscribers
Resume Continue where you left off, on any device Subscribers
Subscriptions and access Only those with an active subscription can play Subscribers
Viewing statistics What is watched, how much, and at what quality Editorial and technical teams

Live streaming is left out; it is a different problem: there the video is processed while it is being broadcast, and the delay is measured in seconds. Downloads for offline viewing and user-uploaded content are left out. And recommendations, which belong to the lesson “Architectures for Systems with Artificial Intelligence,” in Module 8.

Step 2: Quality Attributes and Scenarios

Scenario Stimulus Expected response
SS-1, performance A subscriber presses “Play” The video starts in under 2 seconds. Stalls do not exceed 0.5% of the time watched
SS-2, scalability A premiere draws 80,000 viewers, against the 48,000 of a Sunday No degradation
SS-3, availability The catalog fails Whoever was watching a video keeps watching it
SS-4, processing The editorial team uploads a 38-minute title Publishable in under 45 minutes
SS-5, security A subscriber shares the address of a video It stops working in 5 minutes
SS-6, cost A normal month The CDN costs less than €0.12 per subscriber

Scenario SS-6 is new in the course: cost, as a quality attribute with its own measure. At Verdalia, the infrastructure was €445, and a cap was enough. Here, every technical decision translates into thousands of euros.

Step 3: Scale Estimates

A video is measured by its bitrate: the megabits that each second of picture and sound takes up. The higher the resolution, the higher the bitrate.

# Bitrate ladder: resolution -> megabits per second
LADDER = {"240p": 0.4, "360p": 0.8, "480p": 1.4, "720p": 2.8, "1080p": 5.0}
ORIGINAL_MBIT = 40                      # the file the production company delivers
TITLES, AVERAGE_MINUTES = 4_200, 38
SUBSCRIBERS, HOURS_PER_MONTH = 320_000, 9
PEAK_VIEWERS = 48_000                   # Sundays at 10:00 p.m.
AVERAGE_SERVED_MBIT = 3.2               # not everyone watches 1080p
CDN_EUROS_PER_GB = 0.008
SECONDS_BETWEEN_REPORTS = 10            # the player reports its position


def gigabytes(mbit_per_second, seconds):
    return mbit_per_second * seconds / 8 / 1000


title_seconds = AVERAGE_MINUTES * 60
print("A 38-minute title")
for quality, mbit in LADDER.items():
    print(f"  {quality:>6}  {mbit:4.1f} Mbit/s  {gigabytes(mbit, title_seconds):5.2f} GB")
gb_qualities = gigabytes(sum(LADDER.values()), title_seconds)
gb_original = gigabytes(ORIGINAL_MBIT, title_seconds)
print(f"  The five qualities: {gb_qualities:.2f} GB   The original: {gb_original:.1f} GB")

print(f"Catalog: {TITLES * AVERAGE_MINUTES / 60:.0f} hours")
print(f"  Qualities, in hot storage: {TITLES * gb_qualities / 1000:.1f} TB")
print(f"  Originals, in cold storage: {TITLES * gb_original / 1000:.1f} TB")

peak_gbit = PEAK_VIEWERS * AVERAGE_SERVED_MBIT / 1000
print(f"Bandwidth at the peak: {peak_gbit:.1f} Gbit/s")
gb_per_month = SUBSCRIBERS * gigabytes(AVERAGE_SERVED_MBIT, HOURS_PER_MONTH * 3600)
print(f"Monthly traffic: {gb_per_month / 1e6:.2f} PB   CDN: €{gb_per_month * CDN_EUROS_PER_GB:.0f} a month")
print(f"Position reports at the peak: {PEAK_VIEWERS / SECONDS_BETWEEN_REPORTS:.0f} writes per second")
print(f"Segment requests at the peak, with 6 s segments: {PEAK_VIEWERS / 6:.0f} per second")

Output:

A 38-minute title
    240p   0.4 Mbit/s   0.11 GB
    360p   0.8 Mbit/s   0.23 GB
    480p   1.4 Mbit/s   0.40 GB
    720p   2.8 Mbit/s   0.80 GB
   1080p   5.0 Mbit/s   1.43 GB
  The five qualities: 2.96 GB   The original: 11.4 GB
Catalog: 2660 hours
  Qualities, in hot storage: 12.4 TB
  Originals, in cold storage: 47.9 TB
Bandwidth at the peak: 153.6 Gbit/s
Monthly traffic: 4.15 PB   CDN: €33178 a month
Position reports at the peak: 4800 writes per second
Segment requests at the peak, with 6 s segments: 8000 per second

Explanation:

  • LADDER is the bitrate ladder: the versions of each title, from lowest to highest bitrate.
  • gigabytes turns a bitrate and a duration into a size: megabits per second, times seconds, divided by 8 bits per byte, divided by 1,000.
  • The monthly traffic comes from three figures: subscribers, hours watched per month, and average served bitrate.

Interpretation:

  • Storage is large, but it is not the problem. The entire catalog takes up 60 TB, less than Brotes adds in half a year.
  • The problem is bandwidth: 153.6 Gbit per second at the peak. That is almost 800 times Verdalia's and 22 times Brotes's. No data center of your own can serve it. Only a CDN.
  • The CDN costs €33,178 a month, €0.10 per subscriber. The rest of the infrastructure adds up to about €9,000. It is the main line item, and it depends on a design figure: lowering the average bitrate from 3.2 to 2.9 Mbit per second saves €3,100 a month.
  • The catalog receives almost no traffic. A viewer makes about ten requests to choose a title and then one segment request every 6 seconds for 38 minutes.

Step 4: High-Level Design

The system is divided into two planes, which fail and scale separately:

Control plane Data plane
What it does Decides: who can watch what, and where it is Delivers the bytes of the video
Components API, catalog, subscriptions, authorization, and progress Object storage and CDN
Traffic Small requests: thousands per second 153.6 Gbit per second
Consistency Strong in subscriptions None: the files do not change
If it fails No new video can be started Playback is cut off

The separation is the answer to scenario SS-3. The player, once it has the manifest, only talks to the CDN.

The Ingest Pipeline

flowchart LR
    editorial(["Editorial team"])
    upload["Resumable upload, in chunks"]
    originals[("Originals: cold storage")]
    tasks["Task queue"]
    subgraph workers["Workers, 0 to 20"]
        t1["Transcode to each quality"]
        t2["Segment and generate the manifests"]
    end
    failed["Failed task queue"]
    published[("Segments: hot storage")]
    catalog["Catalog: the title becomes publishable"]
    editorial --> upload --> originals
    upload -->|"Event: original received"| tasks
    tasks --> t1 --> t2 --> published
    t1 -.->|"After 3 attempts"| failed
    t2 -->|"The five qualities are ready"| catalog

The Playback Flow

sequenceDiagram
    participant R as Player
    participant A as API, control plane
    participant C as CDN, data plane
    participant O as Object storage
    R->>A: I want to watch the olive tree pruning
    A->>A: Checks the subscription and reads the progress
    A-->>R: Signed URL of the manifest and position 12 min 40 s
    R->>C: Requests the manifest
    C-->>R: List of qualities
    R->>C: Requests a segment in 240p
    C->>O: Cache miss, requests it from the origin
    O-->>C: Segment
    C-->>R: Segment, which stays stored in the CDN
    R->>C: Requests the next one, in 480p
    C-->>R: Segment, from the cache
    R->>A: Every 10 seconds, the current position

Step 5: Data Model and Choice of Data Stores

Data Store Reason
Catalog: titles, courses, and episodes Relational 4,200 titles. Clear relationships, and few writes
Subscribers, subscriptions, and charges Relational Money: transactions and strong consistency
Playback progress Key-value, with the key progress:<user>:<title> 4,800 writes per second of a tiny piece of data. Losing 10 seconds of progress does not matter
Segments and manifests Object storage, hot tier Read continuously
Originals Object storage, cold tier Read only to reprocess
Playback events Event streaming platform, and then an analytical store Thousands per second, append-only

Tiered storage charges according to access frequency. The hot tier costs more per gigabyte and nothing per read. The cold tier costs a fifth, but charges for every read and may take a while to serve it. The originals take up 80% of the space and no viewer ever sees them. They are kept because, the day a new quality is added, all of them will have to be processed again.

Progress shows why a store is chosen per piece of data. In the relational database, 4,800 writes per second would compete with the charges. In a key-value store they are trivial.

Step 6: Detailed Design of the Critical Points

The Processing Pipeline

A pipeline is a chain of stages in which each one receives the result of the previous one.

Stage What it does Detail
Resumable upload The 11 GB file is sent in 8 MB chunks. Each chunk is acknowledged separately A dropout means repeating one chunk, not the upload
Transcoding The original is converted to each quality on the ladder It is the heavy work: minutes of processor per minute of video
Segmentation Each quality is cut into 6-second segments A 38-minute title is 380 segments per quality
Manifests The list of qualities is written and, for each one, the list of segments Text files
Publication The catalog marks the title as publishable Only when all five qualities are there

It is the asynchronous processing of Module 3, with jobs of minutes instead of milliseconds. Whoever uploads the file does not wait. The tasks go to a queue, and a pool of workers consumes them. The pool adjusts itself according to the length of the queue, from 0 to 20 workers: with no tasks there are no machines, and nothing is paid.

import queue
import threading

QUALITIES = ["240p", "360p", "480p", "720p", "1080p"]
MAX_ATTEMPTS = 3


class TransientError(Exception):
    """A failure that may not repeat: a machine withdrawn, a network dropout."""


task_queue = queue.Queue()
lock = threading.Lock()
done = {}                                   # (title, quality) -> attempt on which it completed
counters = {"runs": 0, "retries": 0, "duplicates": 0, "discarded": 0}


def transcode(title, quality, attempt):
    """Simulates the work. Quality 720p fails the first time."""
    if quality == "720p" and attempt == 1:
        raise TransientError("the worker was withdrawn halfway through the task")
    return f"{title}/{quality}/manifest.m3u8"


def worker():
    while True:
        task = task_queue.get()
        if task is None:                    # stop signal
            task_queue.task_done()
            return
        title, quality, attempt = task
        with lock:
            duplicate = (title, quality) in done
            counters["duplicates" if duplicate else "runs"] += 1
        if not duplicate:
            try:
                transcode(title, quality, attempt)
                with lock:
                    done[(title, quality)] = attempt
            except TransientError:
                with lock:
                    if attempt < MAX_ATTEMPTS:
                        counters["retries"] += 1
                        task_queue.put((title, quality, attempt + 1))
                    else:
                        counters["discarded"] += 1          # would go to the failed queue
        task_queue.task_done()


threads = [threading.Thread(target=worker) for _ in range(3)]
for thread in threads:
    thread.start()

for quality in QUALITIES:
    task_queue.put(("olive-tree-pruning", quality, 1))
task_queue.join()                           # waits for them to finish, retries included
task_queue.put(("olive-tree-pruning", "480p", 1))   # the same message, delivered a second time
task_queue.join()
for _ in threads:
    task_queue.put(None)
for thread in threads:
    thread.join()

for quality in QUALITIES:
    print(f"{quality:>6}  completed on attempt {done[('olive-tree-pruning', quality)]}")
print(counters)
print("Title publishable:", all(("olive-tree-pruning", q) in done for q in QUALITIES))

Output:

  240p  completed on attempt 1
  360p  completed on attempt 1
  480p  completed on attempt 1
  720p  completed on attempt 2
 1080p  completed on attempt 1
{'runs': 6, 'retries': 1, 'duplicates': 1, 'discarded': 0}
Title publishable: True

Explanation:

  • queue.Queue is a thread-safe queue. get waits until there is a task, and task_done signals that it has finished. task_queue.join() blocks until every task delivered has been finished.
  • Each thread runs worker, a loop that takes tasks until it receives None. At Savia Play, each worker is a machine, and the queue, a managed service.
  • lock protects the two dictionaries, which the three threads share. Without it, two threads could modify them at the same time.
  • A task that fails goes back to the queue, with the attempt number increased. After the third it is abandoned, and in production it goes to a failed task queue, like emails.failed at Verdalia.
  • The duplicate check makes the worker idempotent. The queue delivers each message at least once, and sometimes twice. The second 480p task is recognized and not run.
  • There is one task per quality, not one per title. If 720p fails, the other four are not repeated. Real workers go further: they split the video into one-minute chunks and process them in parallel. A 38-minute title, which would keep one machine busy for 95 minutes, is ready in 22.

Adaptive Streaming

If the video were a single file, one quality would have to be chosen for everyone. Adaptive streaming solves the problem with two pieces: the segments, of 6 seconds, and the manifest, a text file that lists them. The two usual formats are HLS, from Apple, and MPEG-DASH, which is an open standard. They work over ordinary HTTP, and that is why any CDN serves them. This is the master manifest of a title, in HLS:

#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=400000,RESOLUTION=426x240
240p/manifest.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1400000,RESOLUTION=854x480
480p/manifest.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080
1080p/manifest.m3u8

Each quality has its own manifest, with the list of its 380 segments. The decision is made by the player, not the server. Before requesting each segment, it measures how fast the previous one arrived and how much video it has downloaded, and chooses.

LADDER = [("240p", 0.4), ("360p", 0.8), ("480p", 1.4), ("720p", 2.8), ("1080p", 5.0)]
MARGIN = 0.8                # only 80% of the measured bandwidth is counted on
BUFFER_TO_STEP_UP = 15      # seconds of video already downloaded
CRITICAL_BUFFER = 5


def choose_quality(current, measured_mbit, buffer):
    """Returns the position on the ladder of the quality for the next segment."""
    if buffer < CRITICAL_BUFFER:
        return 0                                        # emergency: the lowest quality
    sustainable = 0
    for position, (_, mbit) in enumerate(LADDER):
        if mbit <= measured_mbit * MARGIN:
            sustainable = position
    if sustainable > current:                           # step up one at a time, and with buffer
        return current + 1 if buffer >= BUFFER_TO_STEP_UP else current
    return sustainable                                  # step down all at once


# Measured bandwidth, in Mbit/s, and buffer, in seconds, before each segment
MEASUREMENTS = [(6.0, 8), (6.0, 16), (6.4, 22), (6.2, 27), (7.0, 30), (6.8, 30),
                (2.1, 24), (1.2, 12), (0.6, 3), (4.0, 7), (4.0, 17), (4.2, 21)]

current = 0                                             # start with the lowest quality
for number, (mbit, buffer) in enumerate(MEASUREMENTS, start=1):
    current = choose_quality(current, mbit, buffer)
    print(f"Segment {number:2}  measured {mbit:3.1f} Mbit/s  buffer {buffer:2} s  ->  {LADDER[current][0]}")

Output:

Segment  1  measured 6.0 Mbit/s  buffer  8 s  ->  240p
Segment  2  measured 6.0 Mbit/s  buffer 16 s  ->  360p
Segment  3  measured 6.4 Mbit/s  buffer 22 s  ->  480p
Segment  4  measured 6.2 Mbit/s  buffer 27 s  ->  720p
Segment  5  measured 7.0 Mbit/s  buffer 30 s  ->  1080p
Segment  6  measured 6.8 Mbit/s  buffer 30 s  ->  1080p
Segment  7  measured 2.1 Mbit/s  buffer 24 s  ->  480p
Segment  8  measured 1.2 Mbit/s  buffer 12 s  ->  360p
Segment  9  measured 0.6 Mbit/s  buffer  3 s  ->  240p
Segment 10  measured 4.0 Mbit/s  buffer  7 s  ->  240p
Segment 11  measured 4.0 Mbit/s  buffer 17 s  ->  360p
Segment 12  measured 4.2 Mbit/s  buffer 21 s  ->  480p

Explanation:

  • The buffer is the downloaded video that has not been watched yet. As long as there is buffer, the picture does not stop.
  • The loop looks for the highest quality whose bitrate fits within 80% of the measured bandwidth. The margin protects against an optimistic measurement.
  • The algorithm is asymmetric. It steps up one rung at a time, and only with 15 seconds of buffer. It steps down all at once. A worse picture is less annoying than a frozen picture.
  • The video starts at 240p, even if the connection could take more, because the smallest segment is the one that arrives first. It is the answer to scenario SS-1. In five segments, half a minute, it reaches 1080p.
  • At segment 7, the viewer has entered a tunnel. The quality drops to 480p, without interruption. At segment 9, the buffer is critical, and the minimum is requested.

CDN and Segment Caching

Decision Reason
Segments and manifests are kept in the CDN for a year They are immutable. If a title is reprocessed, its path changes
The signature is not part of the cache key If it were, the CDN would store one copy per viewer. The CDN validates the signature, and then looks up by path
Before a premiere, the first segments are preloaded The first viewers must not wait for the origin
An intermediate cache layer protects the origin A hundred CDN points requesting the same segment at once become a single request

Segments that are the same for everyone, that do not change, and that are requested millions of times: it is the ideal case for a cache, by the three conditions of Module 4. Savia Play's hit rate is 98.7%.

Content Protection

The CDN serves files to whoever requests them. So that only a subscriber receives them, the control plane hands out a signed URL: an address with an expiration date and a signature the CDN can check, without asking anyone.

import hashlib
import hmac

KEY = b"secret-key-shared-with-the-cdn"     # in production, in the secrets manager


def signature(path, expires, user_id):
    message = f"{path}|{expires}|{user_id}".encode("utf-8")
    return hmac.new(KEY, message, hashlib.sha256).hexdigest()[:32]


def sign_url(path, user_id, now, seconds=300):
    expires = now + seconds
    return f"{path}?expires={expires}&user={user_id}&signature={signature(path, expires, user_id)}"


def verify_url(url, now):
    path, _, query = url.partition("?")
    params = dict(pair.split("=") for pair in query.split("&"))
    expected = signature(path, int(params["expires"]), params["user"])
    if not hmac.compare_digest(expected, params["signature"]):
        return "rejected: invalid signature"
    if now > int(params["expires"]):
        return "rejected: expired"
    return "accepted"


NOW = 1_824_400_000                                 # a fixed instant, in seconds
url = sign_url("/v/olive-tree-pruning/720p/manifest.m3u8", "u-5310", NOW)
print(url)
print("Right away:          ", verify_url(url, NOW + 10))
print("After 6 minutes:     ", verify_url(url, NOW + 360))
print("Another quality:     ", verify_url(url.replace("720p", "1080p"), NOW + 10))
print("Tampered expiration: ", verify_url(url.replace(str(NOW + 300), str(NOW + 90_000)), NOW + 360))

Output:

/v/olive-tree-pruning/720p/manifest.m3u8?expires=1824400300&user=u-5310&signature=c406fdfb78c866ed11fc528eddae1463
Right away:           accepted
After 6 minutes:      rejected: expired
Another quality:      rejected: invalid signature
Tampered expiration:  rejected: invalid signature

Explanation:

  • hmac.new computes an authentication code with a secret key, the same mechanism we used for the pseudonyms in Module 5. Without the key, a valid signature cannot be forged.
  • The signature covers the path, the expiration, and the user. Changing any of the three invalidates it: that is why whoever extends the expiration fails.
  • hmac.compare_digest compares without revealing, through the time it takes, how many characters match.
  • The CDN has the key and verifies on its own. The control plane is not involved in every segment, and it can be down.
  • The example signs an exact path. In practice the title's prefix is signed, so as not to sign 1,900 files, and the player renews the signature before it expires.

A signed URL limits who downloads, but it does not prevent copying what was downloaded. That is what digital rights management, or DRM, is for: the segments travel encrypted, and a license server hands the key only to the authorized player. Savia Play applies it to the documentaries whose contracts require it.

Step 7: Bottlenecks, Failures, and Trade-offs

Situation What happens Defense
The CDN goes down Nothing can be watched Multi-CDN: two providers, and the player switches if one fails. It also helps to negotiate the price
A premiere with 80,000 viewers Everyone requests the same segments at once Preloading, and an intermediate cache layer
The control plane goes down No new videos start Those in progress carry on
The progress store goes down The position is not saved The player keeps it, and sends it when it comes back
40 titles arrive in one day The queue grows The worker pool scales up to 20. The 63 hours of work are done in just over 3
A task always fails A defective original Three attempts, failed queue, and an alert to the editorial team

Playback events are the observability of this system. The server cannot know whether the picture froze on a television: only the player knows. Each player sends events for start, stall, quality change, and end. They go to an event streaming platform, such as Apache Kafka, which keeps them in order and lets several consumers read them. One computes, minute by minute, the percentage of stalls per CDN provider and per region. Another feeds the editorial statistics. It is near-real-time analytics, separated from the subscriptions database for the same reason as at Verdalia.

The accepted trade-offs: storing five versions of every title, starting every video at poor quality so that it starts sooner, depending on two external providers for the main service, and a delay of up to 45 minutes between upload and publication. Optimizing a €33,000 bill is a discipline in itself, which we will study in the lesson “FinOps and Sustainable Architecture,” in Module 8.

Step 8: Evolution and Recorded Decisions

Year Subscribers Decision Reason
2021 8,000 A contracted video platform, which did everything Four people. Building a pipeline of their own made no sense
2023 90,000 Own processing pipeline, with a CDN The contracted platform charged per minute watched: €21,000 a month
2025 210,000 Second CDN A 50-minute outage of the single provider, on a Sunday night
2026 280,000 Progress in a key-value store, and events on a streaming platform The position reports were saturating the subscriptions database
2027 320,000 Ladder revised per title A whiteboard-and-voice course needs less bitrate than a documentary

The first decision is the most instructive. For two years, Savia Play had no video architecture: it bought one. It built one when a figure justified it.

The Four Systems of the Module, Compared

Verdalia Rutalia Brotes Savia Play
What it is Online store Parcel delivery Social network Video on demand
Technical team 3 people 45, in 6 teams 85, in 11 teams 30, in 4 teams
Dominant attribute Availability and maintainability Maintainability and team autonomy Read scalability Delivery performance and cost
Load pattern Campaign peaks, with a date Constant, with a campaign. One function concentrates 71% 400 reads per write, and viral peaks Daily peak, at 10:00 p.m. Few requests, enormous ones
Peak 151 requests per second 344 tracking queries per second 417 feeds per second, 7 Gbit/s 153.6 Gbit/s
Stores PostgreSQL, cache, queues, and objects One database per service Relational, wide-column, cache, objects, and search Relational, key-value, tiered objects, and event streaming
Consistency Strong at the checkout Sagas between services Eventual almost everywhere Strong in subscriptions. The rest is immutable
Style Modular monolith, with one service Monolith migrating to services Services and events Control plane, data plane, and asynchronous pipeline
Biggest risk Single payment gateway Distributed monolith The account with millions of followers The CDN bill and the CDN going down

All four use the same pieces: load balancers, caches, queues, databases, and CDNs. There is none you did not know before starting the module. What changes is which of them carries the weight, and that is decided by the first three steps of the method.

Common Mistakes and Tips

  • Serving video from the application servers. The data plane belongs to the CDN.
  • Transcoding inside the upload request. It is work of minutes: it goes to a queue.
  • One task per title. A failure at the end forces you to repeat everything. Small tasks are cheap to retry.
  • Including the signature in the cache key. The hit rate drops to almost zero, and the bill multiplies.
  • Deleting the originals to save money. It prevents adding a quality or a format in the future.
  • Storing progress in the payments database. The least important piece of data drowns the most important one.
  • Measuring quality from the server. Only the player sees the stalls.
  • Practical tip. First calculate the cost per user per month of each decision. In a system dominated by bandwidth, it is the best design indicator.

Exercises

Exercise 1: Adding 4K Quality

The editorial team wants to offer the 600 documentaries, of 52 minutes on average, in 4K, at 16 Mbit per second. It is estimated that, at the peak, 10% of viewers would use it instead of 1080p. Calculate, with the lesson's constants and functions, the additional storage, the increase in bandwidth at the peak, and the additional monthly CDN cost, assuming traffic grows in the same proportion as the peak.

Exercise 2: A Cache That Does Not Hit

After a configuration change, the CDN's hit rate drops from 98.7% to 4%, and object storage starts responding slowly. The change added the user parameter to every segment, “for the statistics.” Explain what happened and how you would fix it.

Solutions

Solution to Exercise 1

MBIT_4K, DOCUMENTARIES, MINUTES = 16, 600, 52
gb_title = gigabytes(MBIT_4K, MINUTES * 60)
print(f"One documentary in 4K: {gb_title:.2f} GB. All 600: {DOCUMENTARIES * gb_title / 1000:.2f} TB")

viewers_4k = PEAK_VIEWERS * 0.10
extra_gbit = viewers_4k * (MBIT_4K - 5.0) / 1000
print(f"Peak: {extra_gbit:.1f} Gbit/s more, up {extra_gbit / peak_gbit:.0%}")
print(f"CDN: €{gb_per_month * CDN_EUROS_PER_GB * extra_gbit / peak_gbit:.0f} more a month")

Output:

One documentary in 4K: 6.24 GB. All 600: 3.74 TB
Peak: 52.8 Gbit/s more, up 34%
CDN: €11405 more a month

Storage hardly counts: 3.74 TB more, on top of 60. The cost is in the delivery. Each 4K viewer consumes 11 Mbit per second more than in 1080p, and 10% of them is enough to raise the peak by 34% and the bill by €11,405 a month. The decision is a business one: if 4K attracts or retains subscribers worth more than that amount, it pays off. A middle way is to offer it on a higher-priced plan. Common mistake: evaluating a new quality by what it takes up, and not by what it costs to serve.

Solution to Exercise 2

The CDN identifies each file by its cache key, which by default is the full address, with its parameters. When user is added, the same segment has a different address for each viewer, and the CDN stores one copy per viewer. Almost every request is a miss, and reaches the origin. Object storage goes from serving 1.3% of the requests to 96%: about 70 times more.

The fix has two parts. The cache key must be only the path: the CDN validates the signature and discards the parameters before looking up. And statistics must not travel in the segment's address: that is what playback events are for, which the player sends to the control plane. There is a more general lesson: in this system, a one-line configuration change can multiply the bill. Changes to the CDN deserve the same review and the same gradual rollout as code.

Conclusion

In this lesson you have applied the eight-step method to a video platform, and you have seen a system in which the weight falls on bandwidth. You have calculated that a title takes up 2.96 GB in its five qualities, and that a Sunday peak demands 153.6 Gbit per second. You have met the processing pipeline, with resumable upload, tasks per quality, retries, and idempotency. You have seen how adaptive streaming lets the player choose the quality of each segment, how those segments are cached in the CDN, and how a signed URL limits access without consulting the control plane. And you have distinguished the control plane from the data plane, which fail separately.

The comparison table closes the four cases. A store, a parcel delivery company, a social network, and a video platform, built with the same pieces and arranged in four ways, because their requirements, their scenarios, and their numbers are different.

So far you have read how others reason. Marta returns from Valencia with four architectures in her notebook and one certainty: the method is learned by using it. In the next lesson, “Practical Exercises,” it is your turn: six problems of increasing difficulty, with the course's universe as the setting, to design, measure, secure, size, and decide on your own.

© Copyright 2026. All rights reserved