Questions / Quant development, Trading system components

A token bucket

Applied, about 6 minutes. Question D363.

The bucket refills 1 token per second and holds at most 3. How many requests pass?

def take(rate, burst, times):
    tokens, last, ok = burst, 0.0, 0
    for t in times:
        tokens = min(burst, tokens + (t - last) * rate)
        last = t
        if tokens >= 1:
            tokens -= 1
            ok += 1
    return ok

print(take(1.0, 3, [0, 0, 0, 0, 0.5, 1.0, 1.0, 3.0, 3.0, 3.0]))

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: 6 requests

  1. t = 0: three pass, the fourth fails.
  2. t = 0.5: 0.5 tokens, fails.
  3. t = 1.0: one passes, the next fails.
  4. t = 3.0: 2 tokens, two pass.
  5. Total 6.

Interview shortcut. 3 (burst) + 1 + 2.

Takeaway. A token bucket allows a burst, then the refill rate.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More trading system components questions