DrawCode Algorithm Visualizer • Rate Limiting • Medium

Sliding Window Log Algorithm

Tags: Rate Limiting, Sliding Window, Timestamp Log, System Design, Precision

1. One-Liner

The Sliding Window Log keeps a sorted log of all request timestamps. On each request, it removes entries older than the window, counts what remains, and denies if at limit.


2. The Problem It Solves

Fixed Window can allow a 2x burst at window boundaries. Token Bucket uses O(1) memory but approximates. Sliding Window Log gives precise rate limiting: exactly N requests per sliding window of W seconds, with no boundary bursts.


3. The Core Idea

Imagine a scroll of timestamps: every time a request arrives, you add its time to the scroll. Before adding, you erase any timestamps older than W seconds. Count what's left. If count >= limit, deny. Otherwise add and allow.

The window "slides" forward with time — old entries drop off, new ones are added. No fixed boundaries.


4. How It Works

StepWhat Happens
1. Get timeGet current timestamp
2. Calc cutoffcutoff = now - windowSize
3. Remove expiredFilter out timestamps <= cutoff
4. Count remainingcount = len(log)
5. Check limitcount >= limit?
6a. YES → DenyToo many in window
6b. NO → AllowAppend timestamp, allow

5. Key Properties

PropertyValue
PrecisionExact — no boundary bursts
MemoryO(n) — stores all timestamps in window
Time per requestO(n) — filter + count
Best forWhen accuracy matters more than memory

Implementation Example (PYTHON)

import time

class SlidingWindowLog:
    def __init__(self, window_size, limit):
        self.window_size = window_size
        self.limit = limit
        self.log = []  # sorted timestamps

    def try_allow(self):
        now = time.monotonic()
        cutoff = now - self.window_size
        self.log = [t for t in self.log if t > cutoff]
        count = len(self.log)
        if count >= self.limit:
            return False   # DENY
        self.log.append(now)
        return True    # ALLOW

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer