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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A sliding log keeps exact request timestamps so the window moves continuously instead of resetting in fixed buckets.
- 2Pairing a ConcurrentHashMap with per-value synchronization limits lock contention to a single user's log.
- 3Injecting a Clock makes time-dependent rate-limiting logic deterministic and testable.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-sliding-log-rate-limiter-works-explained-java-4934/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.