Try
↑ ↓ move↵ openesc close

Interview prep / Rate limiting algorithms

Mid · Rate limiting algorithms · System design interview question

Your search endpoint answers in 5 ms, but a report endpoint can take 2 seconds of CPU. A flat limit of 100 requests a minute lets one customer take the service down with reports. How would you change the limiter?

Sketch your own answer first, then compare it with the one below.

A strong answer

Count work, not requests. Move to a token bucket where each call is charged tokens in proportion to its cost. Take a bucket of 1,000 tokens refilling at 1,000 a minute. A search costs 1 token and a report costs 100. The customer can then make 1,000 searches a minute, or 10 reports, or a mix, such as 500 searches and 5 reports. The service is protected by the total work it will accept from any one caller, which is what actually runs out.

Getting the costs right is the hard part. Start with measured CPU time or a simple tier you can explain, and keep the table small. Costs that depend on the request, such as a page size or a date range, can be estimated up front and corrected afterwards by refunding or charging the difference once the real cost is known.

Publish the costs and return the remaining balance in response headers. Clients that can see a report costs 100 will schedule them sensibly.

Keep a separate low cap on concurrent reports as well. Token costs limit work over time, but 10 reports started in the same second still run together.

Sources

Learn it by running it

The rate limiting algorithms lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms