advanced
Rate limits and API auth
Protect APIs with scoped credentials, authorization checks, quotas, burst limits, retry-after guidance, and abuse monitoring.
Public and partner APIs need **authentication**, **authorization**, and **rate limits** as one system — limits without identity are easy to bypass; auth without quotas invites abuse.
Auth patterns:
- **API keys** for server-to-server (scoped, rotatable, never in frontend bundles).
- **OAuth2/OIDC** for user-delegated access (short-lived access tokens, refresh rotation).
- **mTLS** or signed requests for high-trust B2B.
Authorization checks every request: subject, action, resource, tenant context. Fail closed.
Rate limiting dimensions:
- Per key / user / IP / tenant.
- Token bucket or sliding window for burst + sustained limits.
- Separate budgets for expensive endpoints.
HTTP/1.1 429 Too Many Requests
Retry-After: 60
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1710000060
{"type":"rate_limit_exceeded","detail":"Try again in 60 seconds"}
On interviews: 401 vs 403, storing hashed API keys, distributed rate limiting (Redis), and graceful degradation under attack.
Common pitfalls: limits only by IP (NAT pain), no Retry-After, authorization in only one service layer, and long-lived tokens without rotation.
The trade-off is strict security versus developer friction — document quotas, sandbox keys, and self-service rotation.
Checklist:
- Scoped credentials with least privilege.
- 429 with Retry-After and limit headers.
- Central authZ policy or consistent middleware.
- Monitor abuse and anomaly spikes.