Load/Bearing
Low-level design · 19 of 22

Coding an LRU cache and a rate limiter

Two classics you should be able to write from memory in Java: O(1) LRU eviction and a thread-safe token bucket, with tests.

5 min read

These two come up constantly, alone or as the first step of a bigger problem. Both reward the same habits: pick the right data structures, make the operations O(1), make them thread-safe, and prove they work with tests. For the theory, see caching and rate limiting.

LRU cache in O(1)

You need two things at once: find any key in O(1), and know which key was used least recently, also in O(1). A HashMap gives the first. A doubly linked list ordered by use gives the second, because a node can be removed from the middle in O(1) when you already hold a reference to it. The map stores those references.

public final class LruCache<K, V> {
    private final class Node {
        final K key;
        V value;
        Node prev, next;
        Node(K key, V value) { this.key = key; this.value = value; }
    }

    private final int capacity;
    private final Map<K, Node> map = new HashMap<>();
    private final Node head = new Node(null, null);   // most recently used end
    private final Node tail = new Node(null, null);   // least recently used end

    public LruCache(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity must be positive");
        this.capacity = capacity;
        head.next = tail;
        tail.prev = head;
    }

    public synchronized Optional<V> get(K key) {
        Node n = map.get(key);
        if (n == null) return Optional.empty();
        moveToFront(n);
        return Optional.of(n.value);
    }

    public synchronized void put(K key, V value) {
        Node n = map.get(key);
        if (n != null) {
            n.value = value;
            moveToFront(n);
            return;
        }
        if (map.size() == capacity) {
            Node lru = tail.prev;
            unlink(lru);
            map.remove(lru.key);
        }
        n = new Node(key, value);
        map.put(key, n);
        addFront(n);
    }

    private void moveToFront(Node n) { unlink(n); addFront(n); }
    private void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
    private void addFront(Node n) {
        n.next = head.next;
        n.prev = head;
        head.next.prev = n;
        head.next = n;
    }
}

Notes for the interview:

class LruMap<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;
    LruMap(int capacity) { super(16, 0.75f, true); this.capacity = capacity; }   // true = access order
    @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; }
}

Token bucket rate limiter

Store the token count and the time of the last refill. On each request, add the tokens earned since then (capped at capacity), then spend one if there is one. No background thread is needed. Pass the clock in, so tests can control time.

public final class TokenBucket {
    private final long capacity;
    private final double refillPerNano;
    private final LongSupplier clock;      // System::nanoTime in production, a fake in tests
    private double tokens;
    private long last;

    public TokenBucket(long capacity, double refillPerSecond, LongSupplier clock) {
        if (capacity <= 0 || refillPerSecond < 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        this.refillPerNano = refillPerSecond / 1_000_000_000.0;
        this.clock = clock;
        this.tokens = capacity;
        this.last = clock.getAsLong();
    }

    public synchronized boolean tryAcquire() {
        long now = clock.getAsLong();
        tokens = Math.min(capacity, tokens + (now - last) * refillPerNano);   // lazy refill, no timer
        last = now;
        if (tokens < 1) return false;
        tokens -= 1;
        return true;
    }
}

Per-user limits without unbounded memory

One bucket per user ID, created on first use. To stop the map growing forever, cap it and evict the least recently seen user, which is the LRU idea again:

public final class PerUserLimiter {
    private final Map<String, TokenBucket> buckets;
    private final Supplier<TokenBucket> newBucket;

    public PerUserLimiter(int maxUsers, Supplier<TokenBucket> newBucket) {
        this.newBucket = newBucket;
        // Access-ordered LinkedHashMap: the least recently seen user is evicted first.
        this.buckets = Collections.synchronizedMap(new LinkedHashMap<String, TokenBucket>(16, 0.75f, true) {
            @Override protected boolean removeEldestEntry(Map.Entry<String, TokenBucket> eldest) {
                return size() > maxUsers;
            }
        });
    }

    public boolean allow(String userId) {
        return buckets.computeIfAbsent(userId, id -> newBucket.get()).tryAcquire();
    }
}

Evicting a user is nearly harmless. A bucket idle for longer than capacity ÷ rate seconds would be full anyway, so recreating it changes nothing. Only a recently active user who gets evicted early receives a fresh burst, so size the cap well above the number of active users. In production, a cache library with expireAfterAccess (such as Caffeine) does the same thing, and across many servers the bucket moves to Redis.

Tests

Test the behaviour with a fake clock, and test thread safety by hammering a bucket that never refills from several threads:

class TokenBucketTest {
    private long now = 0;                                   // fake clock, in nanoseconds

    @Test
    void allowsBurstThenRefillsAtRate() {
        TokenBucket bucket = new TokenBucket(3, 1.0, () -> now);
        assertTrue(bucket.tryAcquire());
        assertTrue(bucket.tryAcquire());
        assertTrue(bucket.tryAcquire());
        assertFalse(bucket.tryAcquire());                   // burst used up

        now += 1_000_000_000L;                              // one second later
        assertTrue(bucket.tryAcquire());
        assertFalse(bucket.tryAcquire());
    }

    @Test
    void neverGrantsMoreThanCapacityUnderContention() throws Exception {
        TokenBucket bucket = new TokenBucket(100, 0.0, () -> 0L);
        AtomicInteger granted = new AtomicInteger();
        List<Callable<Void>> calls = new ArrayList<>();
        for (int i = 0; i < 1_000; i++) {
            calls.add(() -> { if (bucket.tryAcquire()) granted.incrementAndGet(); return null; });
        }
        ExecutorService pool = Executors.newFixedThreadPool(8);
        pool.invokeAll(calls);
        pool.shutdown();
        assertEquals(100, granted.get());
    }
}

For the LRU cache, test that a get protects a key from eviction, that updating an existing key doesn't grow the size, and that capacity 1 works.

Interview checklist

Practise it

Exercise

Close this page and write both classes from scratch in under 40 minutes, then the two tests. If you get stuck, write down exactly where. That's the part to re-derive tomorrow.

Workshop drill

Do it by hand

Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.

LRU eviction Token bucket

Further reading