How to Implement Rate Limiting with Redis and Lua Scripts

This article explains why rate limiting is essential for service performance and data security, and demonstrates two practical Redis-based implementations—a Lua script approach and a Redis‑cell module method—complete with code examples, usage details, and a brief comparison.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Implement Rate Limiting with Redis and Lua Scripts

Why Limit Access Frequency

When building service APIs, rate limiting is often required, e.g., restricting a user to at most 100 requests per minute.

The main purposes are to ensure service performance and protect data security.

Without limits, callers can flood the service, causing high load, reduced performance, and enabling brute‑force attacks on authentication‑protected endpoints.

Implementing with Redis

Redis offers convenient ways to implement rate limiting. Below are two effective methods.

(1) Solution 1 – Lua Script

Idea

The limiting logic is encapsulated in a Lua script; callers provide a key, the maximum count, and expiration time, and the script returns whether the request is allowed.

Code

local notexists = redis.call("set", KEYS[1], 1, "NX", "EX", tonumber(ARGV[2]))
if (notexists) then
  return 1
end
local current = tonumber(redis.call("get", KEYS[1]))
if (current == nil) then
  local result = redis.call("incr", KEYS[1])
  redis.call("expire", KEYS[1], tonumber(ARGV[2]))
  return result
end
if (current >= tonumber(ARGV[1])) then
  error("too many requests")
end
local result = redis.call("incr", KEYS[1])
return result

Invoke with eval:

eval script 1 key max_requests expiration_seconds

(2) Solution 2 – Redis‑Cell Module

Redis 4 introduced a module system; the official redis‑cell module provides a single command for rate limiting.

Example: CL.THROTTLE user123 15 30 60 user123 is the key

15 is the maximum quota

30 is the allowed number of requests

60 is the time window in seconds

This means user123 can make up to 30 requests within a 60‑second window, with a total quota of 15.

Returned values:

1) (integer) 0   # 0 = allowed, 1 = rejected
2) (integer) 16  # total quota
3) (integer) 15  # remaining quota
4) (integer) -1  # seconds until retry, -1 means no limit
5) (integer) 2   # seconds until quota restores

Each execution decrements the remaining quota; when the quota is exhausted or the request count exceeds the limit, the request is rejected.

Summary

Rate limiting can be implemented in many ways, such as Nginx or HAProxy modules, Guava in Java, or Redis‑based solutions. The Lua‑script method is widely adopted by large cloud providers like Heroku and payment platforms like Stripe. The module‑based approach depends on Redis 4 becoming stable.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

redisrate limitingLua
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.