System DesignADVANCEDPart 1 of 3 in Series

Designing a Distributed Rate Limiter with Redis and Lua Scripts

A deep dive into sub-millisecond sliding window counter algorithms, token buckets, and coordinating distributed rate limiting across multi-region API gateways.

A
Alex Rivera
@alexdev
September 28, 2026 12 min read
Share
Part 1 of 3Technical Learning Track

System Design: From Zero to Production

A comprehensive engineering series guiding backend developers from single-node instances to highly resilient distributed architectures.

Designing a Distributed Rate Limiter with Redis and Lua Scripts

Introduction

Rate limiting is critical for protecting upstream services, preventing cascading failures, and enforcing API tier quotas. When scaling API gateways handling hundreds of thousands of concurrent requests, in-memory rate limiting on individual instances falls short because traffic is load-balanced across multiple nodes.

Architecture

text
sequenceDiagram
    autonumber
    Client->>Gateway: HTTP GET /api/v1/resource
    Gateway->>Redis: EVALSHA sliding_window.lua (Key, Limit, Window)
    Redis-->>Gateway: [Allowed: 1, Remaining: 42, Reset: 15000]
    Gateway->>Backend: Forward Request
    Backend-->>Client: HTTP 200 OK

Benchmark Results

Sliding Window vs Token Bucket (1M ops/sec)

Benchmarked Live
Measured p99 latency under simulated 20ms network jitter.
1.Sliding Window (Lua)
0.84ms
-42% latency
2.Token Bucket (Redis)
1.12ms
-28% latency
3.Memory Footprint
64MB
O(1) memory

Implementation Code

text
export async function acquireRateLimit(key: string, limit: number, windowMs: number): Promise<boolean> {
  const now = Date.now();
  const clearBefore = now - windowMs;
  
  const result = await redis.eval(
    SLIDING_WINDOW_SCRIPT,
    1,
    key,
    now,
    clearBefore,
    limit
  );
  return result === 1;
}
Share
Track Roadmap: System Design: From Zero to Production
All Chapters (3)
A

Alex Rivera

@alexdev

Principal Distributed Systems Engineer. Specializing in high-throughput caching and message brokers.