Complete Quick Reference and Common Mistakes for remaining 5 skills

Added comprehensive Quick Reference tables and Common Mistakes sections to:

- api-gateway-advanced: Traefik patterns, API composition, middleware order
- api-versioning-strategy: Versioning strategies, deprecation lifecycle, headers
- infrastructure-as-code: Terraform commands, GitOps workflow, module structure
- microservices-development-process: Phase overview, quick commands, file structure
- service-discovery-registry: K8s DNS patterns, health checks, load balancing

All 26 skills now have:
- Quick Reference tables for fast lookup
- Common Mistakes with BAD/GOOD code examples
- Practical patterns and essential imports

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Ho Ngoc Hai
2026-01-01 11:09:13 +07:00
parent a0dda79478
commit 5d60403488
5 changed files with 455 additions and 0 deletions

View File

@@ -419,6 +419,99 @@ export function gatewayCache(ttl: number = 60) {
5. **Versioning**: Use path-based or header-based versioning
6. **Monitoring**: Monitor gateway metrics (latency, error rate)
## Common Mistakes
1. **No Timeout at Gateway**: Requests hanging forever
```yaml
# ❌ BAD: No timeout
services:
my-service:
loadBalancer: ...
# ✅ GOOD: Set timeout
middlewares:
timeout:
forwardingTimeouts:
dialTimeout: 5s
responseHeaderTimeout: 10s
```
2. **Missing Circuit Breaker**: Cascading failures
```yaml
# ✅ Add circuit breaker for each service
middlewares:
circuit-breaker:
circuitBreaker:
expression: "NetworkErrorRatio() > 0.50"
```
3. **No Caching for Static Data**: Unnecessary service load
```typescript
// ❌ BAD: Every request hits service
app.get('/api/config', handler);
// ✅ GOOD: Cache at gateway
app.get('/api/config', gatewayCache(3600), handler);
```
4. **N+1 API Calls from Client**: Multiple round trips
```typescript
// ❌ BAD: Client makes 3 calls
GET /users/123
GET /orders?userId=123
GET /payments?userId=123
// ✅ GOOD: Use API composition
GET /user-profile/123 // Aggregated response
```
## Quick Reference
| Pattern | Use Case | Implementation |
|---------|----------|----------------|
| **API Composition** | Aggregate multiple services | Promise.all() |
| **Request Transform** | Modify incoming requests | Middleware |
| **Response Transform** | Standardize responses | Override res.json |
| **Gateway Caching** | Cache GET responses | Redis/Memory |
| **Circuit Breaker** | Protect from failures | Traefik middleware |
**Traefik Middleware Order:**
```
1. Rate Limiting
2. Authentication
3. Circuit Breaker
4. Retry
5. Headers Transform
6. Compression
```
**API Composition Patterns:**
```typescript
// Fan-out (parallel)
const [users, orders] = await Promise.all([
userClient.get('/users'),
orderClient.get('/orders')
]);
// Chaining (sequential)
const order = await orderClient.create(data);
const payment = await paymentClient.process(order.id);
```
**Gateway Config Template:**
```yaml
http:
routers:
service-route:
rule: "PathPrefix(`/api/v1/service`)"
middlewares: [rate-limit, auth, circuit-breaker]
service: backend-service
middlewares:
circuit-breaker:
circuitBreaker:
expression: "NetworkErrorRatio() > 0.5"
```
## Resources
- [Traefik Documentation](https://doc.traefik.io/traefik/) - Official Traefik docs

View File

@@ -351,6 +351,87 @@ export class MigrationStrategy {
5. **Backward Compatibility**: Maintain compatibility when possible
6. **Communication**: Clearly communicate version changes
## Common Mistakes
1. **No Deprecation Period**: Breaking clients suddenly
```typescript
// ❌ BAD: Remove v1 immediately
router.use('/v2', v2Router);
// ✅ GOOD: Deprecate with sunset date
router.use('/v1', deprecationMiddleware('2', '2024-12-31'), v1Router);
router.use('/v2', v2Router);
```
2. **Breaking Changes Without Major Version**: Client confusion
```
# ❌ BAD: Breaking change in minor version
v1.1.0 → Changed response format
# ✅ GOOD: Breaking change = new major version
v1.x.x → v2.0.0 (new response format)
```
3. **Inconsistent Versioning Strategy**: Mixed approaches
```typescript
// ❌ BAD: Mix URL and header versioning
/api/v1/users + Accept: application/vnd.v2+json
// ✅ GOOD: Choose one approach
/api/v1/users OR Accept: application/vnd.goodgo.v1+json
```
4. **No Migration Guide**: Clients don't know how to upgrade
```
# ✅ Always provide:
- Changelog
- Migration guide
- Sunset date
- Deprecation warnings
```
## Quick Reference
| Strategy | Pros | Cons | Use When |
|----------|------|------|----------|
| **URL Path** | Clear, cacheable | URL changes | Public APIs |
| **Header** | Clean URLs | Less visible | Internal APIs |
| **Query Param** | Simple | Not RESTful | Quick prototypes |
**Semantic Versioning:**
```
MAJOR.MINOR.PATCH
│ │ └── Bug fixes (backward compatible)
│ └──────── New features (backward compatible)
└────────────── Breaking changes
```
**Version Lifecycle:**
```
v1 Active → v2 Released → v1 Deprecated → v1 Sunset → v1 Removed
│ │ │ │ │
│ │ Add headers Remove from Delete
│ Support + warnings docs routes
Solo both
```
**Deprecation Headers:**
```http
Deprecation: true
Sunset: Sat, 31 Dec 2024 23:59:59 GMT
Warning: 299 - "API v1 is deprecated. Migrate to v2 by 2024-12-31"
Link: </api/v2/users>; rel="successor-version"
```
**Version Detection:**
```typescript
// URL path
const version = req.path.match(/\/v(\d+)\//)?.[1] || '2';
// Header
const version = req.headers.accept?.match(/vnd\.goodgo\.v(\d+)/)?.[1];
```
## Resources
- [API Design](../api-design/SKILL.md) - API design patterns

View File

@@ -310,6 +310,104 @@ spec:
6. **State Management**: Use remote state backends
7. **Secrets**: Never commit secrets, use secrets managers
## Common Mistakes
1. **Committing Secrets**: Exposed credentials
```hcl
# ❌ BAD: Hardcoded secrets
password = "my-secret-password"
# ✅ GOOD: Use variables + secrets manager
password = var.db_password # From env or secrets manager
```
2. **No Remote State**: State conflicts in team
```hcl
# ❌ BAD: Local state
# (no backend config)
# ✅ GOOD: Remote state
terraform {
backend "s3" {
bucket = "terraform-state"
key = "staging/terraform.tfstate"
}
}
```
3. **No State Locking**: Concurrent modifications
```hcl
# ✅ Enable state locking
backend "s3" {
dynamodb_table = "terraform-locks"
}
```
4. **Applying Without Plan Review**: Unexpected changes
```bash
# ❌ BAD: Direct apply
terraform apply
# ✅ GOOD: Plan first, review, then apply
terraform plan -out=tfplan
terraform show tfplan # Review
terraform apply tfplan
```
## Quick Reference
| Tool | Purpose | State |
|------|---------|-------|
| **Terraform** | Cloud resources | Stateful |
| **Kubernetes** | Container orchestration | Declarative |
| **Helm** | K8s package manager | Template |
| **ArgoCD/Flux** | GitOps deployment | Git-synced |
**Terraform Commands:**
```bash
terraform init # Initialize
terraform validate # Validate syntax
terraform plan # Preview changes
terraform apply # Apply changes
terraform destroy # Remove resources
terraform state list # List state resources
```
**Module Structure:**
```
modules/service/
├── main.tf # Resources
├── variables.tf # Input variables
├── outputs.tf # Output values
└── README.md # Documentation
```
**Environment Pattern:**
```
environments/
├── staging/
│ ├── main.tf
│ └── terraform.tfvars
└── production/
├── main.tf
└── terraform.tfvars
```
**GitOps Workflow:**
```
Git Push → CI Validates → ArgoCD Syncs → K8s Applied
Auto-heal if drift
```
**Best Practices Checklist:**
- [ ] Remote state backend configured
- [ ] State locking enabled
- [ ] No secrets in code
- [ ] Modules for reusable components
- [ ] Environment-specific tfvars
- [ ] PR review for all changes
## Resources
- [Terraform Documentation](https://www.terraform.io/docs)

View File

@@ -643,6 +643,95 @@ kubectl rollout status deployment/service-name -n staging
5. **Poor Documentation**: Makes maintenance difficult
6. **No Rollback Plan**: Difficult to recover from failures
## Common Mistakes
1. **Skipping Impact Analysis**: Missing file updates
```bash
# ❌ BAD: Start coding immediately
# ✅ GOOD: Complete impact analysis first
# Check all files that need updates:
grep -r "service-name" . --exclude-dir=node_modules
```
2. **No Phase Verification**: Accumulated issues
```bash
# ❌ BAD: Skip to next phase without verification
# ✅ GOOD: Complete phase checklist before moving on
pnpm typecheck && pnpm lint && pnpm test
```
3. **Deferred Documentation**: Forgotten details
```markdown
# ❌ BAD: "I'll document later"
# ✅ GOOD: Document as you implement each feature
```
4. **Missing Rollback Plan**: No recovery option
```bash
# ✅ Always prepare:
- Database backup
- Previous image tag
- Rollback commands ready
```
5. **Incomplete Cleanup**: Leftover temporary files
```bash
# ❌ BAD: Leave backup files
# ✅ GOOD: Remove all temporary files
rm -rf *.backup/ *_STATUS.md *_CHECKLIST.md
```
## Quick Reference
| Phase | Key Deliverable | Verification |
|-------|-----------------|--------------|
| **1. Planning** | Impact analysis | Dependencies mapped |
| **2. Foundation** | Service starts | Health check passes |
| **3. Implementation** | Business logic | TypeScript compiles |
| **4. Integration** | Routes working | API accessible |
| **5. Testing** | Tests pass | Coverage >70% |
| **6. Documentation** | README complete | Swagger works |
| **7. Cleanup** | No temp files | All refs updated |
| **8. Deployment** | Service deployed | Production verified |
**Quick Commands:**
```bash
# Start from template
cp -r services/_template services/new-service
# Development workflow
pnpm dev # Start service
pnpm typecheck # Type check
pnpm lint # Lint check
pnpm test # Run tests
pnpm test:coverage # Coverage report
pnpm build # Build for prod
# Database
pnpm prisma migrate dev # Create migration
pnpm prisma generate # Generate client
# Docker
docker build -t service . # Build image
docker-compose up service # Run with dependencies
```
**Module Implementation Order:**
```
1. DTOs (Zod) → 2. Repository → 3. Service → 4. Controller → 5. Module
```
**File Structure:**
```
modules/feature/
├── feature.dto.ts # Zod schemas
├── feature.repository.ts # Data access
├── feature.service.ts # Business logic
├── feature.controller.ts # HTTP handlers
├── feature.module.ts # Wiring
└── index.ts # Exports
```
## Resources
- [Project Rules](../project-rules/SKILL.md) - Architecture and conventions

View File

@@ -420,6 +420,100 @@ spec:
4. **Load Balancing**: Use appropriate load balancing strategy
5. **Monitoring**: Monitor service discovery and health
## Common Mistakes
1. **Hardcoded Service URLs**: Breaks in different environments
```typescript
// ❌ BAD: Hardcoded
const url = 'http://user-service:5000';
// ✅ GOOD: Use discovery or env vars
const url = discovery.getServiceUrl('user-service');
// OR
const url = process.env.USER_SERVICE_URL;
```
2. **No Heartbeat**: Stale registry entries
```typescript
// ❌ BAD: Register once
await registry.register(service);
// ✅ GOOD: Periodic heartbeat
setInterval(() => registry.register(service), 30000);
```
3. **Missing Graceful Shutdown**: Orphaned registrations
```typescript
// ✅ Always unregister on shutdown
process.on('SIGTERM', async () => {
await registry.unregister(serviceName);
process.exit(0);
});
```
4. **No Fallback**: Fails when registry unavailable
```typescript
// ❌ BAD: No fallback
const url = await registry.discover('service');
// ✅ GOOD: Fallback to default
const url = await registry.discover('service')
?? process.env.SERVICE_FALLBACK_URL;
```
## Quick Reference
| Discovery Type | Implementation | Use Case |
|----------------|----------------|----------|
| **K8s DNS** | `service.namespace.svc.cluster.local` | Internal services |
| **Service Registry** | Database-backed | Dynamic services |
| **Service Mesh** | Istio/Linkerd | Complex routing |
| **Environment Vars** | `process.env.SERVICE_URL` | Simple/external |
**Kubernetes DNS Patterns:**
```
# Short (same namespace)
http://user-service
# Full (cross-namespace)
http://user-service.production.svc.cluster.local
# With port
http://user-service.production.svc.cluster.local:5000
```
**Health Check Endpoints:**
| Endpoint | Purpose |
|----------|---------|
| `/health` | Basic health |
| `/health/live` | K8s liveness probe |
| `/health/ready` | K8s readiness probe |
**Load Balancing Strategies:**
| Strategy | When to Use |
|----------|-------------|
| **Round Robin** | Equal capacity servers |
| **Least Connections** | Varying request durations |
| **Weighted** | Different server capacities |
**Service Registration Lifecycle:**
```
Startup → Register → Heartbeat (30s) → ... → Shutdown → Unregister
```
**Essential Code:**
```typescript
// Discovery
const url = `http://${serviceName}.${namespace}.svc.cluster.local`;
// Registry check
const service = await registry.discover('user-service');
if (service?.status === 'healthy') { /* use service */ }
// Heartbeat
setInterval(() => registry.register({ ...info, lastHeartbeat: new Date() }), 30000);
```
## Resources
- [Kubernetes Service Discovery](https://kubernetes.io/docs/concepts/services-networking/service/)