When you provide an API for external customers, you need a way to track their usage and ensure they don't abuse your infrastructure. API Keys and Rate Limiting are your primary defenses.
An API key should be treated like a password. - **Encryption:** Never store keys in plain text in your DB. - **Rotation:** Provide a way for users to 'Roll' their key if it's compromised. - **Metadata:** Attach the key to a specific 'Plan' (Free vs Pro) to automatically apply different limits.
Use the **Token Bucket** algorithm. Give a user 1,000 tokens per hour. Every API call costs 1 token. This allows for 'Bursts' of activity but prevents sustained high-volume attacks that could crash your database.
Q: "Where should Rate Limiting happen in a microservices architecture?"
Architect Answer: "At the **API Gateway**. Doing it at the gateway protects your internal services from ever receiving the malicious traffic. It also centralizes the logic so you don't have to implement Rate Limiting code in every single microservice. For extra defense, we also use **WAF (Web Application Firewall)** at the DNS level to block IP-based DDoS attacks before they even hit our gateway."