Sub topic 9
Storing Media Files and Metadata
This chapter covers where a streaming platform keeps its bytes and its facts. It assumes you know the basics of object storage, relational and key-value databases, and HTTP caching. It also assumes you have read the earlier chapters on transcoding, bitrate ladders, and segmentation. Those chapters produce the files stored here, and the CDN chapter that follows reads from them.
Two kinds of data, two kinds of stores
A video platform stores two very different things.
- Media objects are large, immutable binary files: the original upload, the segments, the playlists, thumbnails, and subtitles. They are written once and read many times.
- Metadata is small, structured, and changes often: titles, owners, processing state, rendition lists, view counts, and permissions.
Putting both in one system is a common early mistake. A relational database is poor at serving multi-megabyte blobs, and object storage is poor at queries such as "all videos by this owner, newest first." The standard design uses an object store for media and a database for metadata, linked by keys.
Storing media in object storage
Object storage (such as Amazon S3, Google Cloud Storage, or a self-hosted system like MinIO) fits video well. It scales to petabytes, replicates data across failure zones, and serves ranged HTTP reads that a CDN can use directly as an origin.
Key layout
Design object keys so that everything for one video sits under one prefix, and so that each version of the output is separate:
source/{video_id}/original.mp4
vod/{video_id}/v1/master.m3u8
vod/{video_id}/v1/720p/index.m3u8
vod/{video_id}/v1/720p/seg_0000.ts
vod/{video_id}/v1/720p/seg_0001.ts
thumbs/{video_id}/v1/poster.jpgThis layout has several practical benefits:
- Deleting a video means deleting one prefix per area.
- A re-encode writes to
v2/and leavesv1/untouched, so playback never sees a half-written set of files. - The
video_idshould be a random or time-ordered ID, not a user-supplied title. Some object stores throttle on hot key prefixes, and random IDs spread load. Titles also change, while IDs must not.
Immutability and caching
Once a segment is written under a versioned path, never overwrite it. Immutable objects let you set long cache lifetimes, such as Cache-Control: public, max-age=31536000, immutable, without any invalidation problem. The exception is playlists for live or in-progress content, which change and need short lifetimes. The CDN chapter returns to this.
Storage tiers
Source files and segments have different access patterns, and object stores offer tiers priced accordingly.
| Data | Access pattern | Typical tier | Reason |
|---|---|---|---|
| Popular segments | Constant reads | Standard | Low read cost and latency |
| Old, rarely watched renditions | Occasional reads | Infrequent access | Cheaper storage, higher read fee |
| Original uploads | Read only on re-encode | Archive or infrequent access | You need them rarely but cannot lose them |
| Temporary transcode output | Short-lived | Standard with a lifecycle expiry rule | Cleaned up automatically |
Keep the original upload. It is the only copy without generational quality loss, and you need it when you add a new codec or a new rung to the ladder later. Storing every rendition forever costs more than most teams expect, so a lifecycle rule that moves cold content to a cheaper tier, or deletes rarely used high-bitrate renditions that can be regenerated, is a normal cost control.
Durability and replication
Object stores typically copy data across several devices in a region. That protects against disk failure but not against a regional outage or an accidental bulk delete. Decide what you need:
- Same-region replication is the default and is usually enough for segments you can regenerate from the source.
- Cross-region replication is worth the cost for original uploads, because they cannot be regenerated.
- Versioning or delete protection on the source bucket guards against operator mistakes.
Storing metadata
Metadata answers questions the player and the product need quickly. Typical records are described below.
A minimal data model
CREATE TABLE videos (
video_id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL, -- uploaded, processing, ready, failed
duration_ms BIGINT,
created_at TIMESTAMP NOT NULL,
current_ver INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE renditions (
video_id TEXT NOT NULL REFERENCES videos(video_id),
version INTEGER NOT NULL,
name TEXT NOT NULL, -- 360p, 720p, 1080p
codec TEXT NOT NULL, -- avc1.4d401f
bandwidth_bps BIGINT NOT NULL,
width INTEGER NOT NULL,
height INTEGER NOT NULL,
playlist_key TEXT NOT NULL, -- object key of index.m3u8
PRIMARY KEY (video_id, version, name)
);
CREATE INDEX videos_by_owner ON videos (owner_id, created_at DESC);The renditions table mirrors what the master playlist advertises. The database does not replace the playlist. The player reads the playlist from the CDN, and the database lets your backend list, audit, and delete renditions without parsing files.
Status as a state machine
The status column is the contract between the pipeline and everything else. A video moves from uploaded to processing to ready, or to failed. Only mark a video ready after every file for the current version is in object storage. Order matters:
- Write all segments and playlists to the new version prefix.
- Verify they exist, for example by listing the prefix and comparing counts.
- In one database transaction, insert the rendition rows and set
status = 'ready'andcurrent_verto the new version.
If the worker crashes between steps 1 and 3, the video stays processing, and the orphaned files are harmless because no record points to them. A periodic cleanup job can delete prefixes that have no matching database version.
Choosing the database
| Need | Fit |
|---|---|
| Rich queries, joins, transactions on a modest dataset | Relational database (PostgreSQL, MySQL) |
| Very high read volume by key, huge number of videos | Key-value or wide-column store (DynamoDB, Cassandra) |
| Text search over titles and descriptions | Search index, fed from the primary database |
| Counters such as views and likes | Separate counter store or aggregated stream, not row updates |
A relational database handles the core catalog well up to a large scale, and it keeps the ready-state transaction simple. Many teams add a cache such as Redis in front for hot lookups. Treat view counts separately. Incrementing a column on every play creates a write hotspot on popular videos. Batch the events through a stream and write aggregates periodically.
Keeping the two stores consistent
The two stores cannot share a transaction, so you must plan for partial failure. Two failure shapes appear.
- Orphaned objects. Files exist but no record points to them. This costs money but does no harm to playback. Clean up with a periodic sweep.
- Dangling records. A record says
ready, but files are missing. This breaks playback. Prevent it by writing objects first and the record last, as in the ordered steps above.
Deletion runs in the reverse order. Mark the record deleted first so that no new playback request is issued, then delete the objects, then remove the record. If you delete objects first, a player may fetch a manifest that points at missing segments.
Serving the playback request
When a player asks to watch a video, the playback API does the following:
- Looks up the video by
video_idand checksstatus = 'ready'. - Checks that the viewer is allowed to watch it.
- Builds the manifest URL from
current_verand the configured CDN host. - Returns that URL, and perhaps a signed token, to the player.
The API never streams video bytes itself. The player fetches the manifest and segments from the CDN, which reads from object storage on a cache miss. This keeps the metadata service small and cheap to scale, because each viewing session needs only a few API calls but thousands of segment requests.
Common mistakes
- Overwriting segments in place, which causes stale CDN copies and mismatched playlists.
- Marking a video
readybefore the final segment is uploaded. - Storing video bytes in the database.
- Using the title or filename as the key.
- Discarding the original upload to save space, then being unable to add a new codec.
- Updating a view counter on the main video row for every play.
Exercise
A worker finishes a re-encode of a video and must publish version 2. Describe the order of operations that avoids both orphan-caused playback errors and dangling records, and say what happens if the worker crashes after uploading half the segments.
Show answer
Upload all version 2 segments and playlists to the v2/ prefix, verify they are all present, then in one database transaction insert the version 2 rendition rows and set current_ver = 2 and status = 'ready'. Players keep using version 1 until that transaction commits. If the worker crashes after uploading half the segments, no record points to v2/, so playback is unaffected and the partial files are orphans that a cleanup sweep removes. The retry can safely rewrite v2/.
Exercise
Why should the database store object keys instead of full CDN URLs, and why should view counts not be incremented directly on the video row?
Show answer
Keys stay valid when the CDN hostname, bucket, or region changes, so you build URLs from configuration at request time. Incrementing a counter on the video row for every play makes a write hotspot on popular videos. Instead, collect play events in a stream and write aggregated counts periodically.