Backend & Cloud Engineer Guide: API Gateways, Redis Lua Rate Limiting & JWT Auth
When a single noisy tenant, runaway webhook loop, or scraping bot hammers your public REST or GraphQL APIs, unprotected backend workers exhaust database connection pools and starve every other customer on your platform. For AI platforms, an unthrottled endpoint can burn thousands of dollars in upstream LLM token quotas in minutes. As a Senior Backend Engineer and Cloud Engineer, I engineer low-latency API gateways, atomic Redis Lua rate limiters, and zero-trust JWT authentication middleware in Go and Python.
1. Why Naive Redis GET + INCR Rate Limiters Fail Under Concurrency
Implementing a rate limiter by running GET key in Python/Go and then conditionally calling INCR key and EXPIRE key introduces two production bugs: concurrent requests read the same counter value before either increments it, and if a worker crashes between INCR and EXPIRE, the key persists forever without a TTL—permanently blocking the customer. By executing a Token Bucket algorithm inside an atomic Redis Lua script, check-and-decrement executes as a single indivisible operation on the Redis thread:
import time
import redis
TOKEN_BUCKET_LUA = """
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])
local data = redis.call("HMGET", key, "tokens", "last_refill")
local tokens = tonumber(data[1])
local last_refill = tonumber(data[2])
if tokens == nil then
tokens = capacity
last_refill = now
else
local elapsed = math.max(0, now - last_refill)
tokens = math.min(capacity, tokens + (elapsed * refill_rate))
last_refill = now
end
if tokens < requested then
local retry_after = math.ceil((requested - tokens) / refill_rate)
return {0, math.floor(tokens), retry_after}
end
tokens = tokens - requested
local ttl = math.ceil(capacity / refill_rate) * 2
redis.call("HMSET", key, "tokens", tokens, "last_refill", last_refill)
redis.call("EXPIRE", key, ttl)
return {1, math.floor(tokens), 0}
"""
class AtomicRateLimiter:
def __init__(self, redis_client: redis.Redis):
self.script = redis_client.register_script(TOKEN_BUCKET_LUA)
def allow_request(self, tenant_id: str, capacity: int = 100, refill_per_sec: float = 10.0) -> tuple[bool, int, int]:
allowed, remaining, retry_after = self.script(
keys=[f"rl:tb:{tenant_id}"],
args=[capacity, refill_per_sec, time.time(), 1],
)
return bool(allowed), int(remaining), int(retry_after)
2. Edge JWKS Caching & Tier-Aware Quota Headers
An API Gateway should never query PostgreSQL on every request just to validate a bearer token. By encoding tenant tier and scopes inside short-lived RS256/EdDSA JWTs and caching the Identity Provider's JSON Web Key Set (JWKS) in memory with background refresh, the gateway verifies signatures in under 0.2ms and returns standard IETF rate-limit headers (RateLimit-Remaining, Retry-After).
3. Hire a Senior Backend & Cloud Engineer
Need to harden your API gateway, prevent abuse on expensive AI endpoints, or design multi-region edge routing? Explore my Backend Engineer Pillar Guide, review my Cloud Engineer Architecture Guide, or book a 1-Day API Architecture Sprint.