Skill — API Gateway Patterns
When this skill activates
Any task involving API gateway configuration, gateway rate limiting, request
routing, authentication offloading, BFF patterns, or gateway-level caching.
Mandatory actions when this skill is active
Before writing any code
- Identify which cross-cutting concerns belong at the gateway vs service level.
- Define rate limiting strategy (algorithm, limits, granularity).
- Determine if BFF pattern is needed (multiple client types).
During implementation
- Keep gateway logic stateless (no session state in gateway).
- Implement circuit breakers per downstream service.
- Add request correlation IDs at the gateway for distributed tracing.
After implementation
- Load test rate limiting configuration.
- Verify circuit breaker thresholds with failure injection.
- Document gateway routing rules in ARCHITECTURE.md.
Rate Limiting Algorithms
Token Bucket
- Bucket holds N tokens, refills at constant rate.
- Each request consumes one token.
- Allows bursts up to bucket capacity.
- Best for: APIs that need burst tolerance.
Sliding Window
- Count requests in rolling time window.
- Smoother than fixed window (no boundary burst issue).
- Best for: strict per-second/minute rate enforcement.
Fixed Window
- Count requests per calendar interval (e.g., per minute).
- Simple to implement, but allows 2x burst at window boundary.
- Best for: simple use cases where boundary bursts are acceptable.
Rate Limit Granularity
- Per-user: fairest, prevents one user from affecting others.
- Per-IP: catches unauthenticated abuse, but shared IPs cause issues.
- Per-endpoint: different limits for reads vs writes.
- Per-plan: higher limits for premium tier customers.
Response Headers
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 847
X-RateLimit-Reset: 1623456789
Retry-After: 30
Authentication Offloading
Pattern
- Client sends request with auth token to gateway.
- Gateway validates JWT signature and expiration.
- Gateway extracts claims (user_id, roles, permissions).
- Gateway passes claims as trusted headers to downstream services.
- Downstream services trust headers (internal network only).
Benefits
- Auth logic in one place, not duplicated across services.
- Downstream services are simpler (no JWT library needed).
- Token refresh/rotation handled centrally.
Security Considerations
- Strip incoming trust headers from external requests (prevent spoofing).
- Internal services MUST reject requests without gateway headers.
- Gateway must validate token on every request (no caching of auth decisions).
Backend for Frontend (BFF)
Pattern
- One gateway per client type: web, mobile, third-party.
- Each BFF tailored to client needs (field selection, aggregation).
- Mobile BFF: fewer fields, compressed responses, batch endpoints.
- Web BFF: full responses, pagination, real-time subscriptions.
- Third-party BFF: stable API, versioned, rate-limited.
When to Use BFF
- Different clients need different data shapes.
- Mobile clients need response optimization (bandwidth).
- Third-party API needs different auth and rate limiting.
Request Aggregation
Pattern
- Client sends one request to gateway.
- Gateway fans out to multiple backend services.
- Gateway combines responses into single response.
- Returns aggregated result to client.
Best Practices
- Set timeout per downstream call (don't wait forever).
- Return partial results if some backends fail (degrade gracefully).
- Cache individual backend responses independently.
- Use async/parallel calls to backends (not sequential).
Circuit Breaking (Per-Route)
States
- Closed: requests flow normally, failures counted.
- Open: requests immediately fail (503), no backend calls.
- Half-Open: allow one probe request to test recovery.
Configuration Per Downstream
payment-service:
failure_threshold: 5 # failures before opening
timeout: 10s # time in open state before half-open
success_threshold: 3 # successes in half-open to close
inventory-service:
failure_threshold: 10
timeout: 30s
success_threshold: 5
Fallback Strategies
- Return cached response (stale but functional).
- Return default/empty response with degraded flag.
- Route to alternative backend (failover service).
Gateway Caching
What to Cache
- GET responses with stable data (product catalog, configuration).
- Use ETag/Last-Modified for conditional requests.
- Cache per-user or per-role (never cache authenticated data globally).
What NOT to Cache
- POST/PUT/DELETE responses.
- Responses with
Cache-Control: no-store.
- Responses containing PII without per-user isolation.
Cache Invalidation at Gateway
- TTL-based (simple, eventual consistency).
- Purge API (explicit invalidation from backend on mutation).
- Surrogate keys (tag responses, purge by tag).
Response Transformation
Appropriate at Gateway
- Field filtering (client requests specific fields).
- Pagination wrapping (add metadata to list responses).
- Format conversion (JSON to XML for legacy clients).
- Header manipulation (add CORS, security headers).
NOT Appropriate at Gateway
- Business logic transformation.
- Data enrichment from other services.
- Complex aggregation with business rules.
Self-check before task completion
Before marking a task done when this skill was active:
1---2name: api-gateway-patterns3description: Skill — API Gateway Patterns4---56# Skill — API Gateway Patterns78## When this skill activates9Any task involving API gateway configuration, gateway rate limiting, request10routing, authentication offloading, BFF patterns, or gateway-level caching.1112## Mandatory actions when this skill is active1314### Before writing any code151. Identify which cross-cutting concerns belong at the gateway vs service level.162. Define rate limiting strategy (algorithm, limits, granularity).173. Determine if BFF pattern is needed (multiple client types).1819### During implementation20- Keep gateway logic stateless (no session state in gateway).21- Implement circuit breakers per downstream service.22- Add request correlation IDs at the gateway for distributed tracing.2324### After implementation25- Load test rate limiting configuration.26- Verify circuit breaker thresholds with failure injection.27- Document gateway routing rules in ARCHITECTURE.md.2829## Rate Limiting Algorithms3031### Token Bucket32- Bucket holds N tokens, refills at constant rate.33- Each request consumes one token.34- Allows bursts up to bucket capacity.35- Best for: APIs that need burst tolerance.3637### Sliding Window38- Count requests in rolling time window.39- Smoother than fixed window (no boundary burst issue).40- Best for: strict per-second/minute rate enforcement.4142### Fixed Window43- Count requests per calendar interval (e.g., per minute).44- Simple to implement, but allows 2x burst at window boundary.45- Best for: simple use cases where boundary bursts are acceptable.4647### Rate Limit Granularity48- **Per-user**: fairest, prevents one user from affecting others.49- **Per-IP**: catches unauthenticated abuse, but shared IPs cause issues.50- **Per-endpoint**: different limits for reads vs writes.51- **Per-plan**: higher limits for premium tier customers.5253### Response Headers54```55X-RateLimit-Limit: 100056X-RateLimit-Remaining: 84757X-RateLimit-Reset: 162345678958Retry-After: 3059```6061## Authentication Offloading6263### Pattern641. Client sends request with auth token to gateway.652. Gateway validates JWT signature and expiration.663. Gateway extracts claims (user_id, roles, permissions).674. Gateway passes claims as trusted headers to downstream services.685. Downstream services trust headers (internal network only).6970### Benefits71- Auth logic in one place, not duplicated across services.72- Downstream services are simpler (no JWT library needed).73- Token refresh/rotation handled centrally.7475### Security Considerations76- Strip incoming trust headers from external requests (prevent spoofing).77- Internal services MUST reject requests without gateway headers.78- Gateway must validate token on every request (no caching of auth decisions).7980## Backend for Frontend (BFF)8182### Pattern83- One gateway per client type: web, mobile, third-party.84- Each BFF tailored to client needs (field selection, aggregation).85- Mobile BFF: fewer fields, compressed responses, batch endpoints.86- Web BFF: full responses, pagination, real-time subscriptions.87- Third-party BFF: stable API, versioned, rate-limited.8889### When to Use BFF90- Different clients need different data shapes.91- Mobile clients need response optimization (bandwidth).92- Third-party API needs different auth and rate limiting.9394## Request Aggregation9596### Pattern97- Client sends one request to gateway.98- Gateway fans out to multiple backend services.99- Gateway combines responses into single response.100- Returns aggregated result to client.101102### Best Practices103- Set timeout per downstream call (don't wait forever).104- Return partial results if some backends fail (degrade gracefully).105- Cache individual backend responses independently.106- Use async/parallel calls to backends (not sequential).107108## Circuit Breaking (Per-Route)109110### States111- **Closed**: requests flow normally, failures counted.112- **Open**: requests immediately fail (503), no backend calls.113- **Half-Open**: allow one probe request to test recovery.114115### Configuration Per Downstream116```yaml117payment-service:118 failure_threshold: 5 # failures before opening119 timeout: 10s # time in open state before half-open120 success_threshold: 3 # successes in half-open to close121122inventory-service:123 failure_threshold: 10124 timeout: 30s125 success_threshold: 5126```127128### Fallback Strategies129- Return cached response (stale but functional).130- Return default/empty response with degraded flag.131- Route to alternative backend (failover service).132133## Gateway Caching134135### What to Cache136- GET responses with stable data (product catalog, configuration).137- Use ETag/Last-Modified for conditional requests.138- Cache per-user or per-role (never cache authenticated data globally).139140### What NOT to Cache141- POST/PUT/DELETE responses.142- Responses with `Cache-Control: no-store`.143- Responses containing PII without per-user isolation.144145### Cache Invalidation at Gateway146- TTL-based (simple, eventual consistency).147- Purge API (explicit invalidation from backend on mutation).148- Surrogate keys (tag responses, purge by tag).149150## Response Transformation151152### Appropriate at Gateway153- Field filtering (client requests specific fields).154- Pagination wrapping (add metadata to list responses).155- Format conversion (JSON to XML for legacy clients).156- Header manipulation (add CORS, security headers).157158### NOT Appropriate at Gateway159- Business logic transformation.160- Data enrichment from other services.161- Complex aggregation with business rules.162163## Self-check before task completion164165Before marking a task done when this skill was active:166167- [ ] Did I read the full SKILL.md before starting? (Not just the triggers)168- [ ] Is gateway logic stateless?169- [ ] Are rate limits per-user (not just per-IP)?170- [ ] Are circuit breakers configured per downstream service?171- [ ] Is auth offloading stripping external trust headers?172- [ ] Is business logic kept out of the gateway?173- [ ] Are request correlation IDs generated at the gateway?