Philosophy: The Backend is the Fortress. Logic is Law. Latency is the Enemy.
Core Principle: ISOLATE features. TRUST no one. SCALE linearly.
ANTI-HAPPY PATH MANDATE (CRITICAL): Never assume the ideal scenario. AI-generated code often fails by ignoring edge cases and failure modes. For every business logic slice, you MUST document and test at least three failure scenarios: Race Conditions, Data Integrity violations (e.g., unique constraint overlaps), and Boundary failures. Reject any implementation that only covers the 'Happy Path'. Engineering is the art of handling what shouldn't happen.
0. The "Vertical Slice" Law (The Anti-Layer Mandate)
CRITICAL: You are FORBIDDEN from creating "Horizontal Layers" (Controllers, Services, Repositories) as primary folders.
The "Feature-First" Protocol:
Code must be organized by BUSINESS CAPABILITY, not technical role.
- The Slice: A single directory (e.g.,
features/create-order/) contains EVERYTHING needed for that feature:
handler.ts (Controller)
logic.ts (Domain/Service)
schema.ts (DTO/Validation)
db.ts (Data Access)
- The Benefit: Changing a feature requires touching only ONE folder. No "Shotgun Surgery" across 5 layers.
- Shared Kernel: Only truly generic code (Logging, Auth Middleware, Database Connection) goes into
shared/.
1. The "Modular Monolith" Mandate
- Microservices Ban: Do NOT start with microservices. Start with a Modular Monolith.
- Modulith Rules:
- Modules must be isolated (like internal microservices).
- Modules communicate via Events (Sub-Process or Message Bus), NEVER by importing another module's code directly.
- The Outbox Pattern (Guaranteed Delivery):
- Problem: If DB commit succeeds but Event Bus fails, the system is inconsistent.
- Mandate: Write events to an
outbox table in the SAME transaction as the data change.
- Relay: A background worker pushes
outbox entries to the Message Bus (RabbitMQ/Kafka).
- Data Sovereignty: Module A cannot query Module B's tables. It must ask Module B via API/Event.
2. The "Zero Trust" Security Protocol
Detailed protocols: See security-protocols.md
Quick Rules:
- Strict Serialization: NEVER return raw DB entities → Use ResponseDTO
- Validation at Gate: Schema validation (Zod/Pydantic) BEFORE logic
- Token Sovereignty: PASETO v4 > JWT (Ed25519 if JWT forced)
3. The "Sub-100ms" Performance Mandate
- The Latency Budget: P50 < 100ms. P99 < 500ms.
- UUIDv7 (The Time-Lord Rule):
- Ban: Never use
UUIDv4 (Random) for Primary Keys. It fragments B-Tree indexes.
- Mandate: Use UUIDv7 (Time-ordered). It enables clustered index locality (fast inserts) like integers, with the uniqueness of UUIDs.
- N+1 Assassin:
- Check: Always inspect ORM queries. Loops triggering DB calls are a "Level 0" error.
- Fix: Use
DataLoader pattern or explicit JOIN loading.
4. API Reliability Contracts
- RFC 7807 (Problem Details):
- Ban: returning
{ "error": "Something went wrong" }.
- Mandate: Return standard Problem JSON:
{
"type": "https://api.myapp.com/errors/insufficient-funds",
"title": "Insufficient Funds",
"status": 403,
"detail": "Current balance is 10.00, required is 15.00",
"instance": "/transactions/12345"
}
- Idempotency Keys:
- Rule: All critical
POST/PATCH (Money, State Change) must accept an Idempotency-Key header.
- Logic: If key exists in Cache (24h TTL), return stored response without re-executing logic.
5. Database Integrity & Design
- Hard Constraints: Application-level checks are "Suggestions". Database Constraints (Foreign Keys, Unique Indexes, Check Constraints) are "Laws".
- Cursor Pagination:
- Ban:
OFFSET / LIMIT on large tables (O(N) performance degradation).
- Mandate: Cursor-based pagination (
WHERE created_at < cursor LIMIT 20).
- Migration Discipline:
- Never alter a column in a way that locks the table for >1s.
- Use "Expand and Contract" pattern for breaking changes.
- Concurrency Control:
- Problem: Two users update the same record. The last one wipes the first.
- Mandate: Use Optimistic Locking. Add a
version (int) column.
- Logic: Update WHERE
id = X AND version = Y. If 0 rows affected, throw StaleObjectException.
6. AI & Vector Readiness
- Semantic Storage: Backend must be ready to store embeddings (Vector Types).
- Guardrails: Output from LLMs must be sanitized and structure-checked on the server side before returning to frontend.
7. Structured Logging Only
- Ban:
console.log("User updated"). String logs are useless for machines.
- *Mandate: JSON Logs with correlation IDs.
{ "level": "info", "event": "user_updated", "user_id": "u7-...", "trace_id": "..." }.
8. Distributed Tracing (OpenTelemetry)
- Every request MUST carry a
traceparent header.
- Spans must cover: DB Queries, External API Calls, and Redis operations.
9. Health Checks
- Liveness (
/health/live): "Am I running?" (Instant, no checks).
- Readiness (
/health/ready): "Can I take traffic?" (Check DB/Redis connection).
10. Circuit Breakers
- Wrap ALL external calls (Payment Gateways, 3rd Party APIs) in a Circuit Breaker.
- Logic: After 5 failures, fail fast for 30s. Don't drown the downstream service.
11. Rate Limiting
- Protect every public endpoint with a Token Bucket rate limiter (Redis-backed).
- Differentiate limits by User Role (Anon: 60/min, Pro: 1000/min).
1. The Pre-Flight Checklist
- Environment Hardening:
- Verify all
process.env variables at startup using a schema (e.g., t3-env or envalid). If a key is missing, crash immediately. Do not start the server in an undefined state.
Before writing a single handler:
- Define the DTOs: Request Schema (Zod) and Response Schema.
- Define the Error States: What can go wrong? (404, 409, 429).
- Define the Data Access: What is the most efficient SQL query?
2. The "No Magic" Rule
- Avoid "Magical" ORM features (Lazy Loading, Auto-Saving context).
- Prefer Explicit over Implicit. "Write the SQL (or Query Builder) if the ORM hides expensive logic."
3. Testing Pyramid
- Unit: Test Domain Logic in isolation (mock DB).
- Integration: Test Feature Slice with a REAL containerized DB (Testcontainers).
- E2E: Test critical flows from the "Outside".
🔗 CROSS-SKILL INTEGRATION
| Skill |
Backend Adds... |
@frontend-design |
API contracts, CORS config, error responses |
@clean-code |
Input validation, no raw SQL, dependency security |
@tdd-mastery |
Integration tests with Testcontainers |
@planning-mastery |
API endpoint task breakdown |
@debug-mastery |
Structured logging, distributed tracing |
Command: Use these skills to architect "Fortress-Level" backend systems.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: backend-design-23description: Elite Tier Backend standards, including Vertical Slice Architecture, Zero Trust Security, and High-Performance API protocols. Use when this capability is needed.4---56<domain_overview>7# Backend Design System89> **Philosophy:** The Backend is the Fortress. Logic is Law. Latency is the Enemy.10> **Core Principle:** ISOLATE features. TRUST no one. SCALE linearly.1112**ANTI-HAPPY PATH MANDATE (CRITICAL):** Never assume the ideal scenario. AI-generated code often fails by ignoring edge cases and failure modes. For every business logic slice, you MUST document and test at least three failure scenarios: Race Conditions, Data Integrity violations (e.g., unique constraint overlaps), and Boundary failures. Reject any implementation that only covers the 'Happy Path'. Engineering is the art of handling what shouldn't happen.13</domain_overview>1415<architectural_protocols>16## 🚀 ELITE TIER KNOWLEDGE (ARCHITECTURAL PROTOCOLS)1718### 0. The "Vertical Slice" Law (The Anti-Layer Mandate)19> **CRITICAL:** You are FORBIDDEN from creating "Horizontal Layers" (Controllers, Services, Repositories) as primary folders.2021**The "Feature-First" Protocol:**22Code must be organized by **BUSINESS CAPABILITY**, not technical role.231. **The Slice:** A single directory (e.g., `features/create-order/`) contains EVERYTHING needed for that feature:24 * `handler.ts` (Controller)25 * `logic.ts` (Domain/Service)26 * `schema.ts` (DTO/Validation)27 * `db.ts` (Data Access)282. **The Benefit:** Changing a feature requires touching only ONE folder. No "Shotgun Surgery" across 5 layers.293. **Shared Kernel:** Only truly generic code (Logging, Auth Middleware, Database Connection) goes into `shared/`.3031### 1. The "Modular Monolith" Mandate32* **Microservices Ban:** Do NOT start with microservices. Start with a **Modular Monolith**.33* **Modulith Rules:**34 * Modules must be isolated (like internal microservices).35 * Modules communicate via **Events** (Sub-Process or Message Bus), NEVER by importing another module's code directly.36 * **The Outbox Pattern (Guaranteed Delivery):**37 * *Problem:* If DB commit succeeds but Event Bus fails, the system is inconsistent.38 * *Mandate:* Write events to an `outbox` table in the SAME transaction as the data change.39 * *Relay:* A background worker pushes `outbox` entries to the Message Bus (RabbitMQ/Kafka).40 * Data Sovereignty: Module A cannot query Module B's tables. It must ask Module B via API/Event.4142### 2. The "Zero Trust" Security Protocol43> **Detailed protocols:** See [security-protocols.md](security-protocols.md)4445**Quick Rules:**461. **Strict Serialization:** NEVER return raw DB entities → Use ResponseDTO472. **Validation at Gate:** Schema validation (Zod/Pydantic) BEFORE logic483. **Token Sovereignty:** PASETO v4 > JWT (Ed25519 if JWT forced)49</architectural_protocols>5051<reliability_contracts>52## 🏗️ Reliability & Performance Contracts5354### 3. The "Sub-100ms" Performance Mandate55* **The Latency Budget:** P50 < 100ms. P99 < 500ms.56* **UUIDv7 (The Time-Lord Rule):**57 * *Ban:* Never use `UUIDv4` (Random) for Primary Keys. It fragments B-Tree indexes.58 * *Mandate:* Use **UUIDv7** (Time-ordered). It enables clustered index locality (fast inserts) like integers, with the uniqueness of UUIDs.59* **N+1 Assassin:**60 * *Check:* Always inspect ORM queries. Loops triggering DB calls are a "Level 0" error.61 * *Fix:* Use `DataLoader` pattern or explicit `JOIN` loading.6263### 4. API Reliability Contracts64* **RFC 7807 (Problem Details):**65 * *Ban:* returning `{ "error": "Something went wrong" }`.66 * *Mandate:* Return standard Problem JSON:67 ```json68 {69 "type": "https://api.myapp.com/errors/insufficient-funds",70 "title": "Insufficient Funds",71 "status": 403,72 "detail": "Current balance is 10.00, required is 15.00",73 "instance": "/transactions/12345"74 }75 ```76* **Idempotency Keys:**77 * *Rule:* All critical `POST/PATCH` (Money, State Change) must accept an `Idempotency-Key` header.78 * *Logic:* If key exists in Cache (24h TTL), return stored response without re-executing logic.79</reliability_contracts>8081<database_integrity>82## 🗄️ Database Integrity & Design8384### 5. Database Integrity & Design85* **Hard Constraints:** Application-level checks are "Suggestions". Database Constraints (Foreign Keys, Unique Indexes, Check Constraints) are "Laws".86* **Cursor Pagination:**87 * *Ban:* `OFFSET / LIMIT` on large tables (O(N) performance degradation).88 * *Mandate:* Cursor-based pagination (`WHERE created_at < cursor LIMIT 20`).89* **Migration Discipline:**90 * Never alter a column in a way that locks the table for >1s.91 * Use "Expand and Contract" pattern for breaking changes.92* **Concurrency Control:**93 * *Problem:* Two users update the same record. The last one wipes the first.94 * *Mandate:* Use Optimistic Locking. Add a `version` (int) column.95 * *Logic:* Update WHERE `id` = X AND `version` = Y. If 0 rows affected, throw `StaleObjectException`.9697### 6. AI & Vector Readiness98* **Semantic Storage:** Backend must be ready to store embeddings (Vector Types).99* **Guardrails:** Output from LLMs must be sanitized and structure-checked on the server side before returning to frontend.100</database_integrity>101102<observability>103## 👁️ Observability & Monitoring (The "Glass Box" Protocol)104105### 7. Structured Logging Only106* **Ban:** `console.log("User updated")`. String logs are useless for machines.107* **Mandate:* JSON Logs with correlation IDs. `{ "level": "info", "event": "user_updated", "user_id": "u7-...", "trace_id": "..." }`.108109### 8. Distributed Tracing (OpenTelemetry)110* Every request MUST carry a `traceparent` header.111* Spans must cover: DB Queries, External API Calls, and Redis operations.112113### 9. Health Checks114* Liveness (`/health/live`): "Am I running?" (Instant, no checks).115* Readiness (`/health/ready`): "Can I take traffic?" (Check DB/Redis connection).116</observability>117118<resilience>119## 🛡️ Resilience Patterns (The "Anti-Fragile" Mandate)120121### 10. Circuit Breakers122* Wrap ALL external calls (Payment Gateways, 3rd Party APIs) in a Circuit Breaker.123* *Logic:* After 5 failures, fail fast for 30s. Don't drown the downstream service.124125### 11. Rate Limiting126* Protect *every* public endpoint with a Token Bucket rate limiter (Redis-backed).127* Differentiate limits by User Role (Anon: 60/min, Pro: 1000/min).128</resilience>129130<workflow_rules>131## 🔧 Workflow Rules132133### 1. The Pre-Flight Checklist1340. **Environment Hardening:**135 * Verify all `process.env` variables at startup using a schema (e.g., `t3-env` or `envalid`). If a key is missing, crash immediately. Do not start the server in an undefined state.136Before writing a single handler:1371. **Define the DTOs:** Request Schema (Zod) and Response Schema.1382. **Define the Error States:** What can go wrong? (404, 409, 429).1393. **Define the Data Access:** What is the most efficient SQL query?140141### 2. The "No Magic" Rule142* Avoid "Magical" ORM features (Lazy Loading, Auto-Saving context).143* Prefer Explicit over Implicit. "Write the SQL (or Query Builder) if the ORM hides expensive logic."144145### 3. Testing Pyramid1461. **Unit:** Test Domain Logic in isolation (mock DB).1472. **Integration:** Test Feature Slice with a REAL containerized DB (Testcontainers).1483. **E2E:** Test critical flows from the "Outside".149</workflow_rules>150151<audit_and_reference>152## 📂 Cognitive Audit Cycle153Before committing code:1541. **Is the endpoint under a feature slice?** (Not in a generic controller folder).1552. **Is Input Validated with a Schema?** (Zero Trust).1563. **Are DB Indexes used?** (Run `EXPLAIN ANALYZE`).1574. **Is the Primary Key UUIDv7?** (Index Perf).1585. **Are secrets managed properly?** (No hardcoded strings).159160---161162## 🔗 CROSS-SKILL INTEGRATION163164| Skill | Backend Adds... |165|-------|-----------------|166| `@frontend-design` | API contracts, CORS config, error responses |167| `@clean-code` | Input validation, no raw SQL, dependency security |168| `@tdd-mastery` | Integration tests with Testcontainers |169| `@planning-mastery` | API endpoint task breakdown |170| `@debug-mastery` | Structured logging, distributed tracing |171172> **Command:** Use these skills to architect "Fortress-Level" backend systems.173</audit_and_reference>174175---176> Converted and distributed by [TomeVault](https://tomevault.io/claim/xenitv1) — claim your Tome and manage your conversions.177<!-- tomevault:4.0:skill_md:2026-04-11 -->