Skip to the solution
EasyFrontendAsked in 20244 min read

Rate Limiter bucket logic

227 views

The problem

Problem, as an interviewer would state it: "Implement a rate limiter using the token bucket algorithm — a bucket holds up to N tokens, each request consumes one, and tokens refill continuously over time. Show me it correctly rejects requests once the bucket is empty, and correctly allows more after tokens refill."

Examples:

Code
const limiter = createTokenBucket({ capacity: 3, refillRatePerSec: 10 });
limiter.tryConsume(); // true, true, true, then false, false for 5 rapid calls

Clarifying questions expected:

  • Should tokens refill continuously (fractional tokens accumulating smoothly) or in discrete steps?
  • Can a single request cost more than one token?
  • Is this rate limiter meant to run per-client (one bucket each) or globally (one shared bucket)?

Code / implementation expected: Yes — real, direct proof that exactly the bucket's own capacity worth of rapid requests are allowed, the rest genuinely rejected, and more become available after a real, measured refill period.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a token-bucket rate limiter allows exactly capacity-many rapid requests, then correctly allows more after a real, measured refill

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 41 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement a Theme Toggle That Persists Choice and Respects prefers-color-scheme

Continue