System Design

Patterns

Dealing with Skew

Uniform traffic is a fiction. Walk the system component by component, say for each one whether the distribution is even and what happens when it is not, and name the places where the skew is helping you.

The shape

Every capacity calculation starts by dividing a total by a count: requests across servers, keys across shards, bytes across disks. The division assumes that the load spreads evenly. In a real system it never does.

Skew is the gap between the average and the worst case, and you have to size the system for the worst case. A shard with 40 times the median load does not run 40 times slower. It falls over, and every request routed to it fails with it. So the average was never the number that mattered.

Skew is not one problem. It comes in four forms, and each form has its own fix. A fix for one form does nothing for the others.

The four forms:

  • Key skew. One key gets far more traffic than the others, such as a celebrity's post, a viral product or a system account. Hashing does not help. Hashing spreads keys across machines, and this is one key.
  • Partition skew. Some partitions get far more keys than others, even though no single key is hot. The cause is usually a bad partition function, the rule that maps each key to a partition. Or the keys cluster on their own, such as timestamps that all fall in the newest range, and the function does not break the cluster up.
  • Temporal skew. Load is even across keys, but it all arrives at the same time. Everyone opens the app at 8 a.m., every cron job fires on the hour, and every token expires at midnight.
  • Size skew. Requests are spread evenly, but the work behind each one is not. One user has 40 followers, and another has 50 million.

The most useful habit is to go through the system one component at a time and say, for each one, whether the load is even and what happens if it is not. If you do this out loud, the interviewer hears that you checked each part. Without it, your answer sounds like a design you remembered and matched to the question.

The moves

Each form has its own fix. Applying the wrong fix is worse than doing nothing, because it looks like progress while the skew stays where it was.

Four forms of skew
Top left, one key's red bar is far above the blue bars of the other keys. Top right, no key is big, but one shard holds many more orange keys, and that shard is the red one. Bottom left, the blue load line crosses the dashed capacity line at 8 a.m., and the part above it is red. Bottom right, each user sends one request, the grey bar, but the work behind the request for the account with 50 million followers is the tall red bar. Each fix is in green, and none of them works for another form.Top left, one key's red bar is far above the blue bars of the other keys. Top right, no key is big, but one shard holds many more orange keys, and that shard is the red one. Bottom left, the blue load line crosses the dashed capacity line at 8 a.m., and the part above it is red. Bottom right, each user sends one request, the grey bar, but the work behind the request for the account with 50 million followers is the tall red bar. Each fix is in green, and none of them works for another form.
Each form needs its own fix. Top left, one key's red bar is far above the blue bars of the other keys. Top right, no key is big, but one shard holds many more orange keys, and that shard is the red one. Bottom left, the blue load line crosses the dashed capacity line at 8 a.m., and the part above it is red. Bottom right, each user sends one request, the grey bar, but the work behind the request for the account with 50 million followers is the tall red bar. Each fix is in green, and none of them works for another form.

Key skew cannot be fixed by spreading keys, because there is only one key. There are three moves. You can split the key into N sub-counters and add them up on every read. You can absorb the writes somewhere cheaper, by buffering them in memory and flushing them to the store on a timer. Or you can stop the traffic from reaching the key at all, by caching the read. A split key costs N reads where there used to be one. Buffering and caching cost freshness, because the stored or cached value runs a little behind.

Partition skew is the one form that hashing does fix. Because it works here, people believe hashing fixes skew in general. If keys cluster because the partition key has structure, such as a timestamp or an id that only grows, hashing the key removes the structure, and the keys spread evenly. A related problem is uneven ranges on a consistent hashing ring, where one node owns a bigger arc of the ring than the others. Virtual nodes fix that: each machine takes many small arcs instead of one large one.

What hashing fixes
On the left, keys are partitioned by time range, so every new key lands in the newest range and one shard takes all the new writes. In the middle, the same keys are partitioned by a hash, and each shard takes a quarter of the load. On the right, one key gets most of the traffic. It has one hash, so its red load still lands on one shard and passes that shard's limit.On the left, keys are partitioned by time range, so every new key lands in the newest range and one shard takes all the new writes. In the middle, the same keys are partitioned by a hash, and each shard takes a quarter of the load. On the right, one key gets most of the traffic. It has one hash, so its red load still lands on one shard and passes that shard's limit.
Hashing spreads many keys evenly, but never one key. On the left, keys are partitioned by time range, so every new key lands in the newest range and one shard takes all the new writes. In the middle, the same keys are partitioned by a hash, and each shard takes a quarter of the load. On the right, one key gets most of the traffic. It has one hash, so its red load still lands on one shard and passes that shard's limit.

Temporal skew is fixed by moving work to a different time. Add jitter, a small random delay, to retries and to scheduled jobs. Stagger expiry times instead of giving every token the same midnight. Put a queue between the arrival of work and the doing of it, so a spike waits in line instead of reaching the servers all at once. The cost is latency. Background work can usually wait, and work that a user is waiting on usually cannot.

Staggered expiry
On the left, every token expires at 00:00, so every client asks for a new one at once, and the red bar goes past capacity. On the right, each token gets a random 0 to 60 extra minutes. The same refreshes now arrive across the hour after midnight, and every bar stays under the dashed capacity line.On the left, every token expires at 00:00, so every client asks for a new one at once, and the red bar goes past capacity. On the right, each token gets a random 0 to 60 extra minutes. The same refreshes now arrive across the hour after midnight, and every bar stays under the dashed capacity line.
The same refreshes, spread over an hour, stay under capacity. On the left, every token expires at 00:00, so every client asks for a new one at once, and the red bar goes past capacity. On the right, each token gets a random 0 to 60 extra minutes. The same refreshes now arrive across the hour after midnight, and every bar stays under the dashed capacity line.

Size skew is fixed by putting a limit on the work that one request can do. Paginate results, cap the size of each fanout batch, and send the largest accounts down a different code path. That last move is where the fanout hybrid comes from. Posts from ordinary accounts are copied into followers' feeds when they are written. Posts from the largest accounts are fetched when a follower reads the feed. The hybrid is a fix for size skew, not for key skew.

Back of envelopeWhy the average is the wrong number
1,000 tenants sharing a cluster, sized on the average:

  total writes/s                             50,000
  tenants                                     1,000
  average per tenant                             50

Sized for the average, with 4x headroom:
  capacity per tenant                           200

Now the real distribution, which is roughly
power-law in most multi-tenant systems:

  median tenant                                   8
  p99 tenant                                  1,200
  largest tenant                             14,000

  ⇒ the largest tenant alone is 70x the capacity
    it was given
  ⇒ it needs its own shard, and probably its own
    treatment entirely

Note what the average told you: nothing. It is
compatible with both a flat distribution and this
one, and only one of them works.

Always ask for the p99 and the max, never the mean.

How to tell you have this problem

Ask for the distribution, not the total. For anything that gets divided up, group it by the key it is divided on and sort the groups, largest first: select count(*) from x group by partition_key order by 1 desc limit 20. As a rough rule, if the top entry is more than about 10 times the median, the skew is large enough to matter. Row counts show where the data sits, so run the same group-by on your request logs to see where the traffic goes.

Look at metrics for each machine, not averages across the fleet. A dashboard of average CPU across a fleet hides the one machine at 100 percent. Plot the maximum next to the average. The gap between the two lines is the skew, and the average line on its own never shows it.

Check whether your worst latency comes from a few specific entities. Group p99 latency, the time within which 99 percent of requests finish, by tenant, by key and by author. If a handful of entities account for most of the slow requests, you have size skew or key skew. Then you can fix those entities directly, instead of making everything faster.

Watch what happens after a rebalance. If the load piles up on one machine again within hours, the skew is in the data, not in where the data was placed. Moving partitions around then treats a symptom and leaves the cause.

What it costs

A special path for large entities stays forever. Once big accounts take a different route, every feature has to be built twice, and a bug can show up on one path only. This is the main cost of the fanout hybrid, and of giving the largest tenants their own shards. It does not go away.

Splitting a key multiplies the cost of a read. With N sub-counters, every read becomes N reads and a sum. Reads usually outnumber writes, so the split can move the cost onto the busier side. Check the ratio of reads to writes before you split.

Salting makes range scans expensive. Salting means putting a short prefix, picked from N values, in front of each key. The prefix spreads writes across N partitions, but keys that sat next to each other are no longer stored together. So one range scan becomes N scans, one per prefix, and the results have to be merged. If users wait on range scans, salting is usually the wrong fix.

Every threshold creates a boundary that someone has to own. A rule like "accounts over N followers get the special path" means an account switches paths when it crosses N. Someone has to own what happens at that switch. Otherwise the largest accounts, the ones that matter most, end up with state that does not match between the two paths.

Sometimes the skew is fine, and you should say so. Not all skew hurts. If you name a place where the load is uneven and explain why it does not matter, you show that you did the check. That is a stronger signal than fixing it.

Where it shows up in the course

articlethe form it takes there
Back-of-Envelope Estimationwhy the peak multiplier exists, and why an average is never the number you provision against
Capacity Planning and Autoscalingthe busiest minute, the steepest climb and the seasonal peak each size something different, and a daily average sizes nothing
Consistent Hashingpartition skew specifically, which virtual nodes fix and which is the only one of the four that hashing touches
Cost as a Design Constrainta daily curve is skew in time: size for the busiest minute, but commit only the floor and follow the curve above it
Design a Distributed Job Schedulermidnight is skew in time: a fifth of all jobs come due in one second, and each job's window says how far it may move
Design a Leaderboard / Ranking Servicemidnight resets are cheap, but a reminder sent to every player at once is spread over an hour
Design an Ad Click Aggregatorkeying Kafka by event ID removes partition skew, and summing for a second before the shuffle absorbs the busy ad's writes
Design Yelp (Nearby Places)density varies about 40,000 times between Midtown and rural Montana, absorbed by a table of radii worked out each night
Distributed Cacheslots spread the key space evenly and do nothing for one popular key, which is why each router keeps a short-lived copy
Geospatial Indexinga query checks 2,700 candidates downtown and 2 at the edge of town, size skew that hashing cannot fix
Indexing and Query Performancea skewed column defeats the query planner the same way it defeats a shard key, because a plan costed from the average is wrong for both the common value and the rare ones
Instagramthe component-by-component walk, including the places where skew helps: image popularity is what makes a high edge hit ratio reachable
Inverted Indexesrouting by tenant makes each search cheap and each shard's size depend on which tenants land on it
Key-Value Storea partition split fixes partition skew and does nothing for one hot key
Partitioning and Shardingtenant size skew, where the largest workspace is 8,000 times the mean and no shard count helps
Search Autocompleteshort prefixes are key skew the edge absorbs; the form to plan for is refills that line up, after a build number in the URL or a cold start
Ticketmaster Bookingan on-sale is key and temporal skew at once, and the draw and the line remove each before it reaches the database
Uber Ride-Hailinga stadium let-out, temporal and key skew at once, where dispatch stays light and only drivers run out
Web Crawlerpoliteness turns uneven host sizes into queue length, and a per-domain budget caps a domain with millions of hosts
YouTubeskew working in your favour: a popularity curve steep enough to make lazy transcoding and edge caching both pay
Live Comments and Reactionshalf a million streams have a few dozen viewers and one has 5 million; placement by stream handles the tail and sampling at the stream worker handles the head

Getting it wrong

Assuming hashing fixes it. Hashing fixes partition skew. It does nothing for the other three: key skew, temporal skew and size skew.

Designing from the average. The same mean fits a distribution your design can handle and one it cannot. Ask for the p99 and the maximum.

Fixing skew you do not have. Split keys and special paths add code that you maintain forever. Measure the distribution first. Many systems are even enough that the skew does not matter.

Missing size skew because request counts look even. If requests are equal in number but very unequal in work, a chart of request rate does not show it. A chart of latency per entity shows it clearly.

Treating the hot entity as a one-off. There is never exactly one hot entity. Whatever you build for the largest account becomes a code path that other accounts take as they grow, so design it as one.

Not mentioning the skew that helps. A few items get most of the requests, and that is what lets a small cache serve most reads. An answer that treats skew only as a threat misses that half.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.