Course contentsShow
← System Design
Lesson 1808 of 1,91943. Real-World System: Rate Limiter ServiceFree lesson

Redis Data Structures for Rate Limiting

Use Redis strings with TTL, sorted sets, or hashes to efficiently store and manage rate limit counters.

Redis Data Structures for Rate Limiting

What You'll Learn

You'll learn which Redis data structures—strings, sorted sets, and hashes—are best suited for implementing different rate limiting algorithms efficiently.

Why Data Structure Choice Matters

Just as you wouldn't use a screwdriver to hammer a nail, choosing the right Redis data structure dramatically impacts your rate limiter's performance, accuracy, and memory footprint. Each structure offers different tradeoffs for operations like incrementing counters, tracking request timestamps, or storing per-user state.

Core Redis Structures for Rate Limiting

Strings with TTL

Perfect for fixed window counters. Use INCR to atomically increment a counter keyed by user ID and time window (e.g., user:123:2024-01-01-14). Set a TTL matching your window duration so keys auto-expire.

Pros: Simple, fast, minimal memory
Cons: Less precise than sliding windows

Sorted Sets (ZSETs)

Ideal for sliding window logs. Store request timestamps as scores with unique member IDs. Use ZADD to add requests, ZREMRANGEBYSCORE to remove old entries outside your window, and ZCOUNT to check current rate.

Pros: Precise per-request tracking
Cons: Higher memory (stores every request), O(log N) operations

Hashes

Useful for token bucket state. Store multiple fields (tokens remaining, last refill time) under one key. Update atomically with Lua scripts.

Pros: Groups related data, efficient for multi-field updates
Cons: Requires scripting for atomic bucket logic

Choosing Your Structure

  • Simple fixed windows? → Strings
  • Need precision? → Sorted Sets
  • Token bucket with state? → Hashes + Lua

Key Takeaway: Match Redis data structures to your rate limiting algorithm—use strings for simplicity, sorted sets for precision, and hashes for stateful algorithms like token buckets.