Detailed Component Design
Now we will deep deep dive into the following:
- How to prevent system against bot views and fradulent views:
- Problem: a bot or a fradulent user tries to view videos and refresh constantly
- Solution:
- Only send a view event to the server after user watches >= 30 sec, this already filters 99% of bot/fradulent activities,
- Furthermore apply IP based rate limiting, so in case request with same IP is keeps coming, the rate limiter will block/reject the request
- Addtionally, we also use deduplication views using userId + videoId,which is stored in redis with TTL. so same user's view cant be counted twice for the same video
- Optionally we can also add device fingerprinting i.e. track userid, ip, devideId, and if same device more than 1000 views with different accounts, flag that as suspicious or even reject requests from the device
- How do we ensure data is not lost when downstream services
- Problem: Redis have data that is not yet synved to DB, and redis crashes. how to prevent data loss?
- Solution:
- Use kafka durable event log
- Once an view event from kafka is consumed it is peristed for 7 days,
- So when redis crashes, we will follow this flow:
- A read request comes in for a video
- Check redis, no data in redis
- Fetch total view count from DB
- Store in redis
- Replay kafka events for that video -> this updates redis and redis is now rebuilt with correct view count
- Return result
- Tradeoff: the first read for the video after downstream services crahses will take some time to return response.
Redis Cache Invalidation - Here, we dont have to worry to much about cache invalidations because, we use write-back policy, meanign, each view write happens to redis first, so redis always have fresh data, the DB is synced later via Background worker.
- Hot video scalability:A video goets viral -> gets 500k views/sec, then this results in
- Problem: one kafka partition becomes hot - suppose the video id is video123, and partitioin hashing for it always produced same key, hence one partiition is overloaded
- Solution:
- Use key salting:
- to spread traffic, instead of sending id as video123, send video123_0, video123_1, video123_2 etc...
- Then apply hash on this idea, this ensures the 500k views are distributed accorss many partitions