0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · บทเรียน

การจำกัดอัตราและรูปแบบการใช้งานที่ควรหลีกเลี่ยง

ออกแบบและสร้างกลไกจำกัดอัตราที่มีประสิทธิภาพด้วย Redis เพื่อปกป้อง API และบริการของคุณ

การจำกัดอัตราและรูปแบบการใช้งานที่ควรหลีกเลี่ยง เป็นบทเรียน Redis Caching & Messaging (Pub/Sub, Streams) ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Redis Caching & Messaging (Pub/Sub, Streams) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Redis Caching & Messaging (Pub/Sub, Streams) มีบทเรียนทั้งหมด 4 บทเรียน

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

Why Rate Limit?

Rate limiting is a crucial technique to control the frequency of requests an application receives. Think of it as a bouncer at a club, letting only a certain number of people in at a time.

It protects your APIs and services from:

  • Abuse: Preventing malicious attacks like brute-force attempts.
  • Overload: Ensuring your servers aren't overwhelmed by too many requests.
  • Fair Usage: Distributing access fairly among all users.

Rate Limiting Concepts

When we talk about rate limiting, a few key terms come up:

  • Limit: The maximum number of requests allowed.
  • Window: The time period over which the limit applies (e.g., 60 seconds).
  • Burst: A sudden spike in requests.

Different algorithms exist, like Fixed Window and Sliding Window, each with its own trade-offs.

Redis's Role in Rate Limiting

Redis is an excellent choice for implementing rate limiters due to its speed, in-memory nature, and atomic operations.

Its ability to quickly increment counters and set expirations makes it ideal for tracking request frequencies across a distributed system.

Fixed Window Algorithm

The Fixed Window algorithm is one of the simplest to implement. It works by:

  1. Defining a fixed time window (e.g., 60 seconds).
  2. Counting requests within that window.
  3. Blocking requests once the limit is reached.

At the end of each window, the counter resets. This method is straightforward but can allow bursts of requests at the window boundaries.

Fixed Window in Action

Here's how you can implement a basic fixed-window rate limiter using Redis's INCR and EXPIRE commands.

Try running this Python example:

import redis
import time

r = redis.Redis(decode_responses=True)

def check_rate_limit(user_id, limit_per_min):
    key = f"rl:{user_id}"
    # Increment counter for the user
    current_count = r.incr(key)
    
    # If it's the first request in this window, set expiration
    if current_count == 1:
        r.expire(key, 60) # Expire in 60 seconds
    
    return current_count <= limit_per_min

if __name__ == "__main__":
    test_user = "user_A"
    rate_limit = 3 # 3 requests per minute

    print(f"User '{test_user}' limit: {rate_limit} req/min")

    for i in range(1, 6):
        if check_rate_limit(test_user, rate_limit):
            print(f"Request {i}: ALLOWED")
        else:
            print(f"Request {i}: BLOCKED")
        time.sleep(0.5) # Simulate quick requests
    
    print("\nWaiting for 60s window to reset...")
    # In a real app, this delay would be handled by subsequent requests
    # For demo, we'll clear the key
    r.delete(f"rl:{test_user}") 
    time.sleep(1) # Small pause
    
    print("Window reset. New request:")
    if check_rate_limit(test_user, rate_limit):
        print("Request 1: ALLOWED")
    else:
        print("Request 1: BLOCKED")

Sliding Window Log Algorithm

The Sliding Window Log algorithm offers more accuracy by tracking individual request timestamps.

Here's how it works:

  1. Each request's timestamp is stored in a Redis Sorted Set (ZSET).
  2. When a new request arrives, old timestamps (outside the current window) are removed.
  3. The number of remaining timestamps in the ZSET is the current request count.

This method prevents the burst issue seen at fixed window boundaries.

Sliding Window Demo

Let's see the Sliding Window Log in action. We'll use Redis's ZADD to add timestamps and ZREMRANGEBYSCORE to remove old ones.

Try running this example:

import redis
import time

r = redis.Redis(decode_responses=True)

def check_sliding_window_limit(user_id, limit, window_seconds):
    key = f"rl_sliding:{user_id}"
    current_time = int(time.time() * 1000) # Milliseconds timestamp
    
    # Remove scores older than the window
    r.zremrangebyscore(key, 0, current_time - (window_seconds * 1000))
    
    # Add current request timestamp
    r.zadd(key, {current_time: current_time})
    
    # Set expiration for the key itself to clean up old rate limiters
    # This is a fallback if no new requests come for a long time
    r.expire(key, window_seconds + 5) 
    
    # Count requests in the window
    current_requests = r.zcard(key)
    return current_requests <= limit

if __name__ == "__main__":
    test_user = "user_B"
    rate_limit = 3 # 3 requests per 10 seconds
    window = 10 # seconds

    print(f"User '{test_user}' limit: {rate_limit} req/{window}s (Sliding Log)")

    for i in range(1, 6):
        if check_sliding_window_limit(test_user, rate_limit, window):
            print(f"Request {i}: ALLOWED")
        else:
            print(f"Request {i}: BLOCKED")
        time.sleep(1) # Simulate requests over time
    
    print("\nWaiting for window to slide...")
    time.sleep(window)
    
    print("Window slid. New request:")
    if check_sliding_window_limit(test_user, rate_limit, window):
        print("Request 1: ALLOWED")
    else:
        print("Request 1: BLOCKED")

Common Pitfalls

When implementing rate limiting, avoid these common anti-patterns:

  • Using KEYS *: Never use this in production to find rate limit keys, as it can block your Redis server.
  • Ignoring Bursts: Simple fixed windows can allow many requests at window boundaries, which might still overload your service.
  • Over-engineering: Don't make your rate limiting logic overly complex, as it can introduce bugs and performance overhead.
  • No Client Feedback: Always return appropriate HTTP status codes (like 429 Too Many Requests) and Retry-After headers.

Rate Limiting Best Practices

To build robust rate limiters with Redis:

  • Atomic Operations: Always use atomic Redis commands like INCR, ZADD, and EXPIRE to prevent race conditions.
  • Set Expirations: Ensure your Redis keys have appropriate Time-To-Live (TTL) values to clean up old data.
  • Choose Wisely: Select the right algorithm (fixed, sliding log, sliding counter) based on your accuracy and performance needs.
  • Provide Feedback: Inform clients when they are rate-limited using standard HTTP responses.
  • Monitor: Keep an eye on your rate limiters to ensure they are working as expected and not causing false positives or negatives.

Check Your Knowledge

You've learned about the Fixed Window algorithm. Now, let's test your understanding of the Redis commands involved.

Recap & Next Steps

In this lesson, we explored the critical role of rate limiting in protecting your services and ensuring fair usage. You learned how Redis's speed and atomic operations make it an ideal tool for this.

We covered two fundamental algorithms: the Fixed Window (using INCR and EXPIRE) and the more accurate Sliding Window Log (using ZADD and ZREMRANGEBYSCORE).

Remember to avoid common anti-patterns and follow best practices for robust rate limiting. Keep practicing these patterns to master them!

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

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

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

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

ออกแบบและสร้างกลไกจำกัดอัตราที่มีประสิทธิภาพด้วย Redis เพื่อปกป้อง API และบริการของคุณ คุณปฏิบัติ Redis Caching & Messaging (Pub/Sub, Streams) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Redis Caching & Messaging (Pub/Sub, Streams) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Redis Caching & Messaging (Pub/Sub, Streams) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

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

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

ฉันเขียนและรันโค้ดในบทเรียน Redis Caching & Messaging (Pub/Sub, Streams) นี้ได้ไหม

ได้ บทเรียน Redis Caching & Messaging (Pub/Sub, Streams) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. รูปแบบแคชขั้นสูง
  2. การจัดการเซสชันด้วย Redis
  3. การจำกัดอัตราและรูปแบบการใช้งานที่ควรหลีกเลี่ยง
  4. กลยุทธ์การทำให้แคชใช้ไม่ได้
← กลับไปที่ Redis Caching & Messaging (Pub/Sub, Streams)