Sliding Window mit Sorted Sets in Redis
Implementieren Sie mit sortierten Mengen in Redis einen präzisen verteilten Rate-Limiter mit Sliding Window, atomaren Operationen und automatischem Ablauf alter Einträge.
Sliding Window mit Sorted Sets in Redis ist eine kostenlose API Rate Limiting & Scalability Patterns-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des API Rate Limiting & Scalability Patterns-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der API Rate Limiting & Scalability Patterns-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
From Theory to Production
You understand the sliding window log and counter conceptually. Now build one that works across many servers using Redis sorted sets, the most common production technique for accurate distributed rate limiting.
Why Sorted Sets
A Redis sorted set (ZSET) stores members ranked by a numeric score. By using the request timestamp as the score, we get an ordered log of recent requests we can trim and count efficiently.
One Key Per Client
Each client gets a key like rl:user123. Every incoming request adds a member to that client's sorted set, scored by the current timestamp in milliseconds.
ZADD rl:user123 1700000000123 1700000000123Trimming the Window
Before counting, remove entries older than the window. If the window is 60 seconds, delete everything with a score below now - 60000. This keeps only the requests inside the current sliding window.
ZREMRANGEBYSCORE rl:user123 0 (now-60000)Counting Requests
After trimming, the cardinality of the set is the number of requests in the window. Compare it against the limit to allow or deny.
ZCARD rl:user123Atomicity Matters
Doing trim, add, and count as separate commands creates a race condition under concurrency. Wrap them in a single Lua script so Redis executes them atomically per client.
The Lua Script
A Lua script run with EVAL performs all steps in one atomic operation, returning whether the request is allowed. No two requests can interleave mid-check.
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1])
local count = redis.call('ZCARD', KEYS[1])
if count < tonumber(ARGV[3]) then
redis.call('ZADD', KEYS[1], ARGV[2], ARGV[2])
return 1
end
return 0Setting Expiry
Always set a TTL on the key (a bit longer than the window) so abandoned clients do not leak memory. Idle keys expire automatically.
EXPIRE rl:user123 120Accuracy vs Memory
This approach is highly accurate because it tracks every request timestamp, but memory grows with request volume per window. For very high-traffic clients, the sliding window counter approximation uses far less memory.
Handling Many Nodes
Because all API nodes talk to the same Redis, the limit is enforced globally regardless of which node handles a request. Use a Redis cluster or replica setup for availability, mindful that replication lag can slightly relax limits.
Failure Modes
Decide what happens if Redis is unreachable: fail open (allow traffic, risk overload) or fail closed (block traffic, risk outage). Most public APIs fail open with a local fallback limiter.
Quick Check
Test your understanding of the Redis sliding window.
Recap
You built a distributed sliding window:
- Store request timestamps in a Redis sorted set, one key per client.
- Trim old entries with
ZREMRANGEBYSCORE, count withZCARD. - Wrap trim/count/add in a Lua script for atomicity.
- Set a TTL to free memory, and decide fail-open vs fail-closed for Redis outages.
Lerne API Rate Limiting & Scalability Patterns mit einem KI-Tutor — kostenlos
Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.
- Kurse
- 12
- Lektionen
- 48
Häufig gestellte Fragen
Ist die Lektion „Sliding Window mit Sorted Sets in Redis“ kostenlos?
Ja — der vollständige Text von „Sliding Window mit Sorted Sets in Redis“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des API Rate Limiting & Scalability Patterns-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der API Rate Limiting & Scalability Patterns-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Sliding Window mit Sorted Sets in Redis“?
Implementieren Sie mit sortierten Mengen in Redis einen präzisen verteilten Rate-Limiter mit Sliding Window, atomaren Operationen und automatischem Ablauf alter Einträge. Du übst API Rate Limiting & Scalability Patterns mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um API Rate Limiting & Scalability Patterns zu starten?
Keine Vorkenntnisse erforderlich. API Rate Limiting & Scalability Patterns auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Sliding Window mit Sorted Sets in Redis“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser API Rate Limiting & Scalability Patterns-Lektion Code schreiben und ausführen?
Ja. Jede API Rate Limiting & Scalability Patterns-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Implementierung des Sliding-Window-Logs
- Strategie des Sliding-Window-Counters
- Algorithmusvergleich und Abwägungen
- Sliding Window mit Sorted Sets in Redis