Skip to lesson

Real world: rate limits and moving averages

In real backend systems, the data rarely sits in a fixed array: requests and telemetry events arrive continuously over time. Sliding windows power API rate limiters, telemetry moving averages, and Redis/Cloudflare traffic counters.

Requests per minute with a window

Suppose an API gateway allows a user at most maxRequests within any rolling windowMillis (for example, 100 requests per 60,000 ms). When a request arrives at timestamp nowMs, how do we decide whether to allow or reject (HTTP 429 Too Many Requests) it?

  1. Maintain Deque<Long> timestamps = new ArrayDeque<>().
  2. On allowRequest(nowMs), poll timestamps from the front while peekFirst() <= nowMs - windowMillis.
  3. If timestamps.size() < maxRequests, offerLast(nowMs) and return true; else return false.

Example 1 · Sliding window log rate limiter with ArrayDeque

RateLimiterDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class RateLimiterDemo {    static class SlidingWindowRateLimiter {        private final int maxRequests;        private final long windowMs;        private final Deque<Long> timestamps = new ArrayDeque<>();
        SlidingWindowRateLimiter(int maxRequests, long windowMs) {            this.maxRequests = maxRequests;            this.windowMs = windowMs;        }
        public boolean allowRequest(long nowMs) {            while (!timestamps.isEmpty() && timestamps.peekFirst() <= nowMs - windowMs) {                timestamps.pollFirst();            }            if (timestamps.size() < maxRequests) {                timestamps.offerLast(nowMs);                return true;            }            return false;        }    }
    public static void main(String[] args) {        SlidingWindowRateLimiter limiter = new SlidingWindowRateLimiter(3, 1000);        long[] arrivals = {100, 400, 800, 950, 1100, 1150};        for (long t : arrivals) {            System.out.println("t=" + t + "ms -> allowed=" + limiter.allowRequest(t));        }    }}
Output
t=100ms -> allowed=true
t=400ms -> allowed=true
t=800ms -> allowed=true
t=950ms -> allowed=false
t=1100ms -> allowed=true
t=1150ms -> allowed=false

What this code does

  • At t=950ms, the window (950 - 1000, 950] = (-50, 950] already holds 3 requests (100, 400, 800), so t=950ms is rejected.
  • At t=1100ms, 100 <= 1100 - 1000 (100 <= 100), so t=100ms expires and t=1100ms is allowed.

With a sliding window log backed by an ArrayDeque<Long> of accepted request timestamps:

  1. Evict expired timestamps from the front: while (!log.isEmpty() && log.peekFirst() <= nowMs - windowMillis) call log.pollFirst().
  2. Check capacity: if log.size() < maxRequests, push log.offerLast(nowMs) and return true (allowed); otherwise return false (rate-limited). Because each accepted request is pushed once and popped once, the amortized work per check is O(1), and the queue holds at most maxRequests timestamps.

Moving averages over a stream

In Moving Average from Data Stream, numbers arrive one at a time via next(int val), and we must return the average of the last k values seen so far (or all values seen if fewer than k have arrived).

Example 2 · Streaming moving average using a zero-allocation circular array

MovingAverageStreamDemo.javaJava
public class MovingAverageStreamDemo {    static class MovingAverage {        private final int[] ring;        private int count = 0;        private int head = 0;        private long windowSum = 0;
        MovingAverage(int size) {            this.ring = new int[size];        }
        public double next(int val) {            if (count < ring.length) {                count++;            } else {                windowSum -= ring[head];            }            ring[head] = val;            windowSum += val;            head = (head + 1) % ring.length;            return (double) windowSum / count;        }    }
    public static void main(String[] args) {        MovingAverage ma = new MovingAverage(3);        int[] stream = {1, 10, 3, 5};        for (int v : stream) {            System.out.printf("next(%d) -> %.2f%n", v, ma.next(v));        }    }}
Output
next(1) -> 1.00
next(10) -> 5.50
next(3) -> 4.67
next(5) -> 6.00

What this code does

  • For the first two calls, count is 1 and 2, so we divide by count rather than 3.
  • On next(5), the circular buffer is full (count == 3), so ring[head] (which holds 1) is subtracted before writing 5 into ring[head].
  • Circular buffer int[k] avoids boxing ints into Integer objects.
  • Index (totalSeen % k) is both the slot of the oldest element (when totalSeen >= k) and the slot where the new element goes.
  • Before reaching k elements, divide windowSum by totalSeen, not k.

Storing the entire history of an unbounded stream would eventually exhaust heap memory (OutOfMemoryError). Instead, we store only the last k values in an ArrayDeque<Integer> (or even better, a fixed circular array int[k] with a head pointer) plus a long windowSum:

  • When count == k, subtract the oldest element before overwriting it.
  • Add val to windowSum, store val, and return (double) windowSum / count.

This uses O(1) time per next(val) call and O(k) bounded memory forever.

Fixed versus sliding window counters

What if a user tier allows 1,000,000 requests per minute? Storing 1,000,000 timestamps per user in a sliding window log is too memory-heavy.

Example 3 · Comparing fixed window vs. sliding window counter on a boundary burst

SlidingWindowCounterDemo.javaJava
public class SlidingWindowCounterDemo {    public static double estimateSlidingCount(            int prevWindowCount, int currWindowCount, long nowMs, long windowMs) {        long elapsedInCurr = nowMs % windowMs;        double prevWeight = 1.0 - ((double) elapsedInCurr / windowMs);        return currWindowCount + prevWeight * prevWindowCount;    }
    public static void main(String[] args) {        int limit = 100;        long windowMs = 60_000;        // 90 requests arrived near the end of minute 0; 20 arrived 15s into minute 1 (t = 75,000ms)        int prevCount = 90;        int currCount = 20;        long nowMs = 75_000;
        boolean fixedAllows = currCount < limit;        double slidingEstimate = estimateSlidingCount(prevCount, currCount, nowMs, windowMs);        boolean slidingAllows = slidingEstimate < limit;
        System.out.println("Fixed counter in curr bucket: " + currCount + " -> allow=" + fixedAllows);        System.out.println("Sliding estimate at 75s: " + slidingEstimate + " -> allow=" + slidingAllows);    }}
Output
Fixed counter in curr bucket: 20 -> allow=true
Sliding estimate at 75s: 87.5 -> allow=true

What this code does

  • At t=75,000ms (15s into the second 60s bucket), elapsedFraction is 15/60 = 0.25, so 75% of the previous bucket is weighted in: 20 + 0.75 * 90 = 87.5.
  • If 15 more requests arrive immediately, the sliding counter reaches 102.5 >= 100 and blocks the burst, whereas a naive fixed counter would allow 80 more!

A fixed window counter stores just one integer per minute bucket (minuteBucket -> count), using O(1) memory—but it suffers from the boundary burst bug: a client can send 1,000,000 requests at 00:59 and another 1,000,000 requests at 01:00, achieving 2× the rate limit in 2 seconds!

Production rate limiters (such as Cloudflare's) use a sliding window counter that stores only two numbers: prevWindowCount and currWindowCount. If we are 30% of the way into the current 60-second bucket (at second 18), the rolling 60-second window overlaps 70% of the previous bucket and 100% of the current bucket: estimatedCount = currWindowCount + prevWindowCount × (1 - elapsedFraction) This approximates a true sliding window using O(1) memory (two integers per user).

The sliding window counter is a simplified linear approximation (it assumes requests in the previous window were evenly distributed), which is standard in high-throughput edge gateways.

Next step

Check your understanding

10 quick questions