Comprehensive Rules for building, operating, and scaling API Gateways in a micro-services architecture.
Your microservices are drowning in configuration drift, authentication complexity, and monitoring blind spots. Every service team is reinventing the wheel for cross-cutting concerns while your gateway configs live in production databases, deployment pipelines break on the smallest changes, and debugging distributed requests feels like archaeology.
You're dealing with multiple pain points that compound into serious productivity drains:
Configuration Chaos: Gateway settings scattered across UIs, databases, and tribal knowledge. No version control, no rollback strategy, no audit trail.
Security Fragmentation: Each service implementing its own auth, rate limiting, and validation logic. Inconsistent policies, duplicated code, security gaps.
Observability Gaps: Request tracing dies at service boundaries. Error correlation across microservices requires manual log archaeology. Performance bottlenecks hide in the gaps between services.
Deployment Brittleness: Gateway changes require database migrations or manual UI clicks. Rollbacks are prayers. Staging doesn't match production.
These Cursor Rules transform your API gateway from a configuration nightmare into a versioned, testable, observable piece of infrastructure that accelerates development instead of blocking it.
Everything in Git: Gateway configurations, OpenAPI specs, security policies, and infrastructure definitions all version-controlled and peer-reviewed.
Security by Default: Zero-trust networking with OAuth 2.0/OIDC, JWT validation, mTLS between services, and comprehensive policy enforcement at the gateway layer.
Observable by Design: Distributed tracing, structured logging, and metrics collection built into every request path with proper correlation IDs.
Fail-Safe Architecture: Circuit breakers, retries, timeouts, and graceful degradation patterns that prevent cascade failures.
# Before: Manual gateway configuration
# After: Declarative, version-controlled config
services:
- name: user-service
url: http://users:8080
routes:
- name: users.v1
paths: [/api/v1/users]
plugins:
- name: jwt
- name: rate-limiting
config:
minute: 500
Deploy gateway changes with the same confidence as application code. Rollback in seconds, not hours.
// Centralized auth validation - never duplicate this logic again
export const makeHandler = <Body, Resp>(
schema: z.ZodType<Body>,
logic: (b: Body) => Promise<Resp>
) => async (req: Request): Promise<Response> => {
const body = await req.json();
const parsed = schema.parse(body); // Fails fast with 400
const data = await logic(parsed); // Happy path only
return new Response(JSON.stringify(data), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
};
Every request gets automatic correlation IDs, distributed tracing, and structured error responses:
{
"error": {
"code": "SERVICE_UNAVAILABLE",
"message": "Rating service timed out",
"requestId": "req_abc123"
}
}
Without Rules (2-3 days):
With Rules (30 minutes):
kong.yamljwt and rate-limiting pluginsWithout Rules (hours of log archaeology):
With Rules (minutes):
Without Rules:
With Rules:
Choose your gateway and apply Infrastructure-as-Code principles:
# terraform/kong.tf
module "kong_gateway" {
source = "github.com/org/terraform-kong-module"
version = "~> 2.3"
service_count = 3
rate_limit = 1000
redis_cache_ttl = 900 # 15 minutes
}
Every API starts with an OpenAPI spec committed to Git:
# api-specs/users-v1.yaml
openapi: 3.0.3
info:
title: Users API
version: "1.0"
paths:
/api/v1/users:
get:
security:
- bearerAuth: []
responses:
200:
description: User list
401:
$ref: '#/components/responses/Unauthorized'
All gateway configuration in version control:
# kong.yaml
_format_version: "3.0"
services:
- name: users
url: http://users:8080
routes:
- name: users.v1
paths: [/api/v1/users]
plugins:
- name: jwt
config:
claims_to_verify: ["exp", "iat"]
- name: rate-limiting
config:
minute: 500
policy: redis
- name: zipkin
config:
http_endpoint: http://jaeger:9411/api/v2/spans
Use the provided handler pattern for consistent error handling:
// src/handlers/users.ts
import { z } from 'zod';
import { makeHandler } from '../utils/handler';
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1)
});
export const createUser = makeHandler(
CreateUserSchema,
async (userData) => {
// Business logic only - auth/validation handled by gateway
return await userService.create(userData);
}
);
Automate everything with proper validation:
# .github/workflows/gateway.yml
name: Gateway Deploy
on:
push:
branches: [main]
paths: ['kong.yaml', 'terraform/**']
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Validate Kong Config
run: deck validate kong.yaml
- name: Terraform Plan
run: terraform plan -out=tfplan
- name: Deploy Gateway
run: |
terraform apply tfplan
deck sync kong.yaml
Automatic observability with proper correlation:
// Automatic request correlation
export const withTracing = (handler: Handler) =>
async (req: Request): Promise<Response> => {
const traceId = req.headers.get('traceparent') || generateTraceId();
// Log structured data
logger.info('Request started', {
traceId,
method: req.method,
path: new URL(req.url).pathname,
userAgent: req.headers.get('user-agent')
});
return handler(req);
};
These Cursor Rules don't just give you configuration templates—they provide a complete methodology for building gateway infrastructure that scales with your team and grows with your architecture.
Your microservices deserve better than configuration chaos and security fragmentation. Implement these rules and ship gateway infrastructure that accelerates development instead of blocking it.
The path from distributed complexity to centralized clarity starts with your next commit.
You are an expert in TypeScript, Node.js, modern API-gateway products (Kong, Tyk, Gloo, Apigee, AWS API Gateway), Infrastructure-as-Code (Terraform), Observability (OpenTelemetry, Prometheus), and secure micro-services networking.
Key Principles
- Security-first: apply Zero-Trust, OAuth 2.0 / OIDC, JWT, and mTLS at the gateway.
- Contract-first: every endpoint starts with an OpenAPI spec committed to Git.
- Version everything (gateway config, policies, docs) and deploy via CI/CD.
- Design for resiliency: use retries, circuit-breakers, and graceful degradation.
- Single Responsibility: gateway handles cross-cutting concerns; services keep business logic.
- Observability everywhere: trace, log, and metric every request.
- Idempotency & safety: HTTP methods must match action semantics; support retry-tokens.
- Fail fast, validate early, return early; happy path last.
- Automate all infrastructure changes with Terraform modules that are peer-reviewed.
TypeScript (Node 18 +, ESM)
- Enable "strict", "noImplicitAny", and "exactOptionalPropertyTypes" in tsconfig.
- Prefer `interface` for contracts; use `type` for utility unions.
- Use async/await; never mix promise chains with callbacks.
- Disallow `any`; use unknown + refinement.
- Centralise HTTP types in `/src/types/http.ts`.
- Directory convention: kebab-case folders, e.g. `gateways/usage-metrics`.
- Example minimal handler wrapper:
```ts
import { z } from 'zod';
export const makeHandler = <Body, Resp>(schema: z.ZodType<Body>, logic: (b: Body) => Promise<Resp>) =>
async (req: Request): Promise<Response> => {
const body = await req.json();
const parsed = schema.parse(body); // throws 400 automatically
const data = await logic(parsed); // happy path
return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } });
};
```
Error Handling and Validation
- Define a typed `HttpError` class that carries `status`, `code`, and `details`.
- Fail fast: validate headers, auth tokens, and body size before forwarding.
- Edge-case guardians: enforce rate limits, header length, and payload limits.
- Normalise all downstream errors to the following structure:
```json
{
"error": {
"code": "SERVICE_UNAVAILABLE",
"message": "Rating service timed out",
"requestId": "{uuid}"
}
}
```
- Log at source, aggregate centrally (Loki / CloudWatch) with correlation id.
- Use circuit breakers (e.g., Envoy / Kong "Circuit Breaker" plugin) per backend with sane defaults: `threshold=5`, `interval=10s`, `timeout=30s`.
Framework-Specific Rules
Kong Gateway
- Prefer DB-less mode; commit `kong.yaml` alongside app code.
- Use plugins: `jwt`, `acl`, `rate-limiting`, `zipkin`, `cors`.
- Example declarative snippet:
```yaml
services:
- name: ratings
url: http://ratings:8080
routes:
- name: ratings.v1
paths: [/api/v1/ratings]
strip_path: false
plugins:
- name: jwt
- name: rate-limiting
config:
minute: 500
```
Tyk Gateway
- Store API definitions in Git; redeploy via `tyk-sync`.
- Enable `oauth2.0`, `jwt_signing` middleware; offload policy decisions to OPA.
Gloo Gateway
- Use `RouteOption` for advanced matching (e.g., header-based A/B testing).
- Integrate external auth with `extauth` service and `AuthConfig` CRDs.
AWS API Gateway
- REST or HTTP APIs: always enable usage plans + API keys *even* for public endpoints.
- Use Lambda authorizers for custom JWT validation; cache for 30 seconds max.
- Tie deployments to stages derived from Git branch names via GitHub Actions.
Apigee
- Leverage shared flows for cross-cutting concerns (OAuth, logging).
- Maintain revisioning; never hot-edit in UI.
Error Mapping Matrix
- 400 – validation error / bad request
- 401 – unauthenticated / expired token
- 403 – policy denial (rate limit, ACL)
- 404 – no route
- 429 – throttled
- 5xx – downstream failure; never expose internal stack traces.
Testing
- Contract tests with `pact-js`; executed in CI before merge.
- Performance tests: `k6` scripts living in `/tests/perf/*.js`; run nightly.
- Chaos tests: inject 500/latency via Envoy filter during staging deploy.
Performance & Scalability
- Enable LRU cache for JWT verification keys (TTL = 15m).
- Use Redis-backed global rate-limit for multi-node gateways.
- Compress responses >1 kB with gzip; auto-skip `image/*`.
- Geographically distribute gateways; route users based on latency.
Security
- Enforce mTLS between gateway and services; rotate certificates every 90 days.
- Use short-lived (≤15 min) access tokens; refresh with OIDC.
- Apply Content-Security-Policy and HSTS headers for browser clients.
Observability
- Inject `traceparent` header (W3C) on ingress if missing.
- Export metrics: p99 latency, error-rate, req/sec per route.
- Store logs in JSON with `requestId`, `userId`, `ip`, `route`, `status`.
Infrastructure-as-Code (Terraform)
- One module per gateway product; outputs exported URLs and secrets.
- Enforce mandatory code reviews and `terraform plan` in PR.
- Example module usage:
```hcl
module "kong_gateway" {
source = "github.com/org/terraform-kong-module"
version = "~> 2.3"
service_count = 3
rate_limit = 1000
}
```
Deployment Workflow
1. Developer updates OpenAPI + `kong.yaml` → PR.
2. CI: lint TS, run contract tests, `terraform plan`.
3. On merge, CD applies Terraform, pushes new config via decK/tyk-sync.
4. Canary 10 %, verify SLOs; then 100 % traffic.
Documentation
- Auto-generate reference docs with `swagger-cli bundle` → `docs/api.html`.
- Add usage snippets (curl, JS, Python) for each endpoint.
- Publish docs to an internal portal on every merge.
Edge-Cases & Limits Checklist
- Header size < 8 KB.
- Overall payload < 6 MB; otherwise 413.
- Timeout upstream after 25 s; gateway returns 504.
- Retry idempotent (GET, PUT) requests once with exponential backoff (50 ms – 500 ms).