System Design
Handbook.
Nine problems, each told the same way: the naive approach, the DSA evolution, then what production actually runs. Read in order — every lesson patches the previous one's weak spot.
Top K Elements the heavy hitters
We start with a simple problem: You have millions of videos, and you want to continuously display the "Top 10 Most Viewed" on the homepage. How do we maintain this ranking dynamically without melting the database?
1. The Naive Approach
If we just dump all videos into an array and sort them by view count in the database, we hit O(N log N) time complexity. If we do this every time someone loads the homepage, the CPU will instantly lock up. Sorting the entire database repeatedly is computationally wasteful.
2. The DSA Evolution (Min-Heap)
In a standard coding interview, you would use a Min-Heap of size K (10). As millions of videos stream in, you compare their view counts to the smallest video currently in the heap. If a new video has more views, you pop the smallest one out and insert the new one. This beautifully reduces the time complexity to a blazing fast O(N log K).
Why it fails in production: A Min-Heap is a "lossy" data structure. It is fantastic for static, known datasets, but terrible for streaming systems. Once a video is kicked out of the Top 10, the heap forgets it completely. If that forgotten video suddenly gets a million views an hour later and goes viral, the heap has no way to dynamically bubble it back to the top because it discarded the reference!
3. The Production Reality (Redis ZSET)
We need a data structure that tracks the rank of all active items continuously without forgetting them. For this, the industry standard is Redis Sorted Sets (ZSET). Under the hood, Redis combines two structures to give us the best of both worlds:
- Hash Map: Maps the
video_idto its exact numerical score. Finding a specific video's score takes perfectO(1)time. - Skip List: A probabilistic, multi-level linked list with "express lanes." It keeps all elements strictly sorted by score. This allows us to update a score and re-rank the item in exactly
O(log N)time, maintaining continuous order.
Production Tooling & Code
# Instantly add or update a video's view count in O(log N)
ZINCRBY videos:trending 100 "video_A"
# Instantly fetch the Top 10 videos with their scores in O(log N + K)
ZREVRANGE videos:trending 0 9 WITHSCORES Time-Based Ranking sliding windows
Redis ZSET is incredibly fast, but it has a fatal flaw: scores never expire. If a video accumulated 50 million views back in 2012, it will stay stuck at the top of the leaderboard forever. We want a "Top 10 in the last 24 hours" feed. How do we cleanly subtract old views as they age out?
1. The Naive Approach
We could store every single "view" event as an individual row with a timestamp in a relational database, and then run a query like SELECT video_id, COUNT(*) WHERE time > NOW() - INTERVAL '24 hours'. However, scanning millions of raw rows on the fly for every single user request will inevitably crash the database.
2. The Evolution (Time Buckets)
Instead of tracking individual views and losing the timing, we group incoming views into small Time Buckets (e.g., 5-minute intervals). We use a Time-Series Database (TSDB) like TimescaleDB (a PostgreSQL extension) or InfluxDB. These databases physically partition data on disk by time intervals, making range queries over time periods lightning fast.
Now, instead of scanning millions of individual rows, the database just adds up the sums of the pre-aggregated 5-minute buckets from the last 24 hours.
3. The Two-Layer Production Architecture
Even with a TSDB, we cannot have the user's mobile app querying the database directly. We must strictly separate the heavy write/compute path from the fast read path:
- Layer 1 — The Scratchpad: The TSDB safely ingests and groups the high-volume streaming data into 5-minute buckets.
- The Aggregator Worker: A background worker wakes up every minute and runs the 24-hour SUM query on the TSDB to fetch the Top 10 results.
- Layer 2 — The Serving Layer: The worker takes those final Top 10 results and blindly overwrites a tiny Redis ZSET (e.g.,
videos:rank:24h). The user API only reads from Redis, keeping the read path at perfectO(1)speed.
The TimescaleDB Query (run by the background worker)
SELECT video_id, SUM(views) as rolling_24h_views
FROM video_views_5m_buckets
WHERE time > NOW() - INTERVAL '24 hours'
GROUP BY video_id
ORDER BY rolling_24h_views DESC
LIMIT 10; Frequency Counting the viral event
We solved reading data fast. Now let's solve writing data fast. A global celebrity posts a video, and 500,000 people click "Like" within 10 seconds. How does the database survive this write tsunami?
1. The Naive Approach
Firing 500,000 UPDATE videos SET likes = likes + 1 commands directly at PostgreSQL. This immediately causes massive row-level locking contention. The database can only process one update to that specific video row at a time. The connections pile up, the database connection pool exhausts, and the entire API goes down.
2. The Evolution (Write-Behind Cache)
We intercept the massive traffic spike using RAM. When a user clicks like, we hit Redis with the atomic INCR command. Because Redis operates on a single-threaded event loop and is purely in-memory, it easily swallows over 100,000 increments per second sequentially without any locking overhead.
A background worker periodically reads the Redis count (e.g., 50,000), resets the Redis counter to 0, and sends exactly one bulk update to PostgreSQL. We successfully turned 50,000 database hits into 1.
3. The Production Reality (Rich Metadata & Durability)
There is a fatal flaw in relying purely on Redis Write-Behind: A "Like" isn't just an anonymous number. It is a relational fact (User X liked Video Y at Time Z). We need this metadata to ensure a user can't like a video twice. Furthermore, if this is an Ad Click system, a Redis crash before the worker flushes the data means lost revenue.
To balance instant UI feedback with bulletproof durability, the true production architecture splits the path:
- The Fast Path (Redis): We blindly
INCRa cached counter in Redis just so the frontend UI can update instantly and feel blazing fast to the user. - The Durable Source of Truth (Kafka): Simultaneously, the API writes a rich JSON event
{user_id, video_id, timestamp, action="like"}to a Kafka topic. Kafka safely and sequentially writes this event to a physical disk, guaranteeing zero data loss even if the database is currently on fire. - Micro-Batching (PgBouncer & COPY): A fleet of backend consumers read these events from Kafka at their own pace. They buffer the events in memory until they collect 10,000 likes or 5 seconds pass. They connect to PostgreSQL through a connection pooler (PgBouncer), which multiplexes thousands of incoming requests over a tiny pool of actual database connections. Finally, they bulk insert the data using PostgreSQL's native
COPYcommand (orexecuteBatch()), bypassing individual query parsing overhead entirely.
Global Leaderboards complex ranking
Now we shift from tracking abstract items (like videos) to tracking 50 million actual users playing a competitive video game. We can't just track the Top 10 anymore. Player #4,589,201 expects to open the app, instantly see their exact global rank, and see the specific players right above and below them.
1. The Solution (Redis ZSET to the Rescue)
Because Redis ZSET uses a Skip List under the hood, we can instantly jump to the exact middle of a 50-million item list without tearing the data structure apart.
ZREVRANK global_leaderboard user_892returns their exact numerical rank.ZREVRANGE global_leaderboard 45891 45893instantly fetches the player and their immediate neighbors.
2. The Curveball (Breaking Ties Fairly)
If Player A and Player B both achieve exactly 5,000 points, Redis breaks the tie by sorting their member strings (User IDs) alphabetically. This is a terrible user experience. In gaming, whoever achieved the score first should rank higher.
The Composite Score Trick: A Redis ZSET only accepts a single floating-point number as a score. We must mathematically fuse the Points and the Timestamp into one number. We do this by inverting the timestamp (subtracting the event time from a massive future date constant).
Score: 5000 points. Max Time Constant: 9999999999.
Player A hits 5000 pts at timestamp 1600000000.
Decimal: (9999999999 - 1600000000) = 8399999999.
Player A's Final Score: 5000.8399999999
Player B hits 5000 pts 5 seconds later at timestamp 1600000005.
Decimal: (9999999999 - 1600000005) = 8399999994.
Player B's Final Score: 5000.8399999994
Player A is mathematically higher! The 3rd Tie-Breaker (String Packing): Floating point precision only gives us ~15 significant digits. If we need a 3rd tie-breaker (like "Win Rate Percentage"), we run out of float space. Instead, we hijack Redis's alphabetical sorting fallback by prepending the win rate to the string ID. 095:user_123 naturally beats 040:user_456 in a descending search.
Caching & Eviction LRU vs. LFU
We are storing all this fast data in expensive RAM. Eventually, the RAM fills up to 100% capacity. When the next item needs to be cached, we have to brutally delete something to make room. Deleting the wrong item means a cache miss, forcing a slow, expensive database read.
1. The LRU Algorithm (Least Recently Used)
How it works (DSA): We use a Hash Map connected to a Doubly Linked List. When an item is read, we find it instantly via the Hash Map, snip it out of the list, and move it to the Head (Most Recently Used). When memory is full, we chop off the Tail.
The Production Flaw (Cache Pollution): Imagine it is 2:00 AM, and your data science team runs a background job to back up 50,000 old, dead movies. Because the job "reads" these movies, LRU dutifully moves every single one of them to the Head of the list. By 2:05 AM, all your popular active movies have been pushed off the Tail and deleted. The cache is entirely polluted with dead data.
Best used for: User Session Data (where relevance is strictly time-bound. If someone hasn't clicked anything in 30 minutes, they closed the tab).
2. The LFU Algorithm (Least Frequently Used)
How it works (DSA): We track a frequency counter on every item. The item clicked the fewest times historically is evicted first.
The Production Flaw (Viral Ghosts): An obscure movie goes massively viral in January, gets 10 million views, and then dies completely by August. Because its historical score is 10M, LFU will never delete it, even though no one is watching it anymore. It haunts your RAM forever. (Fix: We implement an exponential decay function to periodically halve all scores over time).
Best used for: Product Details (where relevance is based on overall global popularity, not just a recent random click).
3. The Production Reality (Approximated Eviction)
Maintaining millions of next and prev linked-list pointers consumes massive amounts of metadata memory. Redis doesn't use strict LRU/LFU Linked Lists. It uses Approximated Eviction. When memory is full, it randomly samples 5 keys, looks at their tiny internal timestamps or counters, and deletes the worst one among those 5. It is 99% as effective as strict LRU, but uses zero pointer memory! You enable this via maxmemory-policy allkeys-lru.
A Note on Netflix: Netflix does NOT cache 5GB .mp4 movies in Redis. Edge Servers (CDNs like Open Connect) cache physical 2-second video chunks on fast NVMe SSDs, sliding only the next few seconds of chunks into RAM. Redis is used purely in the backend to cache the metadata (user profiles, thumbnails, bookmark timestamps).
Search Autocomplete the trie
You go to YouTube and type "sys". Before you even lift your finger off the key, a dropdown instantly suggests "system design interview". How does the backend search billions of historical queries, rank them, and return the Top 10 in under 5 milliseconds?
1. The Naive Approach
Using a standard relational database with SQL: SELECT term FROM historical_searches WHERE term LIKE 'sys%' ORDER BY frequency DESC LIMIT 10. When you ask a B-Tree index for a prefix match, it has to scan massive chunks of the index, load all matching strings into memory, and dynamically sort them by frequency on every single keystroke. The database CPU will hit 100% instantly.
2. The Evolution (The Trie)
We build a Prefix Tree in memory (Root → s → y → s). Finding the exact node for "sys" takes exactly 3 steps (O(L) where L is the length of the word). But we still have a major problem! Once we are standing on the "sys" node, there might be 50,000 branches below it (system design, system of a down, etc.). If we have to recursively traverse all 50,000 branches every time someone types a letter just to compare frequencies and find the Top 10, the CPU still locks up.
The Fix (Pre-computed Top K Caches): In system design, we heavily favor making writes complex so that reads can be instantaneous. Inside every single node of the Trie, we store a hardcoded array of the Top 10 suggestions for that prefix. When you type "s-y-s", the API simply grabs the array stored exactly at the s node and returns it in perfect O(1) time. Zero traversal down the branches is required.
3. Production Tooling & Lambda Architecture
In reality, you don't build this from scratch. You use Elasticsearch (Completion Suggester), which uses an FST (Finite State Transducer). Unlike a standard Trie that only shares prefixes, an FST also shares suffixes (e.g., merging the i-n-g nodes of "testing" and "fishing") to save massive amounts of RAM.
The Architecture Trap: Updating a 10GB Trie in real-time causes massive write contention. We solve this using the Lambda Architecture (Two-Trie System):
- Historical Trie: A massive, read-only Trie built completely offline every night by big data pipelines (Hadoop/Spark).
- Trending Trie: A tiny, incredibly fast Trie (using RediSearch
FT.SUGADD) holding viral search terms from just the last 24 hours.
The API Gateway fires the user's keystroke to both Tries simultaneously, weights the results, and merges them together on the fly.
Merging Sorted Streams news feeds
Imagine you follow 500 people. When you open your social media app, the backend has to grab the 20 most recent posts from each of those 500 people, and perfectly stitch them together into one chronological timeline.
1. The Naive Approach
The backend queries the database for 10,000 posts, dumps them all into a massive array, and calls array.sort(by: timestamp). Sorting is an O(N log N) operation. Doing heavy sorting for every single user, every time they refresh their feed, will cause your API servers to overheat and crash.
2. The Evolution (K-Way Merge)
Because each individual user's list of posts is already sorted by time in the database (typically a Wide-Column Store like Apache Cassandra or ScyllaDB), we do not need to sort the whole pile. We use a classic DSA pattern called the K-Way Merge, executed in the Application Layer (e.g., using Java's PriorityQueue or Python's heapq).
- Take just the 1 absolute newest post from each of the 500 friends and place them in a Min-Heap.
- Pop the newest post off the top of the heap. (This is Post #1 in your timeline feed).
- Look at who authored that post, go back to their list, grab their second newest post, and push it into the heap to replace the one you just took.
- Repeat this process 20 times. Instead of sorting 10,000 items, your heap only ever holds 500 items, and you just generated the feed in a fraction of a millisecond!
Geospatial Search location tracking
You open the Uber app, and it instantly shows you the 5 closest drivers on the map. How does it convert the physical geometry of Planet Earth into a fast database lookup?
1. The Naive Approach
Using the Haversine formula in a SQL query: SELECT driver_id FROM drivers WHERE haversine_distance(user_lat, user_lon, driver_lat, driver_lon) < 2. This calculates the great-circle distance using sines, cosines, and square roots. If you have 50,000 active drivers, the database has to run heavy trigonometry 50,000 times for a single request via a full table scan. The CPU will melt.
2. The Evolution (Geohashing)
We stop doing math on the read path entirely. To index locations, we use Geohashing to convert 2D coordinates (latitude/longitude) into a 1D string. We divide a map of the world into 32 grid squares and assign a letter/number to each. As you zoom in, the string gets longer and more precise. tq3b represents a large city grid. tq3b9c represents a tiny 1.2km bounding box inside it.
The Magic: If you and a driver share the same string prefix (e.g., you are both in tq3b9…), you are near each other! We successfully turned an expensive trigonometric math problem into a blazing fast string-prefix database lookup.
Approximate Counting breaking memory limits
Sometimes, absolute mathematical precision is the enemy of scale. When data gets too astronomically large to physically fit in RAM, we must trade a tiny margin of error for massive memory compression.
1. The Bloom Filter (Approximate Membership)
Google Chrome needs to check if the URL you just typed is in a database of 10 billion known malicious URLs. They cannot make a network request for every site you visit (too slow), so the database must live locally on your laptop. Storing 10 billion string URLs requires ~100GB of RAM. Impossible.
The Fix: We stop storing strings entirely. We use a Bloom Filter (a massive array of bits that starts as all zeroes). When Google adds evil.com to their master list, they pass it through 3 hashing algorithms, resulting in the numbers 4, 12, and 85. They flip those specific bits to 1 in the array. Your browser downloads this tiny 30MB bit array. When you type a URL, Chrome hashes it 3 times. If those 3 bits are 1, Chrome pauses and does a network check.
Trade-off: False positives are possible (a safe site might randomly hash to the same three bits), but false negatives are mathematically impossible. We compressed 100GB to 30MB!
Note on deletions: You cannot delete from a standard Bloom Filter without accidentally deleting shared hashes. To make it deletable, use a Counting Bloom Filter, which changes the bits into integers so you can increment/decrement, though this multiplies your RAM cost by 8.
2. HyperLogLog (Approximate Cardinality)
A YouTube livestream has 10 million unique viewers. The PM wants to count unique viewers (ignoring page refreshes). Storing 10 million UUIDs in a Hash Set to count them takes 100MB per stream. If there are 100,000 concurrent streams, keeping those Hash Sets in memory requires 10 Terabytes of RAM.
The Fix (The Coin Flip Math): We use HyperLogLog (HLL). We stop storing User IDs. Instead, we hash the user IDs into binary strings (e.g., 01001011…). We track the longest streak of leading zeroes we have seen. If you flip a coin and get Heads 1 time, you probably only flipped it a few times. If you flip a coin and get Heads 20 times in a row, probability dictates you must have been flipping it millions of times to achieve such a rare streak. HLL estimates the crowd size based on the mathematical rarity of the leading zeroes.
Production Math: To fix the variance of lucky outliers, HyperLogLog splits the incoming hashes into exactly 16,384 distinct buckets. It tracks the maximum zeroes in each bucket, and averages them together using a Harmonic Mean (which aggressively pulls down massive outliers). By doing this, Redis natively (using PFADD and PFCOUNT) compresses any dataset of any size (even billions) down to exactly 12 Kilobytes of memory, guaranteeing an incredibly accurate error rate of only 0.81%!