Schema Design for a Video Streaming Service
SQL & DataModel answerLast updated
Design a relational database schema for a large-scale video platform, addressing scalability, GDPR compliance, and analytics requirements.
You're building the database layer for a video streaming platform that serves billions of users and handles millions of concurrent streams.
Design a relational database schema that addresses:
-
Core entities: Define tables for users, content creators, videos, viewing activity, engagement (likes/comments), creator-viewer relationships, curated collections, and monetization events. Specify column types, constraints, and key relationships.
-
Data integrity: Establish primary and foreign key relationships, uniqueness guarantees, and strategies to prevent duplicate event recording when clients retry requests.
-
Compliance and lifecycle: Describe approaches for marking content as removed (supporting undo/audit trails) and implementing privacy regulations that require complete user data removal, including historical activity logs.
-
Performance at scale: Propose indexing and partitioning strategies for tables receiving thousands of writes per second. Explain how to support both transactional queries (user-facing reads/writes) and analytical workloads (business intelligence, recommendations) without performance interference.
-
Concrete examples: Provide SQL DDL for 3-4 high-traffic tables and show queries for: (a) daily watch duration per video, (b) most-watched videos by distinct viewers in the past week, (c) paginated comment retrieval with moderation metadata.
-
Multi-format content: Explain storage for multiple video encodings (different resolutions, formats) and experimentation data (which thumbnail variant a user saw).
Assume roughly 2 billion registered users, 1 billion videos, 5 billion daily viewing sessions, and peak traffic of 200,000 events per second.
Hints
Hint 1
Event tables with billions of rows need time-based partitioning; consider which columns appear in WHERE clauses
Hint 2
Prevent duplicate likes or view records through primary key design or uniqueness constraints on client-generated identifiers
Hint 3
For privacy deletion, distinguish between content soft-deletion (supports appeals) and irreversible user data erasure (cryptographic key destruction can make historical events unlinkable)
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Video Platform Database Design
Approach
This problem tests database modeling under real-world constraints: massive write volume, regulatory compliance, and simultaneous operational and analytical access patterns. Strong answers demonstrate understanding of the difference between entity tables (relatively static metadata) and event streams (append-heavy logs), and make explicit trade-offs between normalization, query performance, and compliance requirements.
Scale Context
Before designing, establish working assumptions:
- 2B registered accounts, 1B video catalog
- 5B viewing events daily (~60K/sec average, 200K/sec peak)
- Monetization events at comparable scale
- Read-heavy for metadata queries, write-heavy for behavioral events
These numbers immediately tell us that event tables cannot be queried directly in real-time; we need pre-aggregation and partitioning.
Schema Design
Entity Tables (Transactional)
Users & Content Ownership
CREATE TABLE accounts (
account_id BIGINT PRIMARY KEY,
email CITEXT UNIQUE NOT NULL,
display_name VARCHAR(100),
account_status VARCHAR(20) DEFAULT 'active'
CHECK (account_status IN ('active', 'suspended', 'closed')),
registration_ts TIMESTAMPTZ NOT NULL,
removed_at TIMESTAMPTZ
);
CREATE TABLE creators (
creator_id BIGINT PRIMARY KEY,
owner_account_id BIGINT NOT NULL REFERENCES accounts(account_id),
handle VARCHAR(30) UNIQUE NOT NULL,
removed_at TIMESTAMPTZ
);
CREATE INDEX idx_creator_owner ON creators(owner_account_id)
WHERE removed_at IS NULL;
CREATE TABLE content (
content_id BIGINT PRIMARY KEY,
external_slug VARCHAR(15) UNIQUE NOT NULL,
creator_id BIGINT NOT NULL REFERENCES creators(creator_id),
title TEXT NOT NULL,
description TEXT,
duration_sec INTEGER NOT NULL,
visibility VARCHAR(20) NOT NULL
CHECK (visibility IN ('public', 'unlisted', 'private')),
upload_status VARCHAR(20) NOT NULL
CHECK (upload_status IN ('processing', 'available', 'failed')),
published_ts TIMESTAMPTZ,
removed_at TIMESTAMPTZ,
created_ts TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_content_creator ON content(creator_id, published_ts DESC)
WHERE removed_at IS NULL AND visibility = 'public';
Encodings & Metadata
CREATE TABLE encodings (
encoding_id BIGINT PRIMARY KEY,
content_id BIGINT NOT NULL REFERENCES content(content_id),
resolution_height INTEGER NOT NULL,
codec VARCHAR(20) NOT NULL,
bitrate_kbps INTEGER NOT NULL,
format_flags JSONB, -- HDR, frame rate, etc.
storage_path TEXT NOT NULL,
UNIQUE(content_id, resolution_height, codec, format_flags)
);
CREATE TABLE labels (
label_id BIGINT PRIMARY KEY,
normalized_name VARCHAR(50) UNIQUE NOT NULL
);
CREATE TABLE content_labels (
content_id BIGINT NOT NULL REFERENCES content(content_id),
label_id BIGINT NOT NULL REFERENCES labels(label_id),
PRIMARY KEY (content_id, label_id)
);
CREATE INDEX idx_label_lookup ON content_labels(label_id, content_id);
Engagement & Collections
CREATE TABLE reactions (
account_id BIGINT NOT NULL REFERENCES accounts(account_id),
content_id BIGINT NOT NULL REFERENCES content(content_id),
reaction_type SMALLINT NOT NULL CHECK (reaction_type IN (1, -1)), -- like/dislike
reacted_ts TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, content_id)
);
CREATE INDEX idx_reactions_content ON reactions(content_id);
CREATE TABLE remarks (
remark_id BIGINT PRIMARY KEY,
content_id BIGINT NOT NULL REFERENCES content(content_id),
parent_remark_id BIGINT REFERENCES remarks(remark_id),
author_id BIGINT REFERENCES accounts(account_id), -- nullable after anonymization
message TEXT NOT NULL,
moderation_state VARCHAR(20) NOT NULL DEFAULT 'published'
CHECK (moderation_state IN ('published', 'flagged', 'hidden', 'removed')),
toxicity_score REAL DEFAULT 0,
flag_count INTEGER DEFAULT 0,
created_ts TIMESTAMPTZ NOT NULL DEFAULT now(),
removed_at TIMESTAMPTZ
);
CREATE INDEX idx_remarks_pagination ON remarks(content_id, created_ts DESC, remark_id DESC)
WHERE moderation_state = 'published' AND removed_at IS NULL AND parent_remark_id IS NULL;
CREATE TABLE subscriptions (
subscriber_id BIGINT NOT NULL REFERENCES accounts(account_id),
creator_id BIGINT NOT NULL REFERENCES creators(creator_id),
subscribed_ts TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (subscriber_id, creator_id)
);
CREATE INDEX idx_subscriptions_creator ON subscriptions(creator_id);
CREATE TABLE collections (
collection_id BIGINT PRIMARY KEY,
owner_id BIGINT NOT NULL REFERENCES accounts(account_id),
name VARCHAR(150) NOT NULL,
visibility VARCHAR(20) NOT NULL
);
CREATE TABLE collection_items (
collection_id BIGINT NOT NULL REFERENCES collections(collection_id),
ordering INTEGER NOT NULL,
content_id BIGINT NOT NULL REFERENCES content(content_id),
added_ts TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (collection_id, ordering),
UNIQUE (collection_id, content_id)
);
Event Tables (Append-Only, Partitioned)
Viewing Activity
CREATE TABLE playback_events (
session_uuid UUID NOT NULL,
event_day DATE NOT NULL,
content_id BIGINT NOT NULL,
viewer_token BYTEA NOT NULL, -- pseudonymous, derived from account via HMAC
session_start TIMESTAMPTZ NOT NULL,
watch_duration_ms INTEGER NOT NULL DEFAULT 0 CHECK (watch_duration_ms >= 0),
encoding_id BIGINT,
thumbnail_variant_id BIGINT, -- A/B test assignment
geo_country CHAR(2),
device_type VARCHAR(30),
PRIMARY KEY (event_day, session_uuid)
) PARTITION BY RANGE (event_day);
CREATE INDEX idx_playback_content ON playback_events(content_id, event_day);
-- Create daily partitions, potentially hash sub-partitioned by content_id
Monetization Events
CREATE TABLE ad_events (
ad_event_uuid UUID NOT NULL,
event_day DATE NOT NULL,
content_id BIGINT NOT NULL,
ad_unit_id BIGINT NOT NULL,
campaign_id BIGINT NOT NULL,
viewer_token BYTEA NOT NULL,
event_type VARCHAR(20) NOT NULL CHECK (event_type IN ('impression', 'click', 'skip')),
occurred_ts TIMESTAMPTZ NOT NULL,
PRIMARY KEY (event_day, ad_event_uuid)
) PARTITION BY RANGE (event_day);
Pre-Aggregated Metrics
CREATE TABLE daily_content_metrics (
metric_day DATE NOT NULL,
content_id BIGINT NOT NULL,
view_count BIGINT NOT NULL DEFAULT 0,
total_watch_sec BIGINT NOT NULL DEFAULT 0,
unique_viewer_sketch BYTEA, -- HyperLogLog for cardinality estimation
PRIMARY KEY (metric_day, content_id)
);
CREATE INDEX idx_metrics_content ON daily_content_metrics(content_id, metric_day DESC);
Key Design Decisions
Idempotency
Clients generate UUIDs for viewing sessions and ad events. Ingestion uses:
INSERT INTO playback_events (session_uuid, event_day, content_id, ...)
VALUES (...)
ON CONFLICT (event_day, session_uuid)
DO UPDATE SET watch_duration_ms = GREATEST(playback_events.watch_duration_ms, EXCLUDED.watch_duration_ms);
This makes retries safe—heartbeat updates converge to the maximum observed duration.
For reactions, the composite PK (account_id, content_id) naturally provides idempotency; a second "like" is an upsert.
Soft Deletion vs. Hard Deletion
Soft deletion (removed_at timestamp):
- Applies to content, remarks, and creator profiles
- Supports moderation appeals and audit requirements
- Partial indexes (
WHERE removed_at IS NULL) keep queries fast
Hard deletion (GDPR/privacy):
- When a user exercises deletion rights, we must erase all linkable data
- Strategy: cryptographic key destruction
- Event tables store
viewer_token = HMAC(user_secret, account_id)instead ofaccount_id - A small
account_secretstable holds the HMAC key per user - On erasure: delete the secret, then billions of historical events become permanently unlinkable without rewriting partitions
- Also delete PII from
accounts, nullifyauthor_idin remarks, remove reaction/subscription rows
- Event tables store
Partitioning Strategy
Event tables partition by day because:
- Queries almost always filter by time range
- Old partitions can be detached, compressed, or archived to cold storage
- Partition pruning drastically reduces scan cost
Within each day partition, hash sub-partitioning by content_id (e.g., 64 buckets) distributes hot videos across multiple physical segments, reducing write contention.
OLTP vs. Analytics Separation
Transactional queries hit entity tables and recent event partitions directly.
Analytics workloads read from:
- Materialized aggregates (
daily_content_metrics) updated via batch jobs or change-data-capture streams - Replicated warehouse (columnar store like Redshift, BigQuery) receiving events via streaming pipelines (Kafka → warehouse)
- Probabilistic structures: HyperLogLog sketches for unique viewer counts (can't sum cardinality across days without sketches)
This separation prevents long-running analytical scans from blocking write throughput.
Sample Queries
(a) Daily watch duration per video
SELECT content_id, SUM(total_watch_sec) AS total_watch_seconds
FROM daily_content_metrics
WHERE metric_day = '2026-01-15'
GROUP BY content_id;
(b) Top N videos by unique viewers, last 7 days
WITH weekly AS (
SELECT content_id,
hll_union_agg(unique_viewer_sketch) AS viewer_sketch
FROM daily_content_metrics
WHERE metric_day BETWEEN CURRENT_DATE - 7 AND CURRENT_DATE - 1
GROUP BY content_id
)
SELECT content_id, hll_cardinality(viewer_sketch) AS estimated_unique_viewers
FROM weekly
ORDER BY estimated_unique_viewers DESC
LIMIT 100;
(Note: hll_* functions are PostgreSQL extension; alternative is to union sketches in application code)
(c) Paginated comments with moderation data
SELECT remark_id, message, author_id, toxicity_score, flag_count, created_ts
FROM remarks
WHERE content_id = 987654321
AND moderation_state = 'published'
AND removed_at IS NULL
AND parent_remark_id IS NULL
AND (created_ts, remark_id) < ('2026-01-15 10:30:00', 555555) -- keyset pagination
ORDER BY created_ts DESC, remark_id DESC
LIMIT 20;
Keyset pagination (using the last seen (created_ts, remark_id) tuple) avoids OFFSET performance degradation on deep pages.
Multi-Format Storage
The encodings table holds one row per rendition (1080p H.264, 4K VP9, HDR10, etc.). The UNIQUE constraint on (content_id, resolution_height, codec, format_flags) prevents accidental duplicate transcodes.
A/B test assignments (thumbnail_variant_id in playback_events) link to an experimentation framework table (not detailed here) that maps variants to test cohorts. This enables analysis of click-through rates by thumbnail.
Complexity & Trade-offs
- Time complexity: Properly indexed queries are O(log n) for lookups, O(k) for range scans over k rows (partitions prune irrelevant data)
- Space complexity: Event tables dominate storage; partitioning + compression (e.g., Zstandard on older partitions) and tiered storage (hot SSD, warm HDD, cold S3) manage costs
- Write throughput: Hash sub-partitioning and append-only design support hundreds of thousands of writes/sec
- Consistency vs. performance: Reaction counters are eventually consistent (updated async from CDC), trading immediate accuracy for write scalability
Common Mistakes
- Storing
account_iddirectly in event tables, making GDPR deletion require rewriting billions of rows - Using
OFFSETfor pagination on large tables (O(n) cost even with indexes) - Attempting to
COUNT(DISTINCT viewer)across days by summing daily counts (cardinality doesn't compose—need HyperLogLog or similar) - Over-normalizing event tables with foreign keys, which slows bulk ingestion and creates cascading delete complexity
- No partitioning strategy, leading to table bloat and index maintenance overhead
This design balances correctness, performance, compliance, and operational practicality for a platform operating at scale.