Module 4 · Rate Limiting & API Abuse Prevention

Manish Garg
Manish Garg Associate of (ISC)² · RingSafe
Apr 22, 2026
5 min read
Read as

Last updated: April 29, 2026

Algorithms (token bucket, sliding window), enforcement layers, Redis Lua patterns, abuse patterns and defenses.

Rate limiting is the operational defense that prevents APIs from being abused at scale. Without it, every authenticated endpoint is a potential cost-amplifier (cloud bills), brute-force vector (auth endpoints), or DoS surface. With well-designed rate limits, abusive patterns hit walls quickly while legitimate traffic flows. This module covers rate-limit design, abuse patterns, and the architectures that scale.

Why “set a rate limit” isn’t enough

The naive answer — “100 requests per second per IP” — fails in three common cases:

  • NAT-shared IPs — entire offices and ISPs come from one IP. Rate-limiting per IP punishes legitimate clusters
  • Distributed abuse — attacker uses 10,000 IPs at 1 request each. Per-IP limit useless
  • Asymmetric expense — 100 cheap requests per second is fine; 100 expensive aggregations per second melts the database

Rate limiting needs to be multi-dimensional and aware of cost.

Dimensions to rate-limit on

  • Per-user / per-tenant — primary axis. Authenticated traffic gets per-account limits. Anonymous gets per-IP fallback
  • Per-IP — secondary; useful for unauthenticated endpoints and as anti-distributed-abuse layer
  • Per-endpoint — different limits for different costs (10K req/min for /search, 5 req/min for /reset-password)
  • Per-action category — auth attempts, write operations, expensive reads each tracked
  • Per-API-key — for external developers; tier’d by plan
  • Cost-weighted — each request consumes a “cost” from the user’s budget; cheap reads = 1, expensive aggregations = 100

Algorithms — what to actually implement

Fixed window counter

“100 requests per minute” with the minute being a fixed clock minute. Simple. Edge case: bursting at the boundary lets attacker do 200 in 2 seconds (last second of minute N + first second of minute N+1).

Sliding window log

Track timestamp of every request; count those in the last 60 seconds. Accurate but memory-heavy.

Sliding window counter

Approximation of sliding window using two counters (current and previous window) with weighted blend. Good balance.

Token bucket

Bucket holds N tokens; refills at rate R. Each request consumes a token. Burst-friendly (you can use full bucket immediately) but rate-limited over time. Most production systems use this.

Leaky bucket

Requests enter a queue; queue drains at rate R; overflow is rejected. Smooth rate but no burst. Less common than token bucket in practice.

Where to enforce — gateway vs application

  • Edge / CDN layer (Cloudflare, Fastly, AWS WAF): first line; absorbs the worst — DDoS, scrapers, obvious abuse. Cheap per-request
  • API gateway (Kong, Apigee, AWS API Gateway, Tyk): per-API-key, per-tenant; central management; visible to operators
  • Application layer: business-logic-aware rate limits; per-user, per-action; integrated with auth context

Best practice: layer them. Edge catches the obvious; gateway handles routine rate-limit policy; application catches the business-logic abuse that gateway can’t see.

Storage backends for rate-limit state

  • Redis — most common. Fast, atomic operations (INCR with EXPIRE for fixed window; sorted sets for sliding log)
  • Memcached — works but lacks atomic operations for some patterns
  • In-memory per-instance — only viable for single-instance services or coarse limits; doesn’t scale across replicas
  • Specialised services — Cloudflare Workers KV, AWS API Gateway throttling — managed but coupled to platform

Redis token bucket — pseudocode

def check_and_consume(user_id, cost=1):
  key = f"rl:{user_id}"
  now = time.time()
  refill_rate = 100 / 60   # 100 tokens per 60 seconds
  bucket_max  = 100

  # Lua script for atomicity
  script = """
    local key = KEYS[1]
    local now = tonumber(ARGV[1])
    local rate = tonumber(ARGV[2])
    local max = tonumber(ARGV[3])
    local cost = tonumber(ARGV[4])

    local data = redis.call('HMGET', key, 'tokens', 'last')
    local tokens = tonumber(data[1]) or max
    local last = tonumber(data[2]) or now

    tokens = math.min(max, tokens + (now - last) * rate)

    if tokens < cost then
      redis.call('HSET', key, 'tokens', tokens, 'last', now)
      return 0  -- denied
    end

    tokens = tokens - cost
    redis.call('HSET', key, 'tokens', tokens, 'last', now)
    redis.call('EXPIRE', key, 3600)
    return 1  -- allowed
  """
  return redis.eval(script, 1, key, now, refill_rate, bucket_max, cost)

Communicating limits to clients

Standard headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 47
X-RateLimit-Reset: 1714123456     # Unix timestamp
Retry-After: 30                   # On 429 response, seconds until retry

HTTP status: 429 Too Many Requests. Don’t return 503 (server error) — that’s misleading.

Abuse patterns to design against

Credential stuffing

Attackers replay leaked passwords against your login. Rate limits help; need more:

  • Per-account lockout after N failures (with exponential backoff)
  • Per-IP throttling on /login
  • CAPTCHA after threshold
  • Anomaly detection on geo/device patterns
  • Have-I-Been-Pwned API integration to refuse known-leaked passwords at signup

OTP brute force

4-digit OTP = 10,000 combinations. Attacker brute-forces in seconds without limits. Defenses:

  • Per-account-per-OTP limit (5 attempts then lockout)
  • Per-account-per-day limit on OTP requests (prevent send-spam-then-brute-fresh-OTP cycle)
  • Don’t differentiate “wrong OTP” from “no active OTP” in error messages

Account creation farming

Attackers create accounts at scale for promo abuse, content posting, fraud preparation. Defenses:

  • Per-IP signup limits
  • Email verification before account is fully usable
  • Phone verification for high-value features
  • Behavioral signals: device fingerprint, signup speed (real users take 30+ seconds), browser characteristics
  • Reputation services (e.g., Sift, Fingerprint.com) for high-stake flows

Scraping

Attackers methodically pull your entire catalog/user base via paginated APIs. Defenses:

  • Rate limits per user/IP on list endpoints
  • Maximum page size enforced; no “limit=10000”
  • Cursor-based pagination instead of offset (offset enumeration is trivial)
  • Detect cursor enumeration patterns and throttle progressively
  • Deny anonymous access to list endpoints; require auth even for read

Resource exhaustion

Single user or small group consumes huge backend resources (large file uploads, complex aggregations). Defenses:

  • Cost-weighted rate limits
  • Async processing for expensive operations with quotas (X jobs in flight per tenant)
  • Backpressure mechanism that returns 429 when queue depth exceeds threshold

Quotas vs rate limits

  • Rate limit = short window (per second, per minute). Smooths burst
  • Quota = long window (per day, per month). Caps total usage

Both are needed. SaaS pricing tiers are often quota-based. Both should be communicated to the user via headers and dashboard.

Monitoring — what to alert on

  • 429 rate by endpoint trending up — abuse or under-provisioning
  • Top users by cost — anomalous accounts
  • Requests denied because of complexity score — query patterns to investigate
  • Auth failures by IP/account — credential stuffing in progress
  • New IP address used to authenticate as user X — possible account takeover

What the last module covers

Module 5 covers API gateways and zero-trust at scale — Kong, Apigee, AWS API Gateway, Istio service mesh. Architecture patterns for hundreds of services with consistent auth, observability, and policy enforcement.

🧠
Check your understanding

Module Quiz · 15 questions

Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.

Want this for your team?

Custom team training + practitioner advisory

Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.

Book team training call Replies in 4 working hrs · India-only · Senior consultants