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
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 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.