Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Rate Limiter for Burst Traffic

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Rate Limiter for Burst Traffic. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Quantcast APIs can receive short traffic bursts that should be tolerated without allowing sustained overload. Implement a per-client token bucket rate limiter for a chronologically ordered request stream.

Each client has a bucket with a maximum capacity of capacity tokens. Initially, every client's bucket is full. Tokens are replenished continuously at refill_rate tokens per second, but the bucket cannot exceed its capacity. Processing one request consumes one token. A request is allowed only when its client's bucket contains at least one token after replenishment.

Formal Specification

Implement rate_limit(requests, capacity, refill_rate), where requests is a list of [timestamp, client_id] pairs. timestamp is a nonnegative number of seconds, and client_id is a string. Return a list of booleans in request order, where True means allowed and False means rejected. Requests are globally ordered by nondecreasing timestamp. Each client's state must be independent.

Constraints

  • 1 <= len(requests) <= 10^5
  • 1 <= capacity <= 10^6
  • 0 < refill_rate <= 10^6
  • Timestamps are nondecreasing and have at most six decimal places
  • Each request contains exactly one timestamp and one client ID

Function Signature

def rate_limit(requests, capacity, refill_rate):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output