java 39 lines · 8 steps

Rate-limiting log spam with per-message windows

A thread-safe wrapper that emits one log per time window and reports how many duplicates it swallowed.

Explained by highlit
1public final class ThrottledLogger {
2 
3 private final Logger delegate;
4 private final long windowMillis;
5 private final ConcurrentMap<String, State> states = new ConcurrentHashMap<>();
6 
7 public ThrottledLogger(Logger delegate, Duration window) {
8 this.delegate = delegate;
9 this.windowMillis = window.toMillis();
10 }
11 
12 public void warn(String message) {
13 State state = states.computeIfAbsent(message, k -> new State());
14 long now = System.currentTimeMillis();
15 
16 synchronized (state) {
17 if (now - state.windowStart >= windowMillis) {
18 flush(message, state, now);
19 state.windowStart = now;
20 state.suppressed = 0;
21 delegate.warn(message);
22 } else {
23 state.suppressed++;
24 }
25 }
26 }
27 
28 private void flush(String message, State state, long now) {
29 if (state.suppressed > 0) {
30 delegate.warn("[suppressed {} identical messages in the last {} ms] {}",
31 state.suppressed, now - state.windowStart, message);
32 }
33 }
34 
35 private static final class State {
36 long windowStart = 0L;
37 int suppressed = 0;
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Keying throttle state by message lets you rate-limit each distinct log line independently.
  2. 2Locking on the per-key state object confines contention instead of serializing every call.
  3. 3Counting and later reporting suppressed events preserves signal while cutting volume.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Rate-limiting log spam with per-message windows — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code