java 45 lines · 8 steps

How a sliding-log rate limiter works

A per-user timestamp log enforces a rolling request window with thread-safe pruning under concurrent access.

Explained by highlit
1public class SlidingLogRateLimiter {
2 
3 private final int maxRequests;
4 private final long windowMillis;
5 private final Clock clock;
6 private final ConcurrentMap<String, Deque<Long>> logs = new ConcurrentHashMap<>();
7 
8 public SlidingLogRateLimiter(int maxRequests, Duration window, Clock clock) {
9 this.maxRequests = maxRequests;
10 this.windowMillis = window.toMillis();
11 this.clock = clock;
12 }
13 
14 public boolean tryAcquire(String userId) {
15 long now = clock.millis();
16 long cutoff = now - windowMillis;
17 Deque<Long> timestamps = logs.computeIfAbsent(userId, k -> new ArrayDeque<>());
18 
19 synchronized (timestamps) {
20 while (!timestamps.isEmpty() && timestamps.peekFirst() <= cutoff) {
21 timestamps.pollFirst();
22 }
23 if (timestamps.size() >= maxRequests) {
24 return false;
25 }
26 timestamps.addLast(now);
27 return true;
28 }
29 }
30 
31 public Duration retryAfter(String userId) {
32 Deque<Long> timestamps = logs.get(userId);
33 if (timestamps == null) {
34 return Duration.ZERO;
35 }
36 synchronized (timestamps) {
37 Long oldest = timestamps.peekFirst();
38 if (oldest == null || timestamps.size() < maxRequests) {
39 return Duration.ZERO;
40 }
41 long readyAt = oldest + windowMillis;
42 return Duration.ofMillis(Math.max(0, readyAt - clock.millis()));
43 }
44 }
45}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1A sliding log keeps exact request timestamps so the window moves continuously instead of resetting in fixed buckets.
  2. 2Pairing a ConcurrentHashMap with per-value synchronization limits lock contention to a single user's log.
  3. 3Injecting a Clock makes time-dependent rate-limiting logic deterministic and testable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a sliding-log rate limiter works — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code