Token Bucket Rate Limiter (Java)

Refill tokens continuously from elapsed time and admit only when one is available, so bursts up to capacity pass while steady traffic stays capped.

JavaResilience

Code

snippet
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

public class TokenBucketRateLimiter {

    private final double capacity;
    private final double refillPerSecond;
    private final Supplier<Instant> clock;
    private double tokens;
    private Instant lastRefill;

    public TokenBucketRateLimiter(double capacity, double refillPerSecond, Supplier<Instant> clock) {
        this.capacity = capacity;
        this.refillPerSecond = refillPerSecond;
        this.clock = clock;
        this.tokens = capacity;
        this.lastRefill = clock.get();
    }

    // refill from elapsed time before each decision, then admit only if a token is left
    public synchronized boolean tryAcquire() {
        Instant now = clock.get();
        double seconds = Duration.between(lastRefill, now).toMillis() / 1000.0;
        tokens = Math.min(capacity, tokens + seconds * refillPerSecond);
        lastRefill = now;
        if (tokens >= 1) {
            tokens -= 1;
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-11-21T10:00:00Z"));
        TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(3, 1.0, now::get);

        // inject a virtual clock: 300ms between requests, so the output never depends on real time
        for (int i = 1; i <= 8; i++) {
            boolean allowed = limiter.tryAcquire();
            now.set(now.get().plusMillis(300));
            System.out.println("request " + i + " -> " + (allowed ? "allowed" : "throttled"));
        }
    }
}

How it works

Token Bucket Rate Limiter (Java) reduces to the class TokenBucketRateLimiter and the functions TokenBucketRateLimiter, tryAcquire and main.

The cycling part of this snippet is for (int i = 1; i <= 8; i++).

Putting it to use

Entry signature: public TokenBucketRateLimiter(double capacity, double refillPerSecond, Supplier<Instant> clock)

Output lines are prefixed (request), making each step’s effect easy to spot.

The entry point wires TokenBucketRateLimiter and tryAcquire together — run it once and the whole demo flows.

Core lines

AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-11-21T10:00:00Z"));

Interactive Tools for This Topic

FAQ

What does Token Bucket Rate Limiter (Java) print when run?
Invoke the file as-is — the `request` prefixes identify which step printed each line.