<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1" -->

---
title: Sliding-Window Rate Limiters with TypeScript & Redis
description: A detailed technical guide walks through building a distributed sliding-window rate limiter in TypeScript backed by Redis sorted sets and an atomic Lua script....
canonical: https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: Sliding-Window Rate Limiters with TypeScript & Redis | daily.dev
og:description: A detailed technical guide walks through building a distributed sliding-window rate limiter in TypeScript backed by Redis sorted sets and an atomic Lua script....
og:url: https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1
og:image: https://api.daily.dev/og/posts/JohTnq4x1.png
og:image:alt: Sliding-Window Rate Limiters with TypeScript & Redis
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Sliding-Window Rate Limiters with TypeScript & Redis

**[SitePoint](https://daily.dev/sources/sitepoint)** · 22 min read · 0 upvotes · 0 comments

## Summary

A detailed technical guide walks through building a distributed sliding-window rate limiter in TypeScript backed by Redis sorted sets and an atomic Lua script. It explains why naive check-then-increment approaches suffer TOCTOU race conditions, compares fixed-window, leaky bucket, token bucket, and sliding-window algorithms, and shows the full Lua script line by line for pruning expired entries, summing costs, and admitting or denying requests atomically. It covers dual RPM/TPM quota enforcement, IETF draft-compliant RateLimit-* response headers, Express and Hono middleware wrappers, fail-open/fail-close error handling, Redis Cluster hash-tag key design, and a k6 load test with 200 virtual users proving zero over-admission at a 100 RPM limit. Production considerations include memory sizing per sorted-set entry, key expiry, and circuit-breaker patterns for Redis outages.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://www.sitepoint.com/distributed-sliding-window-rate-limiter-typescript-redis>

## Questions this post answers

### How do I prevent race conditions in a distributed Redis rate limiter across multiple app instances?

Use an atomic Lua script instead of separate read-then-write Redis commands. Because Redis executes Lua scripts atomically and processes commands single-threaded, a script that prunes expired sorted-set entries, sums remaining costs, and conditionally adds a new entry runs as one indivisible operation, eliminating the time-of-check-to-time-of-use race that lets concurrent requests over-admit past the limit.

_Track patterns like atomic Lua scripting for Redis rate limiting as you harden distributed APIs on daily.dev._

### Why is MULTI/EXEC not enough for atomic Redis read-then-write operations like rate limiting?

MULTI/EXEC queues commands and executes them sequentially, but results from earlier commands in the transaction are not visible to later commands within the same transaction, so read-then-write logic can't be expressed without WATCH. WATCH-based optimistic locking then retries under contention, degrading performance exactly when rate limiting needs to be fast and correct.

_Developers debugging Redis transaction semantics can keep tabs on such gotchas via daily.dev._

### How much memory does a Redis sorted-set based sliding-window rate limiter use per key?

Roughly 100 bytes per entry, including the member string, score, and sorted-set overhead, measured via MEMORY USAGE on a 1,000-member test key. At 10,000 entries that comes to about 1 MB per key, making the sliding-window-log approach suitable for API-scale traffic (thousands to tens of thousands of requests per key) rather than CDN-scale traffic of millions of requests per second.

_Engineers sizing Redis capacity for rate limiters can follow deeper infra breakdowns on daily.dev._

## Similar posts on daily.dev

- [Python Rate Limiting: The Limiter That Caused Our Outage](https://daily.dev/posts/python-rate-limiting-the-limiter-that-caused-our-outage-2y3xnfeyu) · SitePoint · 0 upvotes · 0 comments
- [28 Million Decisions Per Second. Zero Allocations. One Rate Limiter.](https://daily.dev/posts/28-million-decisions-per-second-zero-allocations-one-rate-limiter--a6kmxkmhy) · Medium · 0 upvotes · 0 comments
- [System Design Drill Day 7: Rate Limiting APIs, Logins and OTPs with Redis](https://daily.dev/posts/system-design-drill-day-7-rate-limiting-apis-logins-and-otps-with-redis-vwvetnmnk) · C\# Corner · 3 upvotes · 1 comments
- [Rate Limiting Algorithms: Token Bucket vs Sliding Window vs Fixed Window](https://daily.dev/posts/rate-limiting-algorithms-token-bucket-vs-sliding-window-vs-fixed-window-c6i3q4jdl) · Arcjet · 0 upvotes · 0 comments

---

Tags: [#typescript](https://daily.dev/tags/typescript), [#distributed-systems](https://daily.dev/tags/distributed-systems), [#redis](https://daily.dev/tags/redis), [#lua](https://daily.dev/tags/lua)

[View this post on daily.dev](https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"Sliding-Window Rate Limiters with TypeScript \u0026 Redis","url":"https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1"},"datePublished":"2026-09-20T15:32:34.189Z","dateModified":"2026-09-20T15:32:58.561Z","description":"A detailed technical guide walks through building a distributed sliding-window rate limiter in TypeScript backed by Redis sorted sets and an atomic Lua script....","image":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/7e391a2d808a19087a16d6f7a6f6e31b?_a=AQAEuop","thumbnailUrl":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/7e391a2d808a19087a16d6f7a6f6e31b?_a=AQAEuop","isAccessibleForFree":true,"articleSection":"SitePoint","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"SitePoint","logo":"https://media.daily.dev/image/upload/t_logo,f_auto/v1/logos/sitepoint","url":"https://daily.dev/sources/sitepoint"},"commentCount":0,"discussionUrl":"https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":0},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"keywords":"typescript,distributed-systems,redis,lua","timeRequired":"PT22M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"SitePoint","item":"https://daily.dev/sources/sitepoint"},{"@type":"ListItem","position":3,"name":"Sliding-Window Rate Limiters with TypeScript \u0026 Redis"}]}
{"@context":"https://schema.org","@type":"FAQPage","@id":"https://daily.dev/posts/sliding-window-rate-limiters-with-typescript-redis-johtnq4x1#faq","mainEntity":[{"@type":"Question","name":"How do I prevent race conditions in a distributed Redis rate limiter across multiple app instances?","acceptedAnswer":{"@type":"Answer","text":"Use an atomic Lua script instead of separate read-then-write Redis commands. Because Redis executes Lua scripts atomically and processes commands single-threaded, a script that prunes expired sorted-set entries, sums remaining costs, and conditionally adds a new entry runs as one indivisible operation, eliminating the time-of-check-to-time-of-use race that lets concurrent requests over-admit past the limit. Track patterns like atomic Lua scripting for Redis rate limiting as you harden distributed APIs on daily.dev."}},{"@type":"Question","name":"Why is MULTI/EXEC not enough for atomic Redis read-then-write operations like rate limiting?","acceptedAnswer":{"@type":"Answer","text":"MULTI/EXEC queues commands and executes them sequentially, but results from earlier commands in the transaction are not visible to later commands within the same transaction, so read-then-write logic can't be expressed without WATCH. WATCH-based optimistic locking then retries under contention, degrading performance exactly when rate limiting needs to be fast and correct. Developers debugging Redis transaction semantics can keep tabs on such gotchas via daily.dev."}},{"@type":"Question","name":"How much memory does a Redis sorted-set based sliding-window rate limiter use per key?","acceptedAnswer":{"@type":"Answer","text":"Roughly 100 bytes per entry, including the member string, score, and sorted-set overhead, measured via MEMORY USAGE on a 1,000-member test key. At 10,000 entries that comes to about 1 MB per key, making the sliding-window-log approach suitable for API-scale traffic (thousands to tens of thousands of requests per key) rather than CDN-scale traffic of millions of requests per second. Engineers sizing Redis capacity for rate limiters can follow deeper infra breakdowns on daily.dev."}}]}
```

