Sliding Window Counter

        previous minute            current minute
   |───────────────────────|───────────────────────|
                  [════════ your real 60s window ════════]
                  ↑ 20s in                 now (40s in) ↑
   prev counts for:  last 20s of 60  =  1/3 of prev's total
   curr counts for:  all of it so far =  100% of curr's total

estimated_count = prev_count × (1 − elapsed/window) + curr_count 60 s window, 40 s in, prev = 90, curr = 30 → 90 × (20/60) + 30 = 60

The limiter behaves as if 60 requests happened in the last 60 seconds. As now advances toward the end of the current minute the 20/60 fraction shrinks toward 0/60 — the previous minute's influence fades out smoothly. No sudden reset, no seam to abuse.

func (sc *SlidingWindowCounter) Allow(ctx context.Context, userID string) (bool, int64, error) {
    now := time.Now()
    windowSecs := int64(sc.window.Seconds())
    currBucket := now.Unix() / windowSecs
    prevBucket := currBucket - 1
    elapsed := float64(now.Unix() % windowSecs)

    currKey := fmt.Sprintf("rl:swc:%s:%d", userID, currBucket)
    prevKey := fmt.Sprintf("rl:swc:%s:%d", userID, prevBucket)

    pipe := sc.rdb.Pipeline()
    getCurr := pipe.Get(ctx, currKey)
    getPrev := pipe.Get(ctx, prevKey)
    if _, err := pipe.Exec(ctx); err != nil && err != redis.Nil {
        return false, 0, err
    }

    var curr, prev int64
    if v, err := getCurr.Int64(); err == nil { curr = v }
    if v, err := getPrev.Int64(); err == nil { prev = v }

    windowF := float64(windowSecs)
    estimated := float64(prev)*(1-elapsed/windowF) + float64(curr)

    if int64(estimated) >= sc.limit {
        return false, 0, nil
    }

    // Increment current bucket
    pipe2 := sc.rdb.Pipeline()
    pipe2.Incr(ctx, currKey)
    pipe2.Expire(ctx, currKey, sc.window*2)
    if _, err := pipe2.Exec(ctx); err != nil {
        return false, 0, err
    }

    return true, sc.limit - int64(estimated) - 1, nil
}

Line-by-line walkthrough

Phase 1 — Bucket math

now := time.Now()
windowSecs := int64(sc.window.Seconds())
currBucket := now.Unix() / windowSecs
prevBucket := currBucket - 1
elapsed := float64(now.Unix() % windowSecs)

This is the core trick. Time is sliced into fixed-width buckets (e.g., 60-second chunks). Integer division / gives the bucket number, modulo % gives how far into the current bucket we are.

now.Unix()/ 60 → bucket% 60 → elapsedmeaning
10001640bucket 16, 40 s in
1020170new bucket just started
10501730bucket 17, 30 s in

So at now.Unix() = 1050: currBucket = 17, prevBucket = 16, elapsed = 30.

Phase 2 — Fetch both counters in one round trip

currKey := fmt.Sprintf("rl:swc:%s:%d", userID, currBucket)
prevKey := fmt.Sprintf("rl:swc:%s:%d", userID, prevBucket)

pipe := sc.rdb.Pipeline()
getCurr := pipe.Get(ctx, currKey)
getPrev := pipe.Get(ctx, prevKey)
if _, err := pipe.Exec(ctx); err != nil && err != redis.Nil {
    return false, 0, err
}

A Redis pipeline fetches both keys in a single network round trip. redis.Nil means the key doesn't exist yet — that's fine, it just means the counter is 0.

var curr, prev int64
if v, err := getCurr.Int64(); err == nil { curr = v }
if v, err := getPrev.Int64(); err == nil { prev = v }

If a key wasn't found (redis.Nil), that counter stays at its zero value 0. Safe and simple — no special-casing needed.

Phase 3 — The weighted blend (the estimation)

windowF := float64(windowSecs)
estimated := float64(prev)*(1-elapsed/windowF) + float64(curr)

estimated = prev × (1 − elapsed/window) + curr The previous bucket's weight linearly fades from 1.0 → 0.0 as we progress through the current bucket.

At now.Unix() = 1050 (30 s into a 60 s window), with prev = 90 and curr = 30:

estimated = 90 × (1 − 30/60) + 30 = 90 × 0.5 + 30 = 75

This smooths out the boundary — as elapsed approaches windowF, the previous bucket's contribution shrinks to zero. No sudden reset, no seam for attackers to exploit.

Phase 4 — Check the limit (reject early, don't inflate)

if int64(estimated) >= sc.limit {
    return false, 0, nil
}

If the estimated count already exceeds the limit, reject immediately without incrementing. This is critical — rejecting early avoids inflating the counter for a request that won't be served anyway.

Phase 5 — Increment the current bucket only

pipe2 := sc.rdb.Pipeline()
pipe2.Incr(ctx, currKey)
pipe2.Expire(ctx, currKey, sc.window*2)
if _, err := pipe2.Exec(ctx); err != nil {
    return false, 0, err
}

return true, sc.limit - int64(estimated) - 1, nil

Only the current bucket is incremented. The previous bucket is never touched — it exists purely as a side effect of the clock arithmetic. The TTL is window × 2 (120 s for a 60 s window): long enough to keep the key alive through its entire run as "previous," then it auto-cleans up. The return value tells the caller how many requests remain (limit − estimated − 1 to account for this one).

How the two buckets are maintained (there's no rotation)

The thing that trips people up: nothing ever copies "current" into "previous," and nothing resets a counter. There is no rotation code at all. Both buckets fall out of plain arithmetic on the clock.

1. A bucket is just a number computed from the time. Integer division throws away the remainder and tells you which bin you're in; modulo keeps only that remainder and tells you how far into the bin you are:

       1000        =        16 × 60        +        40
   (the time)            which bin (/)          offset in bin (%)
                          → currBucket             → elapsed
now.Unix()/ 60 → currBucket% 60 → elapsedmeaning
10001640bin 16, 40 s in
10191659bin 16, last second
1020170new bin, just started
10501730bin 17, 30 s in
1080180new bin again

2. "Current" and "previous" are just two different Redis keys. The bucket number is baked into the key name, and INCR only ever touches the current key. While we're in bucket 17, every allowed request does INCR ...:17. Key ...:16 is never written — it sits there holding whatever total bucket 16 reached, read-only, as "previous."

3. The boundary "rotation" happens for free. At now.Unix() = 1080 the division flips currBucket from 17 to 18: currKey → ...:18 (brand new, GET reads as 0) and prevKey → ...:17 (the exact key we were incrementing a second ago). No migration, no copy, no reset — only the names the code computes changed.

4. TTL cleans up old buckets. We only ever read current and current−1, so anything two windows back is dead weight. Expire(currKey, window*2) lets old buckets vanish; the ×2 keeps a bucket alive long enough to still be readable as "previous" through the entire next window.

In short: time itself does the bookkeeping. Bucket ID = now.Unix() / windowSecs, the ID lives in the key name, you only INCR the current key, and TTL reaps the rest.

The approximation error

The interpolation assumes requests were uniformly distributed in the previous window. If all previous-window traffic happened at the very end (worst case), the estimate undershoots and you allow slightly more than intended. Cloudflare's analysis found the error is ≤0.003% of limit under real traffic — good enough for almost everything.

Memory / userO(1) — two keys
Accuracy~99.997% under real traffic
Latency~1 RTT
Best forHigh-scale APIs needing O(1) memory and near-exact accuracy