networking · intermediate · ~15 min

Token-bucket rate limiter (single slot)

Token-bucket rate limiting, a defensive shield against brute force.

Challenge

Given the struct

typedef struct { double tokens; double rate; double max; double last_refill; } bucket_t;

implement int rl_allow(bucket_t *b, double now) that:

  • Refills tokens by rate * (now - last_refill), capped at max.
  • Updates last_refill = now.
  • If tokens >= 1.0, consumes one and returns 1; otherwise returns 0.

Starter code

#include <stdio.h>
int rl_allow(bucket_t *b, double now) { /* TODO */ return 0; }

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.