Tutorial · API design

    Rate limiting with Unix timestamps

    Quick answer: Express every limiter decision as pure functions of trusted epoch seconds. Fixed windows floor the clock; sliding windows prune old entries; token buckets add credits proportional to elapsed time. Unit-test each algorithm by simulating monotonic time arrays — flaky waits with setTimeout hide off-by-one bugs.

    Fixed window

    Easiest to implement with Redis INCR. Key = {tenant}:{floor(now/window)}. Communicate reset time as (bucket+1)*window so clients backoff deterministically.

    Sliding window log

    function pruneAndCount(events, nowMs, windowMs) {
      const cutoff = nowMs - windowMs;
      const fresh = events.filter((t) => t >= cutoff);
      return { count: fresh.length, kept: fresh };
    }

    Token bucket (Redis Lua sketch)

    -- KEYS[1] bucket HASH tokens, last
    -- ARGV capacity, refill_per_sec, now, cost
    -- Pseudocode: refill = min(capacity, tokens + (now-last)*rate)
    local cap = tonumber(ARGV[1])
    local rate = tonumber(ARGV[2])
    local now = tonumber(ARGV[3])
    local cost = tonumber(ARGV[4])
    -- HGETALL tokens/last, compute, HSET, return allow

    Choosing an algorithm

    PatternComplexityFairness
    API gateway defaultFixedOkay for coarse public limits
    Fraud-sensitive loginSliding or leaky bucketTighter against bursts
    Bandwidth shapingToken bucketAllows controlled floods

    Key takeaways

    • Tests should inject explicit now — never sleep in CI.
    • Emit Retry-After derived from the same epoch clock.
    • Shard Redis carefully; hot keys saturate single instances.
    • Knowledge reference: rate limiting timestamps.

    Written by Unix Calculator Editorial Team — Last verified May 2026.

    Get the Unix Timestamp Cheatsheet

    One email. Instant cheatsheet. No drip sequence.

    Advertisement