Dev-Backend — Production-Grade Backend Engineering
Build reliable, secure, and maintainable server-side applications.
This skill has modular references for specialized guidance — read the relevant ones before coding.
It activates by change surface whenever work primarily touches APIs, servers, services, jobs, data access, schemas, migrations, or operational backend behavior.
C0/C1 work (small local patches): See jaw-dev §0.0 Work Classifier + §0.1 Patch Fast-Path before reading references.
jaw-dev is canonical: jaw-dev §0.2 Rule Classes, §3 Verification Gate, and §5 Safety Rules apply to all work governed by this skill.
Modular References
| File |
When to Read |
What It Covers |
references/core/crud-api.md |
C2 ordinary CRUD/resource endpoints |
Route/schema/service/query basics, five operations, error+permission mapping |
references/core/api-design.md |
New/changed API style, or C3+ API work (C2 ordinary slice: crud-api.md alone suffices) |
REST conventions, response envelopes, HTTP status, pagination, GraphQL, gRPC, tRPC |
references/core/api-lifecycle.md |
API versioning, deprecation, migration |
Versioning strategy, RFC 9745/8594 lifecycle, oasdiff CI gate |
references/core/architecture.md |
New features at C3+ (C2 ordinary slice: crud-api.md alone suffices) |
Layered architecture, DDD, SOLID, when to split, monolith vs micro |
references/core/anti-slop-backend.md |
New endpoints, classes, or modules |
Banned patterns: god classes, raw SQL in services, magic numbers, etc. |
references/core/observability.md |
Production deployments |
OpenTelemetry, structured logging, distributed tracing, alerting |
references/core/health-checks.md |
Production/long-lived services |
Liveness, readiness, startup probes, dependency checks |
references/core/process-isolation.md |
CPU-bound or untrusted work |
worker_threads vs child_process vs separate service, communication, resource limits |
references/core/caching.md |
Performance optimization |
Redis-compatible (Valkey/Redis) patterns, CDN, connection pooling, cache invalidation |
references/stacks/node.md |
Node.js/TypeScript projects |
Express/Fastify, middleware, Zod validation, ESM, error handling |
references/stacks/python.md |
Python projects |
FastAPI/Django, Pydantic, async patterns, testing |
references/stacks/database.md |
Database design/optimization |
PostgreSQL, MongoDB, indexing, N+1, migrations, ORM comparison |
references/core/ml-serving.md |
ML model deployment, GPU inference |
vLLM/SGLang runtime selection, FastAPI+GPU patterns, dynamic batching, quantization |
references/core/llm-integration.md |
RAG, LLM API integration, prompt engineering |
Chunking, hybrid search, vector DB, structured output, LangChain/LlamaIndex 2026 |
references/core/mobile-api.md |
Mobile app API patterns |
BFF, push notifications, offline sync, mobile auth, API optimization |
Read api-design.md + anti-slop-backend.md first, then the relevant stack file.
For C2 ordinary slices, crud-api.md alone suffices; read api-design.md/architecture.md for new API styles or C3+ work.
When backend decisions depend on current external API docs, API lifecycle
changes, LLM/RAG provider behavior, dependency freshness, or package/source
evidence, read the active jaw-search skill and follow its query-rewrite,
source-fetch, and evidence-status rules.
0. Stack Detection & Architecture Clarification
Auto-detect (existing projects)
| File Found |
Project Type |
tsconfig.json |
TypeScript (Node) |
package.json (no ts) |
JavaScript (Node) |
pyproject.toml/requirements.txt |
Python |
go.mod |
Go |
Cargo.toml |
Rust |
If config files exist → detect silently and proceed.
Architecture Clarification (new or ambiguous projects)
When the request has unspecified technology or unclear scope, clarify before coding:
- Identify what's ambiguous from this list:
| Dimension |
Options to present |
| API style |
REST (default) · GraphQL (BFF/mobile) · gRPC (internal microservices) · tRPC (TS monorepo) |
| Database |
PostgreSQL (default, ACID) · MongoDB (flexible schema) · SQLite (embedded) |
| Auth method |
JWT + refresh (stateless) · Session-based (simple) · OAuth 2.1 (3rd party) |
| Realtime |
Not needed (default) · WebSocket · SSE · Polling |
| Architecture |
Monolith (default) · Modular monolith · Microservices |
- Recommend one with reasoning: cite project context. e.g., "Small team → monolith + PostgreSQL + JWT is the simplest starting point."
- Over-engineering guard: A CRUD API probably doesn't need GraphQL + microservices + event sourcing. Simple → complex, not the reverse.
- One round limit: 2-3 options → recommend → confirm → proceed.
If the user already specifies clear tech (e.g. "FastAPI로 REST API 만들어줘"), skip this entirely.
Node/framework defaults (verified 2026-07-02): production uses Active/Maintenance
LTS — Node 24 (Active LTS) for new services, Node 22 (Maintenance). Framework: Fastify
for greenfield Node APIs (schema/Pino/plugin structure); Express 5 for legacy/ecosystem
compatibility; Hono for edge/serverless/multi-runtime Web-Standards APIs. New TS
validation baseline is Zod v4 (read the migration guide before upgrading v3 projects).
Sources: references/stacks/node.md § Sources.
For new Node backend source files, prefer .ts when the repo supports TypeScript or is greenfield. Inherit jaw-dev TypeScript strict-compatibility rules.
If backend boundaries are unclear, read existing source-of-truth docs/logs first, then document routes, services, repositories, data stores, and runtime commands in the repo's existing SOT before broad implementation.
1. Architecture Decision
Before coding, identify the right pattern:
| Team Size |
Default Starting Point |
| 1-3 devs |
Modular monolith |
| 4-10 devs |
Modular monolith or SOA |
| 10+ devs |
Consider microservices |
Default to monolith. Extract only when you have a proven need (different scaling, independent deployment, technology mismatch).
See references/core/architecture.md for full decision matrices.
API Protocol Decision
| Protocol |
Choose When |
Avoid When |
| REST |
Public/partner APIs, simple CRUD, caching matters |
Clients need flexible data shapes |
| GraphQL |
Mobile/BFF client aggregation, multiple resources per request |
Simple CRUD, server-to-server, file uploads |
| gRPC |
Internal microservices, high-perf binary, bidirectional streaming |
Browser clients (without gRPC-Web), public APIs |
| tRPC (v11) |
TypeScript shared end-to-end: monorepo, internal tools |
Polyglot environments, public APIs |
Hybrid pattern (verified 2026-07-02):
Public/Partner → REST (OpenAPI 3.1+; prefer 3.2 where tooling supports it)
Mobile/Web BFF → GraphQL (client aggregation; Apollo Federation ONLY when multiple
independently-owned subgraphs must compose into a supergraph)
Internal services → gRPC (Protobuf contracts)
TS internal tools → tRPC v11 (zero-codegen type safety)
Deprecations: emit Deprecation (RFC 9745) and optional Sunset (RFC 8594) headers,
but client adoption is uneven — always pair with OpenAPI/changelog dates and deprecated-
endpoint traffic dashboards.
See references/core/api-design.md for protocol-specific patterns.
Long-Lived Connection Operation
Rules for SSE, WebSocket, and any connection held open beyond a single request-response cycle.
Lifecycle examples (HEURISTIC): tune heartbeat, cap, drain, and duration to protocol, proxy, capacity, and product needs. The common six-connection browser limit concerns HTTP/1.x; HTTP/2 stream limits are negotiated. These values are not universal failure thresholds.
| Parameter |
Default |
Rationale |
| Heartbeat interval |
Route-specific |
Keep the stream observable within proxy limits |
| Reconnection backoff |
Exponential 1s-30s with jitter |
Prevent thundering herd on server restart |
| Max connection duration |
Route-specific |
Rebalance within the declared proxy and resource budget |
| Connections per client |
Route-specific |
Account for HTTP version and server capacity |
Server-Side Requirements:
- Connection tracking: Track active connections as needed for capacity, drain, and debugging; use the repository’s established registry.
- Graceful drain on deploy: Stop accepting new connections, finish or close streams within the route budget, and let clients reconnect by their existing protocol. Do not invent a wire frame.
- Memory budget: Bound per-connection buffers, monitor total use, and reject new connections at the established capacity limit.
- Backpressure: If a client stops consuming, use the route-defined bounded buffer and loss/disconnect policy.
Pattern — "202 + Job ID" when the API defines an asynchronous job:
For that contract, instead of holding a connection open for the work:
POST /generate → 202 { jobId: "j_abc123" }
GET /jobs/j_abc123 → { status: "processing", progress: 0.6 }
→ { status: "complete", result: {...} }
A job API may push status over SSE/WebSocket; an existing streaming API may deliver its own operation result. For example, cli-jaw GET /api/events preserves data-only SSE, flushes headers promptly, rejects at capacity with 503, and sends a visible data ping. Do not add an event: field or fixed one-hour cutoff to that route.
Banned:
| Banned |
Fix |
| Unbounded connections (no cap, no registry) |
Track clients and enforce protocol-aware capacity limits |
| No heartbeat where proxy/clients require visibility |
Use the route-defined heartbeat interval and frame format |
| Blocking event loop per connection (sync work in message handler) |
Offload to worker thread or queue; handler stays async |
| Work exceeding the declared response budget or blocking the event loop |
Queue, stream, or isolate according to the route contract |
| No reconnection logic on client side |
Implement exponential backoff with jitter |
2. Layered Architecture (Default; Allow Serverless Handlers, Vertical Slices, and Small Scripts When Appropriate)
Routes → Controllers → Services → Repositories → Database
│ │ │ │
│ │ │ └── Data access only
│ │ └── Business logic (validation at controller boundary — service trusts caller per jaw-dev-architecture §4)
│ └── Parse HTTP, format response
└── URL mapping, middleware
Rules:
- Routes: URL patterns + middleware only. No logic.
- Controllers: parse input, call services, format output. No business rules.
- Services: receive/return plain data (not
req/res). All logic here.
- Repositories: abstract DB access. Services access data through repositories only.
Repository Pattern (Interface Abstraction)
Boundary parsing contract (BACKEND-BOUNDARY-01, DEFAULT). Parse once at
ingress and trust boundaries; inside that boundary, typed values are proof. Do not
duplicate schema validation, null defense, or defensive parsing in services unless the
data crosses a new trust boundary. Canonical boundary-defense ownership stays with
jaw-dev-architecture §4; this is the backend stub.
The reason to state it as a rule rather than a preference: duplicated validation reads as
prudence and behaves as ambiguity — with two checks, neither one is the boundary, and a
later change can remove whichever looks redundant.
Server runtime safety (BACKEND-RUNTIME-01, DEFAULT). Production server runtimes set
explicit read, write, request/idle, and graceful-shutdown timeouts. Drain on SIGTERM or
deploy: stop accepting new work, let in-flight work finish within the shutdown budget,
then close. Propagate the request id from ingress into structured logs, traces, queued
work, and outbound calls wherever the stack supports it — an id that stops at the queue
boundary is the one you will miss during an incident.
Use repository interfaces so services depend on abstractions, enabling mocking and swapping implementations.
Async Task Queue Patterns
When work exceeds what an HTTP response cycle should hold open, use a queue.
Decision: Queue vs Direct:
| Condition |
Use Queue |
Use Direct |
| Work exceeds the measured request/proxy budget (5s is only an example) |
Usually |
Streaming or bounded direct work may fit |
| Must be retryable on failure |
Yes |
No |
| Fire-and-forget (caller doesn't wait) |
Yes |
No |
| <1s, idempotent, caller needs immediate result |
No |
Yes |
| Real-time user-facing validation |
No |
Yes |
Pattern — Accept, Queue, Notify:
1. Client → POST /tasks → Server validates, enqueues
2. Server → 202 { jobId } → Client receives immediately
3. Worker → picks from queue → executes task
4. Client → GET /tasks/{id} → polls status (or receives webhook/SSE push)
5. Worker → completes → writes result, triggers notification
Queue Selection Guide:
| Queue |
When |
Notes |
| BullMQ (Redis-compatible) |
Node.js, need retries + priorities + rate limiting |
Most mature Node queue; needs Redis/Valkey |
| Celery (Redis/RabbitMQ) |
Python, distributed workers, periodic tasks |
De facto Python standard |
| pg-boss (PostgreSQL) |
Node.js, Postgres is the durable system of record, moderate scale |
No extra infra; SKIP_LOCKED-based |
| Simple DB queue (polling) |
Small scale (<100 jobs/min), any language |
status column + SELECT FOR UPDATE SKIP LOCKED |
| SQS / Cloud Tasks |
Serverless, managed, very high scale |
No infra to manage; at-least-once delivery |
| Temporal |
Durable multi-step workflows: sagas, human-in-loop, long-running AI/business processes |
Workflow engine, NOT a default queue replacement |
Required Safeguards:
| Safeguard |
Rule |
| Idempotency key |
Every enqueue call must include a unique idempotency key; dedup on insert |
| Dead letter queue (DLQ) |
Failed 3x (configurable) → move to DLQ → alert → manual review |
| Max retries |
Set explicit limit (default: 3); exponential backoff between attempts |
| Timeout per job |
Every job has a max execution time; kill and retry on exceed |
| Visibility timeout |
Lock duration > expected execution time; prevent duplicate processing |
| Observability |
Emit metrics: queue depth, processing time p95, DLQ size, failure rate |
Banned:
| Banned |
Fix |
| Work exceeds the declared request budget or blocks the event loop |
Queue, stream, or isolate according to the actual contract |
| Queue without DLQ |
Always configure DLQ; alert on DLQ depth > 0 |
| Infinite retries (no max) |
Set maxRetries=3 with exponential backoff |
| No idempotency (duplicate jobs on retry) |
Idempotency key on every enqueue; dedup in worker |
| No timeout on job execution |
Set per-job timeout; kill + mark failed on exceed |
| Polling without backoff (tight loop) |
Poll with interval (1-5s) or use blocking pop / push notification |
3. Error Handling
| Type |
HTTP |
Log Level |
| Validation |
400 |
warn |
| Authentication |
401 |
warn |
| Authorization |
403 |
warn |
| Not found |
404 |
info |
| Conflict |
409 |
warn |
| Rate limit |
429 |
info |
| Internal error |
500 |
error + stack |
Follow the repository error convention. A centralized AppError class is one option where already selected; distinguish operational from programmer errors.
Error Taxonomy (optional AppError hierarchy)
If the repository chooses AppError, a base class may carry statusCode, code, and isOperational. Do not introduce a parallel hierarchy into an established Result/error model.
Result Pattern (conditional)
Consider the Result/Either pattern (e.g. neverthrow) for recoverable domain errors where explicit error handling improves clarity — adopt it only when the project scope justifies it and the repo doesn't already settle error style (HEURISTIC, not a universal requirement).
| Library |
When to Use |
| neverthrow |
Default choice — small explicit Result<T, E> for recoverable domain errors |
| Effect |
Only when the app benefits from a full effect runtime: typed errors, retries, resources, concurrency, tracing, service composition |
Use Result only when selected for this repository. Otherwise propagate errors to a clear handling boundary; do not add wrappers or change public error contracts by preference.
4. Middleware Execution Order
Apply in this sequence (order matters):
- Request ID generation
- Request logging
- Security headers (CORS, CSP, HSTS)
- Rate limiting
- Authentication
- Authorization
- Body parsing
- Input validation (schema)
- Route handler
- Error handler
- Response logging
5. API Response Contract
API endpoints should use a stable response envelope (DEFAULT) unless the protocol (GraphQL, gRPC, SSE) defines its own or the repo already has a different established contract — follow the existing contract first. Envelope, OTel, health checks, and deployment-readiness checks are production-surface concerns (jaw-dev §0.4 shared definition), conditional by project scope, not universal blockers.
For APIs that choose this envelope:
success boolean at top level — never infer from HTTP status alone
error.code is machine-readable (UPPER_SNAKE), error.message is human-readable
meta.requestId on every response — enables cross-service tracing
- Pagination uses cursor-based (
after/before) for large datasets, offset-based (page/pageSize) for admin UIs
- Nullability: prefer consistent key presence; omit when sparse payloads are intentional
- Timestamps: ISO 8601 UTC (
2024-01-15T09:30:00Z), never Unix epoch in JSON
- Money: integer cents + currency code, never floating point
See references/core/api-design.md for protocol-specific patterns (REST, GraphQL, gRPC, tRPC).
6. Caching Strategy
Decision rules:
- Say Redis-compatible, not Redis-only (verified 2026-07-02): prefer Valkey
(Linux Foundation, BSD) for permissive OSS/self-hosted defaults; choose Redis when
managed-service, module, or license posture justifies it (Redis relicensed 2024;
Redis 8 added AGPLv3).
- Cache only after correctness is proven on the uncached path.
- Prefer cache-aside by default; use write-through only when strong consistency matters.
- Every key has a namespace, version, stable identifier, TTL, and invalidation trigger.
- Never cache error responses or personalized CDN responses; protect cached PII with encryption and access controls.
- Add stampede protection for hot keys and monitor hit rate, pool exhaustion, and stale-read incidents.
See references/core/caching.md for TTL guidance, Redis-compatible cache patterns, CDN rules, invalidation triggers, connection pooling, and code examples.
7. Observability (OpenTelemetry)
Decision rules:
- Production services emit traces, metrics, and structured JSON logs with
requestId, traceId, and spanId.
- OTel maturity (verified 2026-07-02): traces and metrics are Stable in JS/Python;
logs are still Development — the baseline is trace/span-correlated structured
logs + OTel traces/metrics; adopt OTel Logs export only where that maturity is acceptable.
- Start with OTel auto-instrumentation, then add custom spans only for business-critical or non-instrumented work.
- Never log PII, secrets, full request/response bodies, or noisy stack traces outside error boundaries.
- Page only on customer-impacting signals tied to SLOs; use warning alerts for capacity trends.
See references/core/observability.md for OTel setup, structured logging conventions, trace propagation, dashboards, RUM correlation, and alerting guidance.
8. Skeleton Project Evaluation
When starting from a template or boilerplate, verify before building on top:
| Check |
What to Verify |
| Dependencies |
Up-to-date? CVEs? Unnecessary packages? |
| Architecture fit |
Does the template's structure match your actual needs? |
| Auth/security |
Is the auth pattern appropriate for your use case? |
| Database |
Is the ORM/query builder suitable for your data model? |
| Dead code |
Remove unused example routes, models, and middleware |
| Config management |
Environment-based config, no hardcoded values |
Treat templates as starting points, not gospel. Strip to essentials, then add what you need.
9. API Performance Targets (HEURISTIC defaults, not universal SLOs)
These are aggressive healthy-service starting budgets. Each product MUST define its own
SLOs from user journeys and alert on error-budget burn, not raw percentile thresholds
alone (Google SRE SLO practice; see observability.md Sources).
| Metric |
Default budget |
Escalation |
| p50 response time (reads) |
≤ 50ms |
Profile with tracing |
| p95 response time (reads) |
≤ 200ms, alert at >500ms (see observability.md) |
Optimization target |
| p95 response time (writes) |
≤ 500ms |
Acceptable for complex writes |
| p99 response time |
≤ 1000ms |
Investigate outliers |
| Error rate |
< 0.1% target, alert at >1% (see observability.md) |
Optimization target |
- Measure at the handler level, not including network
- Use
Server-Timing header to expose backend timing to frontend
- Log slow queries (> 100ms) with EXPLAIN output
- Connection pool (long-running servers): min = CPU cores, max = CPU cores × 4; for serverless/Lambda use min = 0–2
API responses that drive UI must include descriptive error messages (not just codes) for screen reader announcement, pagination metadata (total count) for assistive technology, and Content-Language header matching response body language.
10. SEO Support Endpoints
When the app serves web pages (SSR/SSG):
GET /sitemap.xml — dynamic sitemap generation with <lastmod>
GET /robots.txt — configurable per-environment (disallow staging/preview)
- Structured data: provide JSON-LD data in API responses when frontend needs it
- Redirect chains: max 1 hop (301 for permanent, 308 for POST-preserving)
11. Deployment Patterns
- Blue-green: deploy to inactive environment, verify health + smoke tests, swap traffic
- Canary: route 5% → 25% → 100% with automated rollback on error rate spike
- Rollback: always keep previous version deployed and ready to swap back
- Database migrations: separate from code deploy, backward-compatible (expand-then-contract)
- Feature flags: use for gradual rollout of risky changes
12. Pre-Flight Checklist
- Analytical data / ETL / pipeline quality: load
jaw-dev-data.
- API consumer context / frontend contract alignment: load
jaw-dev-frontend.
- Test strategy / verification harnesses / QA execution: load
jaw-dev-testing.
- Backend failure RCA methodology: load
jaw-dev-debugging.
- New project setup / file placement conventions: load
jaw-dev-scaffolding.
Before delivering:
1---2name: jaw-dev-backend3description: "MUST USE for backend, API, server, or database work — API design, architecture, database optimization, security hardening, error handling, middleware, observability, queues, and long-lived connections. Triggers: backend, API, REST, GraphQL, schema, migration, query optimization, middleware, OTel, caching, Result pattern, server, 백엔드, API 작업, 마이그레이션, 쿼리 최적화."4metadata:5 source: https://skillmd.com/skills/lidge-jun/jaw-dev-backend6 short-description: "Framework-agnostic backend guidance for APIs, architecture, data access, and operations."7 keywords: "API, REST, endpoint, middleware, database, ORM, cache, queue, error handling, observability"8 last-verified: "2026-07-02"9---1011# Dev-Backend — Production-Grade Backend Engineering1213Build reliable, secure, and maintainable server-side applications.14This skill has modular references for specialized guidance — read the relevant ones before coding.15It activates by change surface whenever work primarily touches APIs, servers, services, jobs, data access, schemas, migrations, or operational backend behavior.1617> **C0/C1 work (small local patches):** See `jaw-dev` §0.0 Work Classifier + §0.1 Patch Fast-Path before reading references.1819> **`jaw-dev` is canonical:** `jaw-dev` §0.2 Rule Classes, §3 Verification Gate, and §5 Safety Rules apply to all work governed by this skill.2021## Modular References2223| File | When to Read | What It Covers |24| -------------------------------------- | ------------------------------ | ---------------------------------------------------------------------- |25| `references/core/crud-api.md` | C2 ordinary CRUD/resource endpoints | Route/schema/service/query basics, five operations, error+permission mapping |26| `references/core/api-design.md` | New/changed API style, or C3+ API work (C2 ordinary slice: `crud-api.md` alone suffices) | REST conventions, response envelopes, HTTP status, pagination, GraphQL, gRPC, tRPC |27| `references/core/api-lifecycle.md` | API versioning, deprecation, migration | Versioning strategy, RFC 9745/8594 lifecycle, oasdiff CI gate |28| `references/core/architecture.md` | New features at C3+ (C2 ordinary slice: `crud-api.md` alone suffices) | Layered architecture, DDD, SOLID, when to split, monolith vs micro |29| `references/core/anti-slop-backend.md` | New endpoints, classes, or modules | Banned patterns: god classes, raw SQL in services, magic numbers, etc. |30| `references/core/observability.md` | Production deployments | OpenTelemetry, structured logging, distributed tracing, alerting |31| `references/core/health-checks.md` | Production/long-lived services | Liveness, readiness, startup probes, dependency checks |32| `references/core/process-isolation.md` | CPU-bound or untrusted work | worker_threads vs child_process vs separate service, communication, resource limits |33| `references/core/caching.md` | Performance optimization | Redis-compatible (Valkey/Redis) patterns, CDN, connection pooling, cache invalidation |34| `references/stacks/node.md` | Node.js/TypeScript projects | Express/Fastify, middleware, Zod validation, ESM, error handling |35| `references/stacks/python.md` | Python projects | FastAPI/Django, Pydantic, async patterns, testing |36| `references/stacks/database.md` | Database design/optimization | PostgreSQL, MongoDB, indexing, N+1, migrations, ORM comparison |37| `references/core/ml-serving.md` | ML model deployment, GPU inference | vLLM/SGLang runtime selection, FastAPI+GPU patterns, dynamic batching, quantization |38| `references/core/llm-integration.md` | RAG, LLM API integration, prompt engineering | Chunking, hybrid search, vector DB, structured output, LangChain/LlamaIndex 2026 |39| `references/core/mobile-api.md` | Mobile app API patterns | BFF, push notifications, offline sync, mobile auth, API optimization |4041Read `api-design.md` + `anti-slop-backend.md` first, then the relevant stack file.42For C2 ordinary slices, `crud-api.md` alone suffices; read `api-design.md`/`architecture.md` for new API styles or C3+ work.4344When backend decisions depend on current external API docs, API lifecycle45changes, LLM/RAG provider behavior, dependency freshness, or package/source46evidence, read the active `jaw-search` skill and follow its query-rewrite,47source-fetch, and evidence-status rules.4849---5051## 0. Stack Detection & Architecture Clarification5253### Auto-detect (existing projects)5455| File Found | Project Type |56| ----------------------------------- | ----------------- |57| `tsconfig.json` | TypeScript (Node) |58| `package.json` (no ts) | JavaScript (Node) |59| `pyproject.toml`/`requirements.txt` | Python |60| `go.mod` | Go |61| `Cargo.toml` | Rust |6263If config files exist → detect silently and proceed.6465### Architecture Clarification (new or ambiguous projects)6667When the request has **unspecified technology or unclear scope**, clarify before coding:68691. **Identify what's ambiguous** from this list:7071| Dimension | Options to present |72| ------------ | ----------------------------------------------------------------------------------- |73| API style | REST (default) · GraphQL (BFF/mobile) · gRPC (internal microservices) · tRPC (TS monorepo) |74| Database | PostgreSQL (default, ACID) · MongoDB (flexible schema) · SQLite (embedded) |75| Auth method | JWT + refresh (stateless) · Session-based (simple) · OAuth 2.1 (3rd party) |76| Realtime | Not needed (default) · WebSocket · SSE · Polling |77| Architecture | Monolith (default) · Modular monolith · Microservices |78792. **Recommend one with reasoning**: cite project context. e.g., "Small team → monolith + PostgreSQL + JWT is the simplest starting point."803. **Over-engineering guard**: A CRUD API *probably* doesn't need GraphQL + microservices + event sourcing. Simple → complex, not the reverse.814. **One round limit**: 2-3 options → recommend → confirm → proceed.8283If the user already specifies clear tech (e.g. "FastAPI로 REST API 만들어줘"), **skip this entirely**.8485**Node/framework defaults (verified 2026-07-02):** production uses Active/Maintenance86LTS — Node 24 (Active LTS) for new services, Node 22 (Maintenance). Framework: Fastify87for greenfield Node APIs (schema/Pino/plugin structure); Express 5 for legacy/ecosystem88compatibility; Hono for edge/serverless/multi-runtime Web-Standards APIs. New TS89validation baseline is Zod v4 (read the migration guide before upgrading v3 projects).90Sources: `references/stacks/node.md` § Sources.9192For new Node backend source files, prefer `.ts` when the repo supports TypeScript or is greenfield. Inherit `jaw-dev` TypeScript strict-compatibility rules.93If backend boundaries are unclear, read existing source-of-truth docs/logs first, then document routes, services, repositories, data stores, and runtime commands in the repo's existing SOT before broad implementation.9495---9697## 1. Architecture Decision9899Before coding, identify the right pattern:100101| Team Size | Default Starting Point |102| --------- | ----------------------- |103| 1-3 devs | Modular monolith |104| 4-10 devs | Modular monolith or SOA |105| 10+ devs | Consider microservices |106107**Default to monolith.** Extract only when you have a proven need (different scaling, independent deployment, technology mismatch).108109See `references/core/architecture.md` for full decision matrices.110111### API Protocol Decision112113| Protocol | Choose When | Avoid When |114|----------|-------------|------------|115| **REST** | Public/partner APIs, simple CRUD, caching matters | Clients need flexible data shapes |116| **GraphQL** | Mobile/BFF client aggregation, multiple resources per request | Simple CRUD, server-to-server, file uploads |117| **gRPC** | Internal microservices, high-perf binary, bidirectional streaming | Browser clients (without gRPC-Web), public APIs |118| **tRPC** (v11) | TypeScript shared end-to-end: monorepo, internal tools | Polyglot environments, public APIs |119120**Hybrid pattern (verified 2026-07-02):**121```122Public/Partner → REST (OpenAPI 3.1+; prefer 3.2 where tooling supports it)123Mobile/Web BFF → GraphQL (client aggregation; Apollo Federation ONLY when multiple124 independently-owned subgraphs must compose into a supergraph)125Internal services → gRPC (Protobuf contracts)126TS internal tools → tRPC v11 (zero-codegen type safety)127```128Deprecations: emit `Deprecation` (RFC 9745) and optional `Sunset` (RFC 8594) headers,129but client adoption is uneven — always pair with OpenAPI/changelog dates and deprecated-130endpoint traffic dashboards.131132See `references/core/api-design.md` for protocol-specific patterns.133134### Long-Lived Connection Operation135136Rules for SSE, WebSocket, and any connection held open beyond a single request-response cycle.137138**Lifecycle examples (HEURISTIC):** tune heartbeat, cap, drain, and duration to protocol, proxy, capacity, and product needs. The common six-connection browser limit concerns HTTP/1.x; HTTP/2 stream limits are negotiated. These values are not universal failure thresholds.139140| Parameter | Default | Rationale |141|-----------|---------|-----------|142| Heartbeat interval | Route-specific | Keep the stream observable within proxy limits |143| Reconnection backoff | Exponential 1s-30s with jitter | Prevent thundering herd on server restart |144| Max connection duration | Route-specific | Rebalance within the declared proxy and resource budget |145| Connections per client | Route-specific | Account for HTTP version and server capacity |146147**Server-Side Requirements:**148149- **Connection tracking:** Track active connections as needed for capacity, drain, and debugging; use the repository’s established registry.150- **Graceful drain on deploy:** Stop accepting new connections, finish or close streams within the route budget, and let clients reconnect by their existing protocol. Do not invent a wire frame.151- **Memory budget:** Bound per-connection buffers, monitor total use, and reject new connections at the established capacity limit.152- **Backpressure:** If a client stops consuming, use the route-defined bounded buffer and loss/disconnect policy.153154**Pattern — "202 + Job ID" when the API defines an asynchronous job:**155156For that contract, instead of holding a connection open for the work:157```158POST /generate → 202 { jobId: "j_abc123" }159GET /jobs/j_abc123 → { status: "processing", progress: 0.6 }160 → { status: "complete", result: {...} }161```162A job API may push status over SSE/WebSocket; an existing streaming API may deliver its own operation result. For example, cli-jaw `GET /api/events` preserves data-only SSE, flushes headers promptly, rejects at capacity with 503, and sends a visible data ping. Do not add an `event:` field or fixed one-hour cutoff to that route.163164**Banned:**165166| Banned | Fix |167|--------|-----|168| Unbounded connections (no cap, no registry) | Track clients and enforce protocol-aware capacity limits |169| No heartbeat where proxy/clients require visibility | Use the route-defined heartbeat interval and frame format |170| Blocking event loop per connection (sync work in message handler) | Offload to worker thread or queue; handler stays async |171| Work exceeding the declared response budget or blocking the event loop | Queue, stream, or isolate according to the route contract |172| No reconnection logic on client side | Implement exponential backoff with jitter |173174---175176## 2. Layered Architecture (Default; Allow Serverless Handlers, Vertical Slices, and Small Scripts When Appropriate)177178```179Routes → Controllers → Services → Repositories → Database180 │ │ │ │181 │ │ │ └── Data access only182 │ │ └── Business logic (validation at controller boundary — service trusts caller per jaw-dev-architecture §4)183 │ └── Parse HTTP, format response184 └── URL mapping, middleware185```186187**Rules:**188- Routes: URL patterns + middleware only. No logic.189- Controllers: parse input, call services, format output. No business rules.190- Services: receive/return plain data (not `req`/`res`). All logic here.191- Repositories: abstract DB access. Services access data through repositories only.192193### Repository Pattern (Interface Abstraction)194195**Boundary parsing contract (BACKEND-BOUNDARY-01, DEFAULT).** Parse once at196ingress and trust boundaries; inside that boundary, typed values are proof. Do not197duplicate schema validation, null defense, or defensive parsing in services unless the198data crosses a **new** trust boundary. Canonical boundary-defense ownership stays with199`jaw-dev-architecture` §4; this is the backend stub.200201The reason to state it as a rule rather than a preference: duplicated validation reads as202prudence and behaves as ambiguity — with two checks, neither one is the boundary, and a203later change can remove whichever looks redundant.204205**Server runtime safety (BACKEND-RUNTIME-01, DEFAULT).** Production server runtimes set206explicit read, write, request/idle, and graceful-shutdown timeouts. Drain on SIGTERM or207deploy: stop accepting new work, let in-flight work finish within the shutdown budget,208then close. Propagate the request id from ingress into structured logs, traces, queued209work, and outbound calls wherever the stack supports it — an id that stops at the queue210boundary is the one you will miss during an incident.211212Use repository interfaces so services depend on abstractions, enabling mocking and swapping implementations.213214### Async Task Queue Patterns215216When work exceeds what an HTTP response cycle should hold open, use a queue.217218**Decision: Queue vs Direct:**219220| Condition | Use Queue | Use Direct |221|-----------|-----------|------------|222| Work exceeds the measured request/proxy budget (5s is only an example) | Usually | Streaming or bounded direct work may fit |223| Must be retryable on failure | Yes | No |224| Fire-and-forget (caller doesn't wait) | Yes | No |225| <1s, idempotent, caller needs immediate result | No | Yes |226| Real-time user-facing validation | No | Yes |227228**Pattern — Accept, Queue, Notify:**229230```2311. Client → POST /tasks → Server validates, enqueues2322. Server → 202 { jobId } → Client receives immediately2333. Worker → picks from queue → executes task2344. Client → GET /tasks/{id} → polls status (or receives webhook/SSE push)2355. Worker → completes → writes result, triggers notification236```237238**Queue Selection Guide:**239240| Queue | When | Notes |241|-------|------|-------|242| **BullMQ** (Redis-compatible) | Node.js, need retries + priorities + rate limiting | Most mature Node queue; needs Redis/Valkey |243| **Celery** (Redis/RabbitMQ) | Python, distributed workers, periodic tasks | De facto Python standard |244| **pg-boss** (PostgreSQL) | Node.js, Postgres is the durable system of record, moderate scale | No extra infra; SKIP_LOCKED-based |245| **Simple DB queue** (polling) | Small scale (<100 jobs/min), any language | `status` column + `SELECT FOR UPDATE SKIP LOCKED` |246| **SQS / Cloud Tasks** | Serverless, managed, very high scale | No infra to manage; at-least-once delivery |247| **Temporal** | Durable multi-step workflows: sagas, human-in-loop, long-running AI/business processes | Workflow engine, NOT a default queue replacement |248249**Required Safeguards:**250251| Safeguard | Rule |252|-----------|------|253| Idempotency key | Every enqueue call must include a unique idempotency key; dedup on insert |254| Dead letter queue (DLQ) | Failed 3x (configurable) → move to DLQ → alert → manual review |255| Max retries | Set explicit limit (default: 3); exponential backoff between attempts |256| Timeout per job | Every job has a max execution time; kill and retry on exceed |257| Visibility timeout | Lock duration > expected execution time; prevent duplicate processing |258| Observability | Emit metrics: queue depth, processing time p95, DLQ size, failure rate |259260**Banned:**261262| Banned | Fix |263|--------|-----|264| Work exceeds the declared request budget or blocks the event loop | Queue, stream, or isolate according to the actual contract |265| Queue without DLQ | Always configure DLQ; alert on DLQ depth > 0 |266| Infinite retries (no max) | Set maxRetries=3 with exponential backoff |267| No idempotency (duplicate jobs on retry) | Idempotency key on every enqueue; dedup in worker |268| No timeout on job execution | Set per-job timeout; kill + mark failed on exceed |269| Polling without backoff (tight loop) | Poll with interval (1-5s) or use blocking pop / push notification |270271---272273## 3. Error Handling274275| Type | HTTP | Log Level |276| -------------- | ---- | ------------- |277| Validation | 400 | warn |278| Authentication | 401 | warn |279| Authorization | 403 | warn |280| Not found | 404 | info |281| Conflict | 409 | warn |282| Rate limit | 429 | info |283| Internal error | 500 | error + stack |284285Follow the repository error convention. A centralized `AppError` class is one option where already selected; distinguish operational from programmer errors.286287### Error Taxonomy (optional AppError hierarchy)288289If the repository chooses AppError, a base class may carry statusCode, code, and isOperational. Do not introduce a parallel hierarchy into an established Result/error model.290291### Result Pattern (conditional)292293Consider the Result/Either pattern (e.g. neverthrow) for recoverable domain errors where explicit error handling improves clarity — adopt it only when the project scope justifies it and the repo doesn't already settle error style (HEURISTIC, not a universal requirement).294295| Library | When to Use |296|---------|-------------|297| **neverthrow** | Default choice — small explicit `Result<T, E>` for recoverable domain errors |298| **Effect** | Only when the app benefits from a full effect runtime: typed errors, retries, resources, concurrency, tracing, service composition |299300Use Result only when selected for this repository. Otherwise propagate errors to a clear handling boundary; do not add wrappers or change public error contracts by preference.301302---303304## 4. Middleware Execution Order305306Apply in this sequence (order matters):3073081. Request ID generation3092. Request logging3103. Security headers (CORS, CSP, HSTS)3114. Rate limiting3125. Authentication3136. Authorization3147. Body parsing3158. Input validation (schema)3169. Route handler31710. Error handler31811. Response logging319320---321322## 5. API Response Contract323324API endpoints should use a **stable response envelope** (DEFAULT) unless the protocol (GraphQL, gRPC, SSE) defines its own or the repo already has a different established contract — follow the existing contract first. Envelope, OTel, health checks, and deployment-readiness checks are production-surface concerns (`jaw-dev` §0.4 shared definition), conditional by project scope, not universal blockers.325326**For APIs that choose this envelope:**327- `success` boolean at top level — never infer from HTTP status alone328- `error.code` is machine-readable (UPPER_SNAKE), `error.message` is human-readable329- `meta.requestId` on every response — enables cross-service tracing330- Pagination uses cursor-based (`after`/`before`) for large datasets, offset-based (`page`/`pageSize`) for admin UIs331- Nullability: prefer consistent key presence; omit when sparse payloads are intentional332- Timestamps: ISO 8601 UTC (`2024-01-15T09:30:00Z`), never Unix epoch in JSON333- Money: integer cents + currency code, never floating point334335See `references/core/api-design.md` for protocol-specific patterns (REST, GraphQL, gRPC, tRPC).336337---338339## 6. Caching Strategy340341**Decision rules:**342- Say **Redis-compatible**, not Redis-only (verified 2026-07-02): prefer **Valkey**343 (Linux Foundation, BSD) for permissive OSS/self-hosted defaults; choose Redis when344 managed-service, module, or license posture justifies it (Redis relicensed 2024;345 Redis 8 added AGPLv3).346- Cache only after correctness is proven on the uncached path.347- Prefer cache-aside by default; use write-through only when strong consistency matters.348- Every key has a namespace, version, stable identifier, TTL, and invalidation trigger.349- Never cache error responses or personalized CDN responses; protect cached PII with encryption and access controls.350- Add stampede protection for hot keys and monitor hit rate, pool exhaustion, and stale-read incidents.351352See `references/core/caching.md` for TTL guidance, Redis-compatible cache patterns, CDN rules, invalidation triggers, connection pooling, and code examples.353354---355356## 7. Observability (OpenTelemetry)357358**Decision rules:**359- Production services emit traces, metrics, and structured JSON logs with `requestId`, `traceId`, and `spanId`.360- **OTel maturity (verified 2026-07-02):** traces and metrics are Stable in JS/Python;361 **logs are still Development** — the baseline is trace/span-correlated structured362 logs + OTel traces/metrics; adopt OTel Logs export only where that maturity is acceptable.363- Start with OTel auto-instrumentation, then add custom spans only for business-critical or non-instrumented work.364- Never log PII, secrets, full request/response bodies, or noisy stack traces outside error boundaries.365- Page only on customer-impacting signals tied to SLOs; use warning alerts for capacity trends.366367See `references/core/observability.md` for OTel setup, structured logging conventions, trace propagation, dashboards, RUM correlation, and alerting guidance.368369---370371## 8. Skeleton Project Evaluation372373When starting from a template or boilerplate, verify before building on top:374375| Check | What to Verify |376|-------|---------------|377| Dependencies | Up-to-date? CVEs? Unnecessary packages? |378| Architecture fit | Does the template's structure match your actual needs? |379| Auth/security | Is the auth pattern appropriate for your use case? |380| Database | Is the ORM/query builder suitable for your data model? |381| Dead code | Remove unused example routes, models, and middleware |382| Config management | Environment-based config, no hardcoded values |383384Treat templates as starting points, not gospel. Strip to essentials, then add what you need.385386---387388## 9. API Performance Targets (HEURISTIC defaults, not universal SLOs)389390These are aggressive healthy-service starting budgets. Each product MUST define its own391SLOs from user journeys and alert on error-budget burn, not raw percentile thresholds392alone (Google SRE SLO practice; see observability.md Sources).393394| Metric | Default budget | Escalation |395|--------|--------|-----------|396| p50 response time (reads) | ≤ 50ms | Profile with tracing |397| p95 response time (reads) | ≤ 200ms, alert at >500ms (see observability.md) | Optimization target |398| p95 response time (writes) | ≤ 500ms | Acceptable for complex writes |399| p99 response time | ≤ 1000ms | Investigate outliers |400| Error rate | < 0.1% target, alert at >1% (see observability.md) | Optimization target |401402- Measure at the handler level, not including network403- Use `Server-Timing` header to expose backend timing to frontend404- Log slow queries (> 100ms) with EXPLAIN output405- Connection pool (long-running servers): min = CPU cores, max = CPU cores × 4; for serverless/Lambda use min = 0–2406407API responses that drive UI must include descriptive error messages (not just codes) for screen reader announcement, pagination metadata (total count) for assistive technology, and `Content-Language` header matching response body language.408409## 10. SEO Support Endpoints410411When the app serves web pages (SSR/SSG):412- `GET /sitemap.xml` — dynamic sitemap generation with `<lastmod>`413- `GET /robots.txt` — configurable per-environment (disallow staging/preview)414- Structured data: provide JSON-LD data in API responses when frontend needs it415- Redirect chains: max 1 hop (301 for permanent, 308 for POST-preserving)416417## 11. Deployment Patterns418419- Blue-green: deploy to inactive environment, verify health + smoke tests, swap traffic420- Canary: route 5% → 25% → 100% with automated rollback on error rate spike421- Rollback: always keep previous version deployed and ready to swap back422- Database migrations: separate from code deploy, backward-compatible (expand-then-contract)423- Feature flags: use for gradual rollout of risky changes424425---426427## 12. Pre-Flight Checklist428429- Analytical data / ETL / pipeline quality: load `jaw-dev-data`.430- API consumer context / frontend contract alignment: load `jaw-dev-frontend`.431- Test strategy / verification harnesses / QA execution: load `jaw-dev-testing`.432- Backend failure RCA methodology: load `jaw-dev-debugging`.433- New project setup / file placement conventions: load `jaw-dev-scaffolding`.434435Before delivering:436- [ ] Existing/protocol response contract preserved; shared envelope only where applicable (§5)437- [ ] Input validation with schema (Zod, Pydantic, etc.)438- [ ] Authentication middleware on protected routes439- [ ] Rate limiting on public endpoints440- [ ] Structured JSON logging with `requestId` and `traceId`441- [ ] Error handler preserves the repository error convention and correct HTTP mapping; AppError is optional442- [ ] No raw SQL in service layer443- [ ] No hardcoded secrets444- [ ] Migrations have rollback445- [ ] Observability: traces and structured logs wired (see `references/core/observability.md`)446- [ ] Health endpoints: `/health` (liveness) and `/ready` (readiness) — see `references/core/health-checks.md`447- [ ] API performance: p95 reads ≤ 200ms, slow queries logged with EXPLAIN (§9)448- [ ] SEO endpoints: sitemap.xml + robots.txt if serving web pages (§10)449- [ ] Security review: delegate to `jaw-dev-security/SKILL.md` for production readiness450- [ ] Stack-specific rules followed (see `references/stacks/`)