05. API Security and Rate Limits¶
⏱️ Estimated time: 33 min | Level: intermediate
ELI5 callback: In the apartment building, the front door checks identity, the elevator key limits movement, the wall keeps tenants apart, the audit records rule-following, and the safe protects valuables.
1) Think of the API boundary as a guard rail¶
APIs are where untrusted input meets trusted business logic. That boundary deserves suspicion by default.
See. Every field, header, method, and body shape can become an attack path or an abuse path.
So what to do? Validate early, normalize carefully, and reject loudly when data breaks contract.
API security is not only about attackers. It also protects you from buggy clients and accidental overload.
Now watch. A great domain model can still fall if the API edge is lazy.
- The front door reminds you to verify caller identity before serving sensitive APIs.
- The elevator key reminds you that endpoint-level permissions still matter after login.
- The wall reminds you that tenant context must travel through every request path.
- The audit reminds you that sensitive API access needs evidence and traceability.
-
The safe reminds you that payload protection and secret handling stay relevant too.
-
Validate schema, size, type, enum range, and encoding at the edge.
- Reject unknown fields on critical routes when compatibility rules allow it.
- Canonicalize identifiers before comparing them in authorization logic.
- Set body size and upload size limits before parsing large requests.
2) Browser-facing APIs need CORS and CSRF discipline¶
CORS is a browser rule about which origins may call a resource. It is not a full security model.
CSRF is about tricking an authenticated browser into sending an unwanted action.
Simple, no? CORS controls reading by web origins. CSRF controls unwanted submission using existing credentials.
Cookie-based sessions need CSRF protection. Token-based APIs in headers reduce that specific risk, but not all browser risks.
Do not use wildcard origins with credentials unless you enjoy incident calls.
- Allow only expected origins, methods, and headers.
- Prefer SameSite cookies and CSRF tokens for state-changing browser requests.
- Separate public read APIs from credentialed mutation APIs when possible.
- Review preflight handling because hidden mismatches create confusing failures.
- Teach teams that CORS errors and authorization errors are not the same problem.
┌──────────┐ Origin + cookies ┌─────────────┐ │ Browser │─────────────────────▶│ API / Edge │ └──────────┘◀──── CORS headers ───└─────────────┘ │ │ └──── CSRF token or SameSite ────┘
3) Rate limits are fairness controls and abuse controls¶
Rate limiting protects availability, cost, and fairness. It also slows brute force and scraping attacks.
Good limits are multidimensional: per IP, per user, per tenant, per token, and sometimes per endpoint.
Now watch. One global limit is easy to implement and easy to bypass or misuse.
Burst limits and steady-state limits solve different problems. Design both intentionally.
API gateways help, but backend services still need local safety checks for expensive operations.
- Limit login, password reset, OTP verification, and token refresh routes separately.
- Set stricter budgets for export, search, and AI inference routes because cost is asymmetric.
- Return clear retry guidance so good clients back off cleanly.
- Track both rejected and accepted volumes because near-limit behaviour matters.
- Do not forget internal APIs because abuse can start from inside too.
-
Make quota ownership clear between product, platform, and finance teams.
-
Token buckets are simple for bursts.
- Leaky bucket or sliding windows can smooth fairness differently.
- Choose the algorithm based on the shape of abuse you expect.
4) Gateways help, but application checks still matter¶
API gateways centralize auth, rate limits, routing, and observability. Good. Use them wisely.
But the gateway cannot understand every business rule, tenant nuance, or record-level permission.
See. Edge controls reduce noise. Application controls protect the real resource.
Input validation should happen at the edge and near the core if transformations occur in between.
A gateway is a strong helper, not a substitute for secure handlers.
- Authenticate once at the edge, then pass trusted context carefully downstream.
- Re-check object-level authorization inside the service that owns the object.
- Validate file uploads, content types, and decompression behaviour close to processing code.
- Shield internal error details so attackers do not learn schema or stack behaviour.
- Use idempotency keys for payment-like operations where retries are normal.
- Log correlation IDs so abuse patterns are traceable across services.
5) Common mistakes and a practical checklist¶
API security fails when teams assume a happy client, a friendly network, or perfect upstream validation.
See. Attackers love inconsistent parsing, optional fields, and forgotten legacy routes.
Now watch. An endpoint hidden from docs is still an endpoint.
The practical answer is layered controls: validation, authentication, authorization, limits, and observability together.
Short punchy rule: reject bad input fast, serve valid input safely, and meter expensive work.
- Check pagination and filtering endpoints for denial-of-wallet problems.
- Review old mobile routes and internal admin routes with the same threat model.
- Make status codes meaningful so monitoring sees real failure patterns.
- Store request bodies carefully because logs can become a sensitive data leak.
- Fuzz parsers and validators for file uploads and complex JSON payloads.
- Document which limits are contractual and which are purely defensive.
The API edge should fail closed on malformed requests.
Legacy clients create modern security work.
Telemetry should distinguish attack noise from user mistakes.
Hidden routes still need rate limits and auth.
Gateways centralize patterns, but services own business truth.
Expensive endpoints deserve special budgets, not equal budgets.
Idempotency protects both users and operators during retries.
CORS is a browser rule, not a permission system.
One endpoint with weak limits can dominate your entire cost profile.
Input validation is a product reliability feature too.
Where this lives in the wild¶
- Public REST and GraphQL APIs serving browser, mobile, and partner clients.
- API gateways enforcing common authentication and throttling policies.
- Payment, billing, and export endpoints with high-cost or high-risk operations.
- Internal admin and support APIs that must still handle untrusted input safely.
- AI inference APIs where prompt size and concurrency must be controlled carefully.
Pause and recall¶
- Why is CORS not the same as authorization?
- Why should rate limits differ by endpoint type?
- What security checks still belong inside the application even with a gateway?
- Why do malformed request limits matter for reliability too?
Interview Q&A¶
Q: What is the difference between CORS and CSRF? A: CORS controls which browser origins may read responses, while CSRF stops unwanted authenticated actions from a user browser. Common wrong answer to avoid: "They are basically the same browser security feature."
Q: Why are per-tenant and per-endpoint limits useful? A: Because abuse shape, cost, and fairness differ across tenants and routes, so one flat limit is crude. Common wrong answer to avoid: "A single requests-per-minute number solves rate limiting."
Q: Why is object-level authorization still needed after gateway auth? A: Because only the owning service truly knows whether this caller may access this exact resource. Common wrong answer to avoid: "If the token is valid at the gateway, the backend is done."
Q: What is a common mistake with API logs? A: Logging sensitive bodies or tokens in the name of debugging and accidentally creating a data leak. Common wrong answer to avoid: "More logs are always safer."
Apply now (5 min)¶
Pick one write API in your product and list every edge control before business logic runs.
Mark validation, auth, authorization, rate limit, payload size, and idempotency points.
Then ask which one control would fail if the gateway were misconfigured.
If the answer is all of them, your backend needs stronger ownership.
Bridge. APIs secured. But secrets are the keys to everything. → 06