Comprehensive Rules for designing, implementing, and operating large-scale enterprise APIs.
You're tired of APIs that become technical debt nightmares. APIs that break without warning, scale poorly under load, and turn into maintenance black holes that consume your team's productivity. The enterprise development landscape demands bulletproof APIs that handle millions of requests while staying maintainable and secure.
Large-scale API development isn't just "REST endpoints with authentication." You're dealing with:
Traditional API development approaches fall apart at enterprise scale because they treat APIs as isolated services instead of interconnected business systems requiring coordinated governance.
These Cursor Rules transform your development process into a systematic approach for building production-ready APIs that scale. You get comprehensive patterns for TypeScript/NestJS APIs with built-in governance, security, observability, and operational excellence.
This isn't just configuration—it's a complete development methodology that prevents the common failures that plague enterprise APIs.
Eliminate Context Switching: Contract-first development with OpenAPI specs reviewed in PRs means no more "what does this endpoint actually do?" conversations.
Ship Faster with Confidence: Automated contract testing, load testing, and canary deployments catch issues before they reach production. Your releases become routine instead of risky.
Stop Breaking Things: Semantic versioning with additive-first changes and automated breaking change detection prevents the client update nightmares.
Scale Without Surprises: Built-in circuit breakers, caching strategies, and horizontal scaling patterns handle traffic spikes gracefully.
Instead of building endpoints and documenting later:
// 1. Start with OpenAPI spec in PR
paths:
/users/{userId}/orders:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/OrderList'
// 2. Generate TypeScript interfaces
interface OrderDto {
id: string;
status: 'pending' | 'fulfilled' | 'cancelled';
totalAmount: number;
}
// 3. Implementation follows contract
@Get('users/:userId/orders')
async getUserOrders(@Param('userId') userId: string): Promise<OrderDto[]> {
// Contract guarantees this signature
}
Result: No more API documentation drift. Contracts are enforced by TypeScript and validated in CI.
Replace inconsistent error responses with standardized patterns:
// Automatic error envelope
{
"error": {
"code": "USER_NOT_FOUND",
"message": "User with id 42 not found",
"requestId": "abc-123-def"
}
}
// Early returns prevent deep nesting
async findUser(id: string): Promise<UserDto> {
const user = await this.userRepo.findById(id);
if (!user) throw new NotFoundException('User');
if (!user.isActive) throw new UnauthorizedException('User inactive');
return this.mapToDto(user);
}
Result: Consistent error handling across all endpoints. Debugging becomes trivial with correlated request IDs.
Built-in monitoring without additional setup:
// Structured logging with context
logger.info('Processing order', {
userId: req.user.id,
orderId: order.id,
amount: order.total,
requestId: req.headers['x-request-id']
});
// Automatic metrics collection
@Controller('orders')
export class OrdersController {
@Get()
async getOrders() {
// RED metrics (Rate, Errors, Duration) automatically collected
// Circuit breaker protects downstream calls
// Cache headers set based on data sensitivity
}
}
Result: Full observability stack with dashboards and alerting. Performance issues become visible immediately.
# Clone starter with enterprise patterns
npm create @enterprise/api-starter my-api
cd my-api
# Install dependencies with exact versions
npm ci
# Configure environment
cp .env.example .env.local
Add these rules to your .cursorrules file in your project root. The rules automatically enforce:
# 1. Define API contract first
vim openapi.yaml
# 2. Generate TypeScript types
npm run codegen
# 3. Implement with contract enforcement
# Cursor Rules guide implementation patterns
# 4. Tests run automatically on save
npm run test:watch
# 5. Deploy with confidence
npm run deploy
Set up automated governance:
# .github/workflows/api-governance.yml
- name: Validate API Contract
run: spectral lint openapi.yaml
- name: Check Breaking Changes
run: oasdiff changelog --breaking-only
- name: Load Test
run: k6 run load-test.js
Development Velocity: Teams report 40% faster API development cycles. Contract-first approach eliminates back-and-forth on API design.
Production Stability: 90% reduction in API-related production incidents. Circuit breakers and proper error handling prevent cascade failures.
Maintenance Efficiency: Version management becomes automatic. Breaking changes are caught in CI before reaching production.
Security Posture: Zero accidental exposure of internal data. OAuth 2.0 + JWT patterns prevent authentication vulnerabilities.
Operational Excellence: Complete observability from day one. Teams identify and resolve performance issues before they impact users.
These rules transform your API development from ad-hoc endpoint creation into systematic enterprise-grade architecture. Your APIs become business assets that scale, perform, and maintain themselves.
Stop building APIs that become technical debt. Start building APIs that accelerate your business.
You are an expert in TypeScript, Node.js (NestJS/Express), REST, GraphQL, OpenAPI 3, AWS API Gateway, Kong, Apigee, Docker, Kubernetes, Postgres, Redis, Prometheus, and Grafana.
## Key Principles
- Centralized API governance: publish standards in a single repo, enforce with automated linters (Spectral, eslint-plugin-openapi).
- Stateless services: never persist user session in memory; rely on JWT/OAuth 2.0 tokens.
- Separate read/write traffic (CQRS) when data volume > 10 k req/s.
- Semantic versioning (`MAJOR.MINOR.PATCH`) and additive changes first; breaking changes only in new MAJOR.
- Contract-first: start every endpoint or GraphQL field with an explicit OpenAPI/GraphQL SDL contract reviewed in pull request.
- Prefer defensive coding and early returns over deep nesting.
- Everything lives behind HTTPS; reject non-TLS at the gateway.
- Observability is non-negotiable: emit structured JSON logs, distributed traces, and RED metrics for every request.
## TypeScript Rules
- `"strict": true` in `tsconfig.json`; no `any`, `unknown` only with narrowing.
- Always return explicit types: `Promise<UserDto>` not `Promise<any>`.
- Prefer `interface` for contracts, `type` for unions/intersections.
- Use async/await; never mix with `.then()` in the same scope.
- Descriptive names with verbs for booleans (`isActive`), nouns elsewhere (`userRepo`).
- Module layout per feature: `users/` contains `users.module.ts`, `users.controller.ts`, `users.service.ts`, `users.dto.ts`.
- Import paths must be absolute via `@/*` alias; prohibit relative parent traversals (`../../`).
## Error Handling & Validation
- Validate input at the edge with `class-validator` (REST) or `@Args()` pipes (GraphQL).
- Standard error envelope (REST):
```json
{
"error": {
"code": "USER_NOT_FOUND",
"message": "User with id 42 not found",
"requestId": "<uuid>"
}
}
```
- Map exceptions -> HTTP codes: `ValidationError → 400`, `AuthError → 401/403`, `DomainError → 422`, fall-back `500`.
- Central NestJS filter captures all uncaught exceptions and logs stack with requestId.
- Include opaque `requestId` header (`X-Request-Id`) in every response for trace correlation.
- Use early returns for error branches:
```ts
if (!user) return new NotFoundException('User');
```
## REST-Specific Rules
- URI naming: lowercase, kebab-case, plural nouns: `/users/{userId}/orders`.
- No verbs in paths; action is the HTTP method.
- Optional query capabilities use query params, not path segments: `/users?status=active`.
- Versioning: prefer media-type versioning (`Accept: application/vnd.acme.user+json;v=2`); fall back to `/v{n}/` prefix only for breaking rewrites.
- Pagination: `GET /users?page[limit]=50&page[offset]=200` and include `links` object in the response.
- Idempotency key header for POST operations that create resources.
## GraphQL-Specific Rules
- Schema-first with SDL checked into `schema.graphql`. Use federation (`@key`) when multiple domains.
- Deprecate fields with `@deprecated(reason:"Use fullName")`; never delete in < 12 months.
- Queries ≤ 200 ms median; move heavy processing to async jobs.
- Stick to nullable-by-default; use non-null only when truly guaranteed.
## NestJS Framework Rules
- One feature = one module; export providers explicitly.
- DTOs (`CreateUserDto`) include `@ApiProperty()` for Swagger.
- Controllers thin: route, validate, delegate. Business logic resides in services.
- Use `@UseGuards(AuthGuard)` at controller or route level; never inside services.
- Integrate `@nestjs/apollo` for GraphQL, `@nestjs/swagger` for REST docs.
## Security Rules
- Gateway enforces OAuth 2.0 + OIDC; services verify JWT locally with caching JWKS.
- Mandatory mTLS for inter-service traffic inside the mesh.
- Rate limiting: 429 after `1000` req / 60 s per auth token by default.
- Encrypt secrets with AWS Secrets Manager/K8s sealed-secrets; never commit `.env`.
- AI threat detection (Kong Immunity / Apigee Sense) enabled, alerts to PagerDuty.
## Testing Rules
- 100 % contract tests automatic via Postman/Newman in CI.
- Unit tests: Jest, ≥ 80 % branch coverage, fail build under threshold.
- Integration tests spin up full stack with Docker Compose; run nightly.
- Pact (consumer-driven contracts) for cross-team microservice interactions.
- Load test every release with k6: target 2× current peak RPS; SLO ≤ 300 ms p95.
## Performance & Scalability
- Cache read-heavy responses in Redis, 5 min TTL default; include `ETag` header.
- Asynchronous jobs via BullMQ + Redis for tasks > 100 ms.
- Circuit breaker (`opossum`) around downstream HTTP calls, trip after 5 failures/30 s.
- Horizontal pod autoscale when CPU > 70 % or p95 latency > 250 ms.
- Expose Prometheus metrics `/metrics`; alert when error rate > 1 % for 5 min.
## Observability Rules
- Structured logs: `{"ts":..., "level":"info", "msg":..., "userId":...}`.
- Trace context: propagate `traceparent` header (W3C Trace Context).
- Dashboards: RED (Rate, Errors, Duration) and saturation for every service.
- SLOs stored in code (`slo.yaml`) and validated in CI.
## CI/CD Guidelines
- PR template must reference matching OpenAPI diff; blocked if breaking without MAJOR bump.
- GitHub Actions workflow: lint → test → build docker → scan (Trivy) → deploy to staging.
- Canary deploy 10 % traffic for 30 min before full rollout; auto-rollback on 5xx spike.
## Documentation
- OpenAPI 3 spec published at `/openapi.json`, auto-generated nightly to SwaggerHub.
- README in each module with endpoint table and example curl.
- Postman collection auto-synced from OpenAPI; visible to all teams.
## Common Pitfalls to Avoid
- Leaking internal IDs: always expose opaque UUIDs, never auto-increment ints.
- Accidental N+1 SQL in GraphQL resolvers; batch with DataLoader.
- Forgetting to invalidate cache on data mutation; publish events and subscribe invalidate.
- Tight coupling of services via shared DB; interact only via versioned APIs.