一键导入
api-gateway-patterns
API Gateway design patterns including rate limiting, authentication, versioning, BFF and circuit breaking
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
API Gateway design patterns including rate limiting, authentication, versioning, BFF and circuit breaking
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
**Architecture Decision Record (ADR) — Philosophy-First**: Creates well-structured ADRs using a 3-phase process: (1) Define the architectural philosophy and identity of the system, (2) Explore options through the lens of that philosophy, (3) Adversarial review by a devil's advocate agent. Use this skill whenever the user wants to document a technical decision, create an ADR, record why a technology or approach was chosen, compare architectural alternatives, or mentions 'ADR', 'architecture decision', 'decision record', 'technical decision', 'why did we choose', or 'document this decision'. Also trigger when the user is evaluating trade-offs between technical approaches and wants to formalize the reasoning.
**AI/ML Engineering Review**: Reviews AI/ML systems for production readiness — model serving, MLOps pipelines, LLM integration patterns, prompt engineering, evaluation frameworks, and responsible AI. Covers model deployment, feature stores, experiment tracking, monitoring/drift detection, and AI safety. Use when the user mentions ML, AI, machine learning, model, LLM, GPT, Claude, embeddings, RAG, fine-tuning, MLOps, model serving, feature store, or any AI/ML infrastructure.
**API Documentation & Design (OpenAPI/Swagger)**: Helps write and review API documentation, generate OpenAPI/Swagger specs, design RESTful APIs, and document GraphQL schemas. Use whenever the user mentions 'API docs', 'Swagger', 'OpenAPI', 'API specification', 'API design', 'REST API', 'endpoint documentation', 'API contract', 'API versioning', 'GraphQL schema', 'API reference', or asks to document their API, generate a Swagger spec, design API endpoints, or review API contracts for consistency.
ARB process design, RFC governance, decision log and technical review workflows
**Backend Code Review (Node.js, Java, Microservices)**: Expert review of backend code focusing on Node.js, Java, Clean Architecture, SOLID principles, microservices patterns, SQL/database design, messaging (Kafka, SQS, SNS), and payment flows. Use whenever the user wants a review of backend code, API design, service architecture, database queries, or mentions Node, Java, Spring, NestJS, Express, microservices, REST API, gRPC, or asks to review server-side code. Also trigger for database schema reviews, query optimization, and message queue patterns.
**Chaos Engineering**: Designs and reviews resilience testing strategies — fault injection, game days, failure mode analysis, and blast radius assessment. Covers chaos experiments for distributed systems, database failures, network partitions, and dependency outages. Use when the user mentions chaos engineering, resilience testing, fault injection, game day, failure testing, blast radius, circuit breaker testing, or wants to verify system reliability under failure conditions.
| name | api-gateway-patterns |
| description | API Gateway design patterns including rate limiting, authentication, versioning, BFF and circuit breaking |
| triggers | {"frameworks":["kong","nginx","envoy","traefik","api-gateway"],"file-patterns":["**/gateway/**","**/proxy/**"]} |
| preferred-model | sonnet |
| min-confidence | 0.4 |
| depends-on | [] |
| category | architecture |
| estimated-tokens | 5000 |
| tags | ["api-gateway","rate-limiting","routing"] |
┌─────────────────────┐
│ API Gateway │
│ │
Clients ────────►│ 1. Rate Limiting │
│ 2. Authentication │
│ 3. Request Routing │
│ 4. Load Balancing │
│ 5. Circuit Breaking │
│ 6. Response Caching │
│ 7. Logging/Tracing │
└────┬────┬────┬──────┘
│ │ │
┌────┘ │ └────┐
▼ ▼ ▼
┌──────┐ ┌──────┐ ┌──────┐
│Svc A │ │Svc B │ │Svc C │
└──────┘ └──────┘ └──────┘
// Allows burst then throttles
const rateLimiter = {
bucketSize: 100, // Max tokens
refillRate: 10, // Tokens per second
refillInterval: 1000, // ms
};
// Burst: 100 requests instantly, then 10/sec sustained
// More accurate, no burst
// Count requests in last N seconds
// Redis implementation:
// ZADD rate:{userId} {timestamp} {requestId}
// ZREMRANGEBYSCORE rate:{userId} 0 {timestamp - window}
// ZCARD rate:{userId}
| Tier | Rate Limit | Burst |
|---|---|---|
| Free | 100 req/hour | 10 req/sec |
| Basic | 1000 req/hour | 50 req/sec |
| Pro | 10000 req/hour | 200 req/sec |
| Enterprise | Custom | Custom |
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 1619472000
Retry-After: 60
| Strategy | Example | Pros | Cons |
|---|---|---|---|
| URL path | /v1/users | Simple, clear | URL pollution |
| Header | Accept: application/vnd.api.v1+json | Clean URLs | Hidden, harder to test |
| Query param | /users?version=1 | Easy to switch | Messy |
Recommendation: URL path for public APIs, header for internal APIs.
v1: Active → Deprecated → Sunset
│ │ │
└──────────┘ │
6 months minimum │
communication │
└── Remove with 3-month warning
┌────────┐ ┌─────────────┐ ┌──────────┐
│ Mobile │────►│ Mobile BFF │────►│ │
│ App │ │ (optimized) │ │ │
└────────┘ └─────────────┘ │ Core │
│ Services │
┌────────┐ ┌─────────────┐ │ │
│ Web │────►│ Web BFF │────►│ │
│ App │ │ (full data) │ │ │
└────────┘ └─────────────┘ └──────────┘
Mobile BFF: Less data, compressed images, offline-first
Web BFF: Full data, SSR support, WebSocket
enum CircuitState { CLOSED, OPEN, HALF_OPEN }
class CircuitBreaker {
private state = CircuitState.CLOSED;
private failureCount = 0;
private successCount = 0;
private lastFailureTime: Date;
private readonly threshold = 5; // Failures to open
private readonly timeout = 30000; // ms before half-open
private readonly halfOpenMax = 3; // Successes to close
async execute<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === CircuitState.OPEN) {
if (Date.now() - this.lastFailureTime.getTime() > this.timeout) {
this.state = CircuitState.HALF_OPEN;
} else {
throw new Error('Circuit is OPEN — service unavailable');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
private onSuccess() {
if (this.state === CircuitState.HALF_OPEN) {
this.successCount++;
if (this.successCount >= this.halfOpenMax) {
this.state = CircuitState.CLOSED;
this.failureCount = 0;
}
}
this.failureCount = 0;
}
private onFailure() {
this.failureCount++;
this.lastFailureTime = new Date();
if (this.failureCount >= this.threshold) {
this.state = CircuitState.OPEN;
}
}
}
// Gateway aggregation — single client call, multiple services
@Get('dashboard')
async getDashboard(@User() user) {
const [profile, stats, notifications] = await Promise.allSettled([
this.userService.getProfile(user.id),
this.billingService.getStats(user.companyId),
this.notificationService.getUnread(user.id),
]);
return {
profile: profile.status === 'fulfilled' ? profile.value : null,
stats: stats.status === 'fulfilled' ? stats.value : null,
notifications: notifications.status === 'fulfilled' ? notifications.value : [],
};
// Graceful degradation: partial response even if one service fails
}