API GatewayDDoSEncryptionTLSWAFDefense in DepthSecurity

Protection

Secure systems from unauthorized access and attacks — API gateway authentication, DDoS mitigation, and data encryption at rest and in transit. Defense-in-depth for production systems.

24 min read9 sections
01

The Big Picture — Why Security Is Layered

No single security measure is enough. A firewall doesn't stop SQL injection. Encryption doesn't prevent DDoS. Auth tokens don't protect against data breaches if the database is unencrypted. Security works in layers — each layer catches what the previous one missed.

✈️

The Airport Security Analogy

An airport doesn't rely on a single checkpoint. Layer 1: ID check at the entrance (authentication — are you who you claim to be?). Layer 2: security screening (gateway filtering — is your request safe?). Layer 3: locked luggage in the cargo hold (encryption at rest — data is protected even if someone accesses the storage). Layer 4: sealed cabin during flight (encryption in transit — data is protected while moving). If any single layer fails, the others still protect. That's defense-in-depth.

🔥 Key Insight

Security is not a feature you add at the end. It's a property of the architecture. Every layer — edge, gateway, application, database — has a security role. A breach at any layer should not compromise the entire system.

02

Defense-in-Depth Architecture

Security Layers — From Edge to Databasetext
ClientCDN/WAFAPI GatewayApplicationDatabase

Layer 1Edge (CDN / WAF):
DDoS protection (absorb volumetric attacks)
WAF rules (block SQL injection, XSS patterns)
IP filtering (block known malicious IPs)
Rate limiting (per IP, per region)

Layer 2API Gateway:
Authentication (validate JWT / API key)
Authorization (check permissions for this endpoint)
Request validation (schema, size limits, content type)
Rate limiting (per user / per API key)

Layer 3Application:
Input sanitization (prevent injection attacks)
Business logic authorization (can this user access this resource?)
Audit logging (who did what, when)
CORS enforcement

Layer 4Database / Storage:
Encryption at rest (AES-256)
Access control (least privilege, no public access)
Encrypted backups
Network isolation (private subnet, no public IP)

🌐 Perimeter Security

  • CDN absorbs DDoS traffic before it reaches your servers
  • WAF blocks known attack patterns (OWASP Top 10)
  • API Gateway enforces auth on every request
  • Goal: stop bad traffic before it reaches your application

🔒 Internal Security

  • Application validates and sanitizes all input
  • Database encrypted at rest (even if disk is stolen)
  • Service-to-service communication over TLS (mTLS)
  • Goal: limit damage if perimeter is breached
03

API Gateway Auth & Enforcement

The API gateway is the front door of your system. Every request passes through it. It's the ideal place to enforce authentication, rate limiting, and request validation — before the request ever reaches your application code.

API Gateway — What It Enforcestext
Incoming request:
  POST /api/orders
  Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
  Content-Type: application/json
  Body: { "product_id": 42, "quantity": 2 }

Gateway checks (in order):

1. AUTHENTICATIONIs the token valid?
Decode JWTverify signaturecheck expiration
Invalid? → 401 Unauthorized (request rejected)

2. RATE LIMITINGIs this user within their quota?
Check: user-42 has made 95/100 requests this minute
Over limit? → 429 Too Many Requests
Under limit? → increment counter, proceed

3. REQUEST VALIDATIONIs the request well-formed?
Content-Type must be application/json
Body must match schema (product_id: integer, quantity: integer > 0)
Body size < 1 MB
Invalid? → 400 Bad Request

4. AUTHORIZATIONDoes this user have permission?
User role: "customer"can access POST /api/orders
User role: "customer"cannot access DELETE /api/admin/* ❌ → 403

5. ROUTING — Forward to the correct backend service
   → /api/orders → Order Service
   → /api/products → Product Service

All checks pass → forward request to backend service
Any check fails → return error, backend never sees the request

Benefits

  • Centralized security — one place for all auth logic
  • Backend services don't implement auth individually
  • Rate limiting protects all services uniformly
  • Request validation catches bad input before it reaches business logic
  • Single audit log for all API access

Considerations

  • Gateway is a single point of failure (must be highly available)
  • Added latency (~1-5ms per request for auth checks)
  • Gateway must be updated when auth rules change
  • Complex gateway config can become hard to manage
  • Don't put business logic in the gateway — only security and routing

🎯 Interview Insight

Always put authentication at the gateway layer. Say: "Every request passes through the API gateway, which validates the JWT, checks rate limits, and validates the request schema. Backend services trust that requests from the gateway are authenticated. This centralizes security and keeps backend services simple."

04

DDoS Mitigation

A DDoS (Distributed Denial of Service) attack floods your system with traffic from thousands of sources, overwhelming your servers until legitimate users can't access the service. You can't block a single IP — the traffic comes from everywhere.

DDoS Attack — What Happenstext
Normal traffic: 10,000 requests/secservers handle it fine

DDoS attack: 10,000,000 requests/sec from 50,000 IPs
Servers overwhelmedCPU 100% → memory exhausted
Legitimate users get timeouts"site is down"
Attack costs the attacker $50/hour (botnet rental)
Downtime costs you $50,000/hour (lost revenue + reputation)

Defense layers:

Layer 1CDN / Edge (Cloudflare, AWS Shield):
Absorbs volumetric attacks at the edge (Tbps capacity)
Filters known bot traffic patterns
Geo-blocking (block traffic from regions you don't serve)
95% of attack traffic never reaches your servers

Layer 2API Gateway:
Rate limiting per IP: 100 requests/minute
Rate limiting per user: 1000 requests/minute
Block IPs that exceed thresholds
Challenge suspicious traffic (CAPTCHA)

Layer 3Application:
Connection limits per client
Request timeout (kill slow requests)
Circuit breaker (stop calling overwhelmed downstream services)
Graceful degradation (serve cached content when under attack)
🚦

Rate Limiting

Cap requests per IP, per user, per API key. Excess requests get 429 Too Many Requests. Prevents any single source from overwhelming the system.

🧹

Traffic Scrubbing

CDN providers analyze traffic patterns and filter out bot traffic. Legitimate requests pass through; attack traffic is dropped at the edge before reaching your infrastructure.

🛡️

CDN Shielding

CDN edge servers absorb the attack volume. Your origin servers see only legitimate traffic. Cloudflare can absorb 100+ Tbps — more than any single attack.

🎯 Interview Insight

DDoS must be handled at the edge, not at the application level. By the time attack traffic reaches your servers, it's too late. Say: "I'd use a CDN with DDoS protection (Cloudflare, AWS Shield) as the first layer. Rate limiting at the API gateway as the second layer. Application-level circuit breakers as the last resort."

05

Data Encryption (At Rest & In Transit)

Encryption In Transit — Protecting Data on the Wire

Encryption In Transit — TLS/HTTPStext
Without encryption (HTTP):
  Client"password=hunter2" → [anyone on the network can read this] → Server
WiFi sniffing, ISP monitoring, man-in-the-middle attacks

With encryption (HTTPS / TLS):
  Client → [encrypted blob] → [unreadable to anyone in between] → Server
Only the client and server can read the data

What TLS protects:
Confidentialitydata is encrypted (can't be read)
Integritydata can't be modified in transit
Authenticationyou're talking to the real server (certificate)

Where to use TLS:
ClientServer: HTTPS (mandatory for any public API)
ServiceService: mTLS (mutual TLS, both sides verify)
ServiceDatabase: TLS connection (encrypt DB traffic)
Everywhere. There is no reason to use unencrypted connections.

Encryption At Rest — Protecting Stored Data

Encryption At Rest — AES-256text
Without encryption at rest:
  Database disk is stolen / accessed by unauthorized person
All data is readable in plain text
Passwords, credit cards, personal infoall exposed

With encryption at rest:
  Database disk is stolen / accessed
Data is encrypted with AES-256
Without the encryption key, data is unreadable gibberish

What to encrypt:
Database storage (PostgreSQL: pgcrypto, RDS encryption)
Object storage (S3 server-side encryption: SSE-S3, SSE-KMS)
Backups (encrypted backupsif backup is stolen, data is safe)
Sensitive fields (credit card numbers, SSNapplication-level encryption)

Key management:
Keys stored in a Key Management Service (AWS KMS, HashiCorp Vault)
Keys rotated periodically (every 90 days)
Access to keys is audited and restricted
NEVER store encryption keys in code or config files

🔒 In Transit (TLS)

  • Protects data while it moves across the network
  • HTTPS for client-server, mTLS for service-to-service
  • Prevents eavesdropping and man-in-the-middle attacks
  • Performance cost: ~1-2ms for TLS handshake (negligible)

💾 At Rest (AES-256)

  • Protects data while it sits on disk
  • Database encryption, S3 encryption, backup encryption
  • Prevents data exposure if storage is compromised
  • Performance cost: ~1-5% CPU overhead (transparent to app)

🎯 Interview Insight

Both are mandatory in production. Say: "All communication uses TLS — client-to-server (HTTPS), service-to-service (mTLS), and service-to-database. All storage is encrypted at rest — database, S3, backups. Keys are managed in KMS with automatic rotation. This protects against both network interception and physical storage compromise."

06

End-to-End Scenario

Let's design the security architecture for a public API serving a fintech application — where every layer matters.

🏦 Fintech API — Public-Facing, Sensitive Data

Handles: account balances, transactions, personal info.

Requirements: zero unauthorized access, survive DDoS, encrypt everything.

1

Edge — CDN + WAF (Cloudflare)

All traffic enters through Cloudflare. DDoS attacks are absorbed at the edge (Tbps capacity). WAF rules block SQL injection, XSS, and known attack patterns. Geo-blocking restricts access to supported countries. Bot detection challenges suspicious traffic with CAPTCHA. 95% of malicious traffic is stopped here.

2

API Gateway — Auth + Rate Limiting

Every request must include a valid JWT (issued by our auth service). Gateway validates the JWT signature, checks expiration, extracts user_id and roles. Rate limiting: 100 requests/minute per user, 1000/minute per API key. Request validation: schema check, size limits. Invalid requests → 401/400/429. Backend never sees unauthenticated traffic.

3

Application — Business Logic Security

Even with gateway auth, the application enforces authorization: 'Can user-42 access account-99?' (ownership check). Input sanitization: parameterized queries (prevent SQL injection). Audit logging: every sensitive operation is logged (who, what, when, from where). CORS: only allow requests from our frontend domain.

4

Database — Encryption + Access Control

PostgreSQL with encryption at rest (AES-256 via RDS). TLS for all database connections (no unencrypted traffic). Sensitive fields (SSN, account numbers) additionally encrypted at the application level with per-user keys. Database in a private subnet — no public IP, accessible only from application servers. Backups encrypted with KMS-managed keys.

Security Architecture — All Layerstext
Client (HTTPS)


CDN / WAF (Cloudflare)
DDoS absorption
WAF rules (OWASP Top 10)
Bot detection


API Gateway (Kong / AWS API Gateway)
JWT validation
Rate limiting (per user, per IP)
Request schema validation


Application (Node.js / Go)
Authorization (ownership checks)
Input sanitization
Audit logging
CORS enforcement

  ▼ (TLS)
Database (PostgreSQL, private subnet)
Encrypted at rest (AES-256)
Sensitive fields: app-level encryption
Access: application servers only
Backups: encrypted with KMS
07

Trade-offs & Decision Making

DimensionMore SecurityLess Security
LatencyHigher (auth checks, encryption overhead)Lower (no checks)
User experienceFriction (CAPTCHA, MFA, rate limits)Smoother (no barriers)
CostHigher (CDN, WAF, KMS, security team)Lower
RiskLower (multiple defense layers)Higher (single breach = full compromise)
ComplexityHigher (more systems to manage)Lower

Edge vs Application-Level Protection

ProtectionEdge (CDN/WAF)Application Level
DDoSEssential (absorb at edge)Too late (traffic already hit your servers)
SQL injectionWAF catches common patternsParameterized queries (definitive fix)
AuthenticationBasic (API key check)Full (JWT validation, role checks)
Rate limitingPer IP (coarse)Per user/API key (fine-grained)
Best forVolumetric attacks, known patternsBusiness logic, authorization, input validation

🎯 Decision Framework

Use edge protection for volumetric threats (DDoS, bot traffic). Use gateway for authentication and rate limiting. Use application for authorization and input validation. Use database encryption for data at rest. Every layer is necessary — they protect against different threat types.

08

Interview Questions

Q:What does an API gateway do for security?

A: The API gateway is the first line of defense for your application. It handles: (1) Authentication — validates JWT tokens or API keys on every request. Invalid tokens are rejected before reaching backend services. (2) Rate limiting — caps requests per user/IP to prevent abuse. (3) Request validation — checks schema, size limits, content type. (4) Routing — forwards valid requests to the correct backend service. The key benefit: backend services don't implement auth individually. Security is centralized, consistent, and auditable in one place.

Q:How do you mitigate DDoS attacks?

A: Layer 1 (Edge): Use a CDN with DDoS protection (Cloudflare, AWS Shield). The CDN absorbs volumetric attacks at the edge — your servers never see the attack traffic. Layer 2 (Gateway): Rate limiting per IP and per user. Block IPs that exceed thresholds. Challenge suspicious traffic with CAPTCHA. Layer 3 (Application): Connection limits, request timeouts, circuit breakers. Graceful degradation — serve cached content when under attack. The critical insight: DDoS must be stopped at the edge. By the time it reaches your servers, it's too late.

Q:What's the difference between encryption at rest and in transit?

A: In transit: data is encrypted while moving across the network (TLS/HTTPS). Protects against eavesdropping and man-in-the-middle attacks. If someone intercepts the traffic, they see encrypted gibberish. At rest: data is encrypted while stored on disk (AES-256). Protects against physical theft or unauthorized access to storage. If someone steals the database disk, they can't read the data without the encryption key. Both are mandatory in production — they protect against different threat vectors.

1

Your public API is getting 10x normal traffic from suspicious IPs

How do you respond?

Answer: Immediate: CDN/WAF auto-detects the spike and applies rate limiting at the edge. Suspicious IPs are challenged with CAPTCHA or blocked. Short-term: API gateway rate limits per IP are tightened. Alert on-call engineer. Analyze traffic patterns — is it a DDoS or a legitimate traffic spike? Medium-term: if DDoS, enable Cloudflare 'Under Attack' mode (all traffic gets a JS challenge). If legitimate, scale up backend capacity. Long-term: review rate limiting thresholds, add geo-blocking for regions you don't serve, implement bot detection.

2

A developer asks: 'Do we really need encryption at rest? Our database is in a private subnet.'

How do you respond?

Answer: Yes, encryption at rest is mandatory. A private subnet protects against network access — but not against: (1) a compromised application server that has DB credentials, (2) a stolen or decommissioned disk that wasn't wiped, (3) an insider with access to the infrastructure, (4) a backup stored in an insecure location. Encryption at rest ensures that even if someone gets physical access to the storage, the data is unreadable without the encryption key. The performance cost is ~1-5% CPU — negligible. For regulated industries (finance, healthcare), it's legally required.

09

Pitfalls

🚪

No gateway-level protection

Each microservice implements its own authentication. Service A validates JWT correctly. Service B has a bug and accepts expired tokens. Service C doesn't check auth at all. Inconsistent security across services — attackers find the weakest link.

Centralize authentication at the API gateway. All requests pass through the gateway, which validates tokens before forwarding. Backend services trust that requests from the gateway are authenticated. One place to update auth logic, one place to audit, one place to fix vulnerabilities.

🔓

Weak encryption practices

Using HTTP instead of HTTPS for internal services ('it's internal, nobody can see it'). Storing encryption keys in environment variables or config files. Using outdated TLS versions (TLS 1.0/1.1). Not encrypting database backups.

HTTPS everywhere — including internal services (use mTLS). Store keys in KMS (AWS KMS, HashiCorp Vault) — never in code or config. Enforce TLS 1.2+ (disable older versions). Encrypt all backups. Rotate keys every 90 days. Audit key access.

🌊

Ignoring DDoS risks

No CDN, no WAF, no rate limiting. The application server is directly exposed to the internet. A $50 botnet rental takes down your entire service for hours. Even a moderate traffic spike from a viral post overwhelms the server.

Put a CDN with DDoS protection in front of everything (Cloudflare free tier is a good start). Add rate limiting at the API gateway. Never expose application servers directly to the internet — always behind a load balancer and CDN. Plan for 10x traffic spikes.

🔑

Poor key management

Encryption keys hardcoded in source code. Same key used for all environments (dev, staging, prod). Keys never rotated. No audit trail of who accessed keys. If the key is compromised, all data encrypted with it is exposed.

Use a dedicated Key Management Service (KMS). Separate keys per environment. Rotate keys automatically (every 90 days). Audit all key access. Use envelope encryption: data encrypted with a data key, data key encrypted with a master key in KMS. If a data key is compromised, only that data is at risk — not everything.