study 02 of 03
Rate-limited REST gateway
API gateway layer: Redis token-bucket rate limiter + idempotency key cache, allowing safe retry semantics for non-idempotent upstream operations.
The problem
Downstream services expose non-idempotent endpoints (payment, order create). Clients retry on timeout. Without gate-level idempotency, a timeout followed by retry causes duplicate operations on the upstream.
Constraints
- Rate limit must be enforced per-client-key, not globally.
- Idempotency window: 24 hours. Same key within the window returns cached response.
- The cache write and the upstream call have to be atomic. A partial commit leaves ghost idempotency keys behind.
- Implementation must add < 5ms to p99 latency on cache hit.
Architecture
Hover, tap, or tab into a box to read what it does.
Trade-offs
Redis MULTI/EXEC for token bucket
instead of Lua script
Both are atomic. MULTI/EXEC is explicit and debuggable without a Redis Lua runtime. Lua is faster but harder to instrument.
Cache-then-proxy (write cache before returning)
instead of Write cache after returning to client
Writing after the response leaves a race where the client gets the response but the key is not cached. A second request within the window hits upstream again.
24-hour idempotency window
instead of Session-scoped or indefinite
Short enough to clear space. Long enough to cover retry loops in client code that might run overnight. Indefinite would require a dedicated eviction strategy.
What I'd change
- Add a pending state to the idempotency key. Mark it in flight before calling upstream, so two concurrent duplicates cannot both get through.
- Expose idempotency key status via a side-channel GET endpoint for debugging.
- Move rate-limit counters to Redis Cluster for multi-node horizontal scale.