API Rate Limiting & Scalability Patterns · درس

تحديد المعدل الموزع باستخدام Redis

تعلّم كيفية مشاركة حالة حدود المعدل بين عدة مثيلات للبوابات والخدمات باستخدام Redis والعمليات الذرية ونصوص Lua لتجنب حالات التسابق.

الدرس 4 من 413 خطوة

تحديد المعدل الموزع باستخدام Redis درس مجاني في API Rate Limiting & Scalability Patterns على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في API Rate Limiting & Scalability Patterns، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة API Rate Limiting & Scalability Patterns 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

The Multi-Instance Problem

When you run several gateway replicas, each one keeping its own in-memory counter means a client gets N x limit total — once per instance.

To enforce one global limit, every instance must read and update shared state.

Why Redis

Redis is the de facto choice for distributed rate limiting because it offers:

  • Sub-millisecond in-memory reads and writes
  • Atomic commands like INCR
  • Built-in expiry for automatic window resets
  • Lua scripting for multi-step atomic logic

A Naive Counter

The simplest fixed-window counter uses INCR plus EXPIRE:

The first request in a window creates the key and sets a TTL; later requests just increment.

INCR rate:user:42
-- if reply == 1 (first hit):
EXPIRE rate:user:42 60

The Race Condition

Running INCR then EXPIRE as two separate calls has a bug: if the process crashes between them, the key has no TTL and the limit never resets.

The fix is to make the check-and-increment atomic.

Atomicity with Lua

Redis runs a Lua script as a single atomic unit. We can check the count, increment, and set expiry without interruption.

local c = redis.call('INCR', KEYS[1])
if c == 1 then
  redis.call('EXPIRE', KEYS[1], ARGV[2])
end
if c > tonumber(ARGV[1]) then
  return 0
end
return 1

Calling the Script

From the gateway you invoke the script with EVAL, passing the key, the limit, and the window size.

A return of 1 means allow; 0 means reject with 429 Too Many Requests.

allowed = redis.eval(script, keys=['rate:user:42'], args=[100, 60])
if allowed == 0:
    return Response(status=429)

Sliding Window with Sorted Sets

For smoother limiting, store request timestamps in a sorted set. Remove old entries, count what remains, then add the new one.

ZREMRANGEBYSCORE rate:user:42 0 (now-window)
ZCARD rate:user:42
ZADD rate:user:42 now now

Returning Rate Limit Headers

Good gateways tell clients where they stand using standard headers:

  • X-RateLimit-Limit
  • X-RateLimit-Remaining
  • Retry-After on a 429

The Lua script can return remaining count alongside the allow flag.

Handling Redis Failures

What if Redis is unreachable? Two strategies:

  • Fail open — allow traffic; favors availability
  • Fail closed — reject traffic; favors protection

Most APIs fail open with a local fallback limiter to avoid a full outage.

Reducing Latency

Every limit check is a network hop. Cut overhead by:

  • Co-locating Redis near the gateway
  • Using connection pooling
  • Batching counters with a short local cache for very hot keys

Keying by Identity

The rate limit key defines what you are limiting. Common choices:

  • rate:ip:1.2.3.4 for anonymous traffic
  • rate:user:42 for authenticated users
  • rate:apikey:abc for API clients

Pick the most specific identity available so one abuser cannot exhaust a shared bucket.

Quick Check

Test your grasp of distributed limiting.

Recap

You learned to share rate limit state across instances:

  • A shared Redis store gives one global limit
  • Lua scripts make check-and-increment atomic
  • Sorted sets enable sliding windows
  • Decide fail open vs. closed for Redis outages
البدء مجانًا

تعلم API Rate Limiting & Scalability Patterns مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
12
الدروس
48

الأسئلة الشائعة

هل درس «تحديد المعدل الموزع باستخدام Redis» مجاني؟

نعم — نص درس «تحديد المعدل الموزع باستخدام Redis» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة API Rate Limiting & Scalability Patterns، انتقل إلى CoddyKit PRO. تتضمن دورة API Rate Limiting & Scalability Patterns 4 دروس في المجموع.

ماذا ستتعلم في «تحديد المعدل الموزع باستخدام Redis»؟

تعلّم كيفية مشاركة حالة حدود المعدل بين عدة مثيلات للبوابات والخدمات باستخدام Redis والعمليات الذرية ونصوص Lua لتجنب حالات التسابق. تتمرن على API Rate Limiting & Scalability Patterns مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ API Rate Limiting & Scalability Patterns؟

لا تُشترط خبرة سابقة. API Rate Limiting & Scalability Patterns على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «تحديد المعدل الموزع باستخدام Redis»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس API Rate Limiting & Scalability Patterns هذا؟

نعم. كل درس في API Rate Limiting & Scalability Patterns يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. أنماط التكامل مع بوابات API
  2. تحديد المعدل العام مقابل الخاص بكل خدمة
  3. الضبط الديناميكي لمعدل الطلبات
  4. تحديد المعدل الموزع باستخدام Redis
← العودة إلى API Rate Limiting & Scalability Patterns