Design a Scalable Video Like-Count Engine for Viral Bursts
System DesignModel answerLast updated
Architect a high-performance system to handle user video likes, user engagement tracking, and extreme traffic bursts on viral content.
Design the backend services and storage infrastructure for the "like" reaction feature on a global video platform.
Functional Requirements
- Toggle Like State: Logged-in users can add or remove a like on a video.
- Retrieve Total Likes: Any viewer (authenticated or anonymous) can view the current count of likes on a video page.
- Retrieve Viewer State: Logged-in users can view whether they have currently liked the video being watched.
- User Activity Ledger: Logged-in users can request a paginated history of all videos they have liked.
Non-Functional Requirements & Constraints
- High Throughput & Low Latency: The system must handle hundreds of thousands of read requests per second globally, with video page counter lookups returning in under 30 ms.
- Viral Traffic Spikes: Popular video releases or breaking events can trigger sudden localized bursts of up to 100,000 like updates per second on a single video entity.
- Strict Deduplication & Idempotency: Each user may contribute at most 1 like to a video's aggregate count. Network retries or duplicate UI interactions must not corrupt the total count.
- Read-Your-Own-Writes for User State: A user who likes a video must immediately see the liked state reflected on their interface upon page reload or navigation, even if the public counter updates asynchronously.
Detail your data storage schemas, read/write pipeline architectures, hot-key mitigation strategies, counter accuracy guarantees, and key system trade-offs.
Hints
Hint 1
Decouple the transactional state of user actions (user X liked video Y) from the aggregate counter calculation engine (total likes for video Y).
Hint 2
To solve single-key bottlenecks during viral bursts, combine write-ahead buffering with sharded counters or windowed aggregation queues.
Hint 3
Use read-your-own-writes consistency (or optimistic UI updates with user-level cache) for the active user's state, while allowing global aggregate counters to remain eventually consistent by a few seconds.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Requirements & Scale Estimates
Scale & Traffic Profile
- Daily Active Users (DAU): 600 million
- Total Catalog Size: ~5 billion videos
- Read Load (Video Pages): ~6 billion requests/day $\approx 70,000$ QPS average (Peak: ~180,000 QPS).
- Write Load (Likes/Unlikes): ~600 million events/day $\approx 7,000$ QPS average baseline.
- Viral Burst Peak: Up to 100,000 write requests/sec targeted at a single trending video key.
2. System Architecture
To prevent a single database row or cache key from locking during viral events, we separate the User Reaction State (Ledger) from the Aggregate Counter Engine.
+------------------------+
| Client Application |
+-----------+------------+
|
v
+------------------------+
| API Gateway |
+-----------+------------+
|
+-------------------------+-------------------------+
| |
v v
+--------------------------+ +--------------------------+
| Reaction Write Service | | Counter Read Service |
+------------+-------------+ +------------+-------------+
| |
+---------+---------+ |
| | |
v v v
+------+ +---------------+ +------------------+
| User | | Kafka Topic | | Edge / CDN |
| State| | (Raw Events) | | Cache Layer |
| Cache| +-------+-------+ +--------+---------+
+------+ | |
v v
+---------------+ +------------------+
| Stream Engine | | Multi-Tier Cache |
| (Flink/Spark) | | (Redis Counter) |
+-------+-------+ +--------+---------+
| |
+--------------+--------------+ |
v v v
+------------------+ +------------------+ +------------------+
| User History DB | | Sharded Counters | | Persistent Counter|
| (Cassandra) | | Buffer (Redis) | | DB (ScyllaDB) |
+------------------+ +------------------+ +------------------+
3. Data Models & Storage Tiering
A. Immutable Ledger / User History (Distributed Wide-Column NoSQL)
We use Apache Cassandra or ScyllaDB partitioned by user_id for fast pagination of a user's liked videos and quick lookup of user reaction state.
Table: user_liked_videos
CREATE TABLE user_liked_videos (
user_id uuid,
video_id uuid,
liked_at timestamp,
PRIMARY KEY (user_id, video_id)
) WITH CLUSTERING ORDER BY (video_id DESC);
Table: video_likers (Optional audit ledger, sharded by video_id)
CREATE TABLE video_likers (
video_id uuid,
user_id uuid,
liked_at timestamp,
PRIMARY KEY (video_id, user_id)
);
B. Persistent Aggregates (Key-Value / Document Store)
Stores the durable canonical count for each video.
Table: video_counters
CREATE TABLE video_counters (
video_id uuid PRIMARY KEY,
like_count counter
);
4. Detailed Component Design & Workflows
Write Path: Handling Viral Spikes & Ensuring Idempotency
When millions of users click "Like" on a viral video simultaneously, updating a single database row or cache key synchronously leads to catastrophic lock contention and connection pool exhaustion.
Step 1: Validation & Fast Deduplication
- User clicks Like on Video $V$.
- The request reaches the Reaction Write Service.
- The service checks the user's localized state in Redis (
user:{user_id}:likes).- If the state already matches the requested action (e.g., user already likes the video), the request returns success immediately (idempotent no-op).
Step 2: Event Ingestion & Streaming Aggregation
- The validated action is published to a high-throughput Apache Kafka topic (
video-like-events), partitioned byvideo_id. - A Stream Processing Engine (e.g., Apache Flink) consumes events over tumbling 1-second time windows.
- Flink aggregates actions per
video_id: $$\Delta_{\text{likes}} = \text{Count}(\text{LIKE}) - \text{Count}(\text{UNLIKE})$$ - Sharded Counter Updates (Hot-Key Mitigation):
- For normal videos, Flink flushes the aggregate delta directly to the Redis counter:
INCRBY video:{video_id}:count delta. - For detected hot videos (traffic exceeding threshold $T$), the counter is dynamically split across $S$ shards in Redis: $$\text{Key} = \text{video:}{video_id}:\text{shard_}{rand(1, S)}$$
- Writes are distributed uniformly across shards, avoiding bottlenecking a single key or Redis node.
- For normal videos, Flink flushes the aggregate delta directly to the Redis counter:
Incoming Stream (100k writes/s for Video A)
|
v
[ Kafka Topic ] -> Partitioned by video_id
|
v
[ Flink Aggregator Window (1s) ] -> Sums deltas per video
|
+---> Normal Video A ---> INCRBY video:A:count +12
|
+---> Hot Video B ---> INCRBY video:B:shard_3 +450
Step 3: Ledger Persistence
Simultaneously, an asynchronous sink processor writes the explicit (user_id, video_id, timestamp) record into the Cassandra user_liked_videos table to maintain the exact history ledger.
Read Path: High-Volume Count & User State Retrieval
1. Fetching Video Like Count (Public Viewer)
- Tier 1 (CDN Edge): For popular/public videos, responses are cached at CDN edge nodes with a low TTL (2–5 seconds). This absorbs up to 95% of incoming read traffic.
- Tier 2 (Redis Counter Cluster):
- If the video is standard: Read
video:{video_id}:count. - If the video is flagged as hot: Issue a multi-key query (
MGET) across all $S$ shards (video:{video_id}:shard_1..S) and sum the results in memory.
- If the video is standard: Read
- Tier 3 (Persistent DB): Fallback to
video_counterstable on cache miss and backfill Redis.
2. Fetching Viewer Reaction State ("Have I Liked This?")
- Latency SLA: $< 15\text{ ms}$.
- On video load, the client requests the user's state for the current
video_id. - The service checks the User State Cache (
user:{user_id}:likesusing a Redis Set or Bloom Filter for historical items). - If missing, it queries the
user_liked_videostable in Cassandra for(user_id, video_id)and populates the cache. - Optimistic Client Representation: The UI updates immediately upon user click. If the network request fails, the UI rolls back the state and notifies the user.
5. Counter Reconciliation & Abuse Mitigation
Counter Reconciliation Pipeline
Because stream buffers, network partitions, or transient message loss can cause distributed counters to drift over time, an offline batch worker ensures ultimate accuracy:
- Batch Sync Job: A periodic Spark/Hadoop job runs during off-peak hours or in micro-batches for recently active videos.
- It scans the immutable ledger (
user_liked_videosor raw audit logs), computes exact count $\sum \text{likes}$, and updatesvideo_counters. - If a drift threshold is passed (e.g., drift $> 0.1%$), the cache layer is silently updated with the true value.
Fraud & Abuse Prevention
- Rate Limiting: API Gateway enforces token bucket limits per authenticated
user_id(e.g., max 30 reaction toggles per minute) and IP rate limits for unauthenticated traffic. - Bot Filtering: An inline risk engine evaluates user signals (account age, device telemetry, watch-time ratio). Suspicious events are routed to a dead-letter queue for offline analysis rather than affecting live aggregate counters.
6. Trade-off Matrix
| Architecture Choice | Primary Benefit | Trade-off & Mitigation |
|---|---|---|
| Async Event Streaming (Kafka + Flink) | Decouples read/write loops; flattens extreme viral traffic spikes. | Global counts are eventually consistent by 1–3 seconds. (Acceptable for public metrics). |
| Dynamic Key Sharding in Cache | Prevents Redis hot-key memory/CPU bottlenecks on viral items. | Increases read overhead for hot keys ($S$ key lookups). Mitigated by CDN edge caching. |
| Separation of Ledger & Aggregate Storage | Optimizes schema structures independently for fast range queries vs high-speed increments. | Dual-write path complexity. Resolved using Kafka as single source of event ingestion. |