0Pricing
API Rate Limiting & Scalability Patterns · บทเรียน

การจำกัดอัตราแบบกระจายด้วย Redis

เรียนรู้การใช้ Redis เพื่อสร้างตัวจำกัดอัตราแบบกระจายที่แข็งแกร่งและขยายขนาดได้ ซึ่งทำงานครอบคลุมอินสแตนซ์บริการหลายรายการ

การจำกัดอัตราแบบกระจายด้วย Redis เป็นบทเรียน API Rate Limiting & Scalability Patterns ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน API Rate Limiting & Scalability Patterns และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส API Rate Limiting & Scalability Patterns มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Scaling Beyond Single Server

In previous lessons, we learned about basic rate limiting. But what happens when your application grows and runs on multiple servers?

  • In-memory limits: They only track requests on a single server.
  • Multiple servers: Each server has its own counter, leading to inaccurate and ineffective limits.
  • The problem: Users can bypass limits by hitting different servers.

We need a way for all servers to share the same rate limit state.

Introducing Redis for Shared State

To build a distributed rate limiter, we need a centralized, fast data store accessible by all our application instances. This is where Redis shines!

  • What is Redis? An open-source, in-memory data structure store.
  • Why Redis? It's extremely fast, supports various data types, and is designed for concurrent access.
  • Key for Rate Limiting: Its atomic operations are perfect for incrementing counters reliably across multiple services.

Redis Commands for Counters

Redis provides simple yet powerful commands that are ideal for building rate limiters. The two main ones you'll use are INCR and EXPIRE.

  • INCR key: Atomically increments the number stored at key by one. If the key doesn't exist, it's set to 0 before incrementing.
  • EXPIRE key seconds: Sets a timeout on key. After the timeout, the key is automatically deleted. This is crucial for defining our rate limiting windows.

These commands ensure our counters are consistent even with many concurrent requests.

Implementing Fixed Window with Redis

Let's consider a Fixed Window Counter algorithm using Redis. Imagine we want to limit a user to 5 requests per 60 seconds.

  1. Define a key: A unique key for the user and the current time window, e.g., user:123:2023-10-27-10:00.
  2. Increment Counter: When a request comes in, use INCR on this key.
  3. Set Expiry: For the first request in a new window, also use EXPIRE to set the key's timeout (e.g., 60 seconds).
  4. Check Limit: Before incrementing, check if the current count for the key is less than the allowed limit.

Basic Redis Fixed Window Code

Here's a simple Python example for a fixed window rate limiter using Redis. This snippet shows the core logic without full error handling.

import redis
import time

def is_rate_limited(user_id, limit, window_seconds):
    r = redis.Redis(host='localhost', port=6379, db=0)
    current_minute = int(time.time() // window_seconds)
    key = f"rate_limit:{user_id}:{current_minute}"

    count = r.get(key)
    if count is None:
        r.setex(key, window_seconds, 0) # Initialize and set expiry
        count = 0
    else:
        count = int(count)

    if count < limit:
        r.incr(key)
        return False # Not rate limited
    return True # Rate limited

if __name__ == "__main__":
    user = "user_alice"
    requests_limit = 5
    time_window = 60 # seconds

    print(f"Testing rate limiter for {user} ({requests_limit} reqs/{time_window}s)")
    for i in range(1, 8):
        if is_rate_limited(user, requests_limit, time_window):
            print(f"Request {i}: Rate limited!")
        else:
            print(f"Request {i}: OK")
            time.sleep(0.1) # Simulate some work

Addressing Race Conditions

In the previous example, the `get`, `setex`, and `incr` operations are separate. This can lead to a race condition:

  • Two requests might `GET` the key when it doesn't exist.
  • Both might `SETEX` it, potentially overwriting each other's expiry.
  • The `EXPIRE` might not be set for the *first* incremented value, causing the counter to persist indefinitely.

We need to perform these multiple Redis commands as a single, atomic operation.

Atomic Operations with Lua Scripts

Redis allows you to execute server-side Lua scripts. This is incredibly powerful for rate limiting because:

  • Atomicity: A Lua script runs as a single, indivisible command. No other Redis commands can interrupt it.
  • Efficiency: Reduces network round trips for complex operations.

We can write a Lua script to check the counter, increment it, and set its expiry all in one go.

Lua Script Example for Limiter

Here's a Lua script for an atomic fixed window counter. It takes the key, limit, and window duration as arguments.

local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])

local current_count = redis.call('INCR', key)

if current_count == 1 then
redis.call('EXPIRE', key, window)
end

if current_count > limit then
return 1 -- Rate limited
else
return 0 -- Not rate limited
end

Python Calling Lua Script

Now, let's see how to integrate and execute this Lua script from our Python application. The EVAL command sends the script to Redis for atomic execution.

import redis
import time

def is_rate_limited_atomic(user_id, limit, window_seconds):
    r = redis.Redis(host='localhost', port=6379, db=0)
    current_minute = int(time.time() // window_seconds)
    key = f"rate_limit_atomic:{user_id}:{current_minute}"

    # The Lua script to execute
    lua_script = """
    local key = KEYS[1]
    local limit = tonumber(ARGV[1])
    local window = tonumber(ARGV[2])

    local current_count = redis.call('INCR', key)

    if current_count == 1 then
        redis.call('EXPIRE', key, window)
    end

    if current_count > limit then
        return 1 -- Rate limited
    else
        return 0 -- Not rate limited
    end
    """

    # Execute the Lua script atomically
    # KEYS[1] is 'key'
    # ARGV[1] is 'limit', ARGV[2] is 'window_seconds'
    result = r.eval(lua_script, 1, key, limit, window_seconds)
    return bool(result)

if __name__ == "__main__":
    user = "user_bob"
    requests_limit = 5
    time_window = 60 # seconds

    print(f"Testing atomic rate limiter for {user} ({requests_limit} reqs/{time_window}s)")
    for i in range(1, 8):
        if is_rate_limited_atomic(user, requests_limit, time_window):
            print(f"Request {i}: Rate limited!")
        else:
            print(f"Request {i}: OK")
            time.sleep(0.1) # Simulate some work

Distributed Limiting Check

Which of the following are key benefits of using Redis for distributed rate limiting, especially when using Lua scripting?

Recap: Redis for Scale

Great job! You've learned how to build robust distributed rate limiters using Redis.

  • Distributed Problem: In-memory limits fail with multiple application instances.
  • Redis Solution: Provides a fast, centralized, and shared state for rate limit counters.
  • Key Commands: INCR and EXPIRE are fundamental.
  • Atomicity with Lua: Crucial for preventing race conditions and ensuring correctness when multiple Redis commands are involved.

This approach is foundational for building scalable and resilient APIs.

คำถามที่พบบ่อย

บทเรียน “การจำกัดอัตราแบบกระจายด้วย Redis” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจำกัดอัตราแบบกระจายด้วย Redis” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส API Rate Limiting & Scalability Patterns ให้อัปเกรดเป็น CoddyKit PRO คอร์ส API Rate Limiting & Scalability Patterns มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจำกัดอัตราแบบกระจายด้วย Redis”

เรียนรู้การใช้ Redis เพื่อสร้างตัวจำกัดอัตราแบบกระจายที่แข็งแกร่งและขยายขนาดได้ ซึ่งทำงานครอบคลุมอินสแตนซ์บริการหลายรายการ คุณปฏิบัติ API Rate Limiting & Scalability Patterns ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน API Rate Limiting & Scalability Patterns หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน API Rate Limiting & Scalability Patterns บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การจำกัดอัตราแบบกระจายด้วย Redis” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน API Rate Limiting & Scalability Patterns นี้ได้ไหม

ได้ บทเรียน API Rate Limiting & Scalability Patterns ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การออกแบบตัวจำกัดอัตราในหน่วยความจำ
  2. การจำกัดอัตราแบบกระจายด้วย Redis
  3. การจัดการเมื่อเกินขีดจำกัดอัตรา
  4. การทดสอบและการตรวจสอบตัวจำกัดอัตราการส่งคำขอ
← กลับไปที่ API Rate Limiting & Scalability Patterns