senior-backend
alirezarezvani/claude-skills
設計並實作後端系統,包括 REST API、微服務、資料庫架構、驗證流程及安全性強化措施。涵蓋 Node.js/Express/Fastify 開發、PostgreSQL 優化、API 安全性,以及後端架構模式。
...展開全部資深後端工程師
後端開發模式、API 設計、資料庫優化及資安實務。
快速入門
# Generate API routes from OpenAPI spec
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
# Analyze database schema and generate migrations
python scripts/database_migration_tool.py --connection postgres://localhost/mydb --analyze
# Load test an API endpoint
python scripts/api_load_tester.py https://api.example.com/users --concurrency 50 --duration 30
工具概覽
1. API 框架生成器
根據資料結構定義,自動產生 API 路由處理常式、中介軟體及 OpenAPI 規格。
輸入:OpenAPI 規格(YAML/JSON)或資料庫資料結構 輸出:路由處理程序、驗證中介軟體、TypeScript 類型
使用方法:
# Generate Express routes from OpenAPI spec
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
# Output: Generated 12 route handlers, validation middleware, and TypeScript types
# Generate from database schema
python scripts/api_scaffolder.py --from-db postgres://localhost/mydb --output src/routes/
# Generate OpenAPI spec from existing routes
python scripts/api_scaffolder.py src/routes/ --generate-spec --output openapi.yaml
支援的框架:
- Express.js (
--framework express) - Fastify (
--framework fastify) - Koa (
--framework koa)
2. 資料庫遷移工具
分析資料庫結構、偵測變更,並產生支援回滾功能的遷移檔案。
輸入:資料庫連線字串或結構檔案 輸出:遷移檔案、結構差異報告、優化建議
用法:
# Analyze current schema and suggest optimizations
python scripts/database_migration_tool.py --connection postgres://localhost/mydb --analyze
# Output: Missing indexes, N+1 query risks, and suggested migration files
# Generate migration from schema diff
python scripts/database_migration_tool.py --connection postgres://localhost/mydb \
--compare schema/v2.sql --output migrations/
# Dry-run a migration
python scripts/database_migration_tool.py --connection postgres://localhost/mydb \
--migrate migrations/20240115_add_user_indexes.sql --dry-run
3. API 負載測試工具
執行 HTTP 負載測試,可配置並發數,並測量延遲百分位數與吞吐量。
輸入:API 端點 URL 及測試設定 輸出:包含延遲分位數、錯誤率及吞吐量指標的效能報告
使用方式:
# Basic load test
python scripts/api_load_tester.py https://api.example.com/users --concurrency 50 --duration 30
# Output: Throughput (req/sec), latency percentiles (P50/P95/P99), error counts, and scaling recommendations
# Test with custom headers and body
python scripts/api_load_tester.py https://api.example.com/orders \
--method POST \
--header "Authorization: Bearer token123" \
--body '{"product_id": 1, "quantity": 2}' \
--concurrency 100 \
--duration 60
# Compare two endpoints
python scripts/api_load_tester.py https://api.example.com/v1/users https://api.example.com/v2/users \
--compare --concurrency 50 --duration 30
後端開發工作流程
API 設計工作流程
適用於設計新 API 或重構現有端點時。
步驟 1:定義資源與操作
# openapi.yaml
openapi: 3.0.3
info:
title: User Service API
version: 1.0.0
paths:
/users:
get:
summary: List users
parameters:
- name: "limit"
in: query
schema:
type: integer
default: 20
post:
summary: Create user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUser'
步驟 2:產生路由骨架
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
步驟 3:實作業務邏輯
// src/routes/users.ts (generated, then customized)
export const createUser = async (req: Request, res: Response) => {
const { email, name } = req.body;
// Add business logic
const user = await userService.create({ email, name });
res.status(201).json(user);
};
步驟 4:新增驗證中介軟體
# Validation is auto-generated from OpenAPI schema
# src/middleware/validators.ts includes:
# - Request body validation
# - Query parameter validation
# - Path parameter validation
步驟 5:產生更新的 OpenAPI 規格
python scripts/api_scaffolder.py src/routes/ --generate-spec --output openapi.yaml
資料庫優化工作流程
適用於查詢速度緩慢或需提升資料庫效能的情況。
步驟 1:分析當前效能
python scripts/database_migration_tool.py --connection $DATABASE_URL --analyze
步驟 2:識別慢查詢
-- Check query execution plans
EXPLAIN ANALYZE SELECT * FROM orders
WHERE user_id = 123
ORDER BY created_at DESC
LIMIT 10;
-- Look for: Seq Scan (bad), Index Scan (good)
步驟 3:產生索引遷移方案
python scripts/database_migration_tool.py --connection $DATABASE_URL \
--suggest-indexes --output migrations/
步驟 4:測試遷移(模擬執行)
python scripts/database_migration_tool.py --connection $DATABASE_URL \
--migrate migrations/add_indexes.sql --dry-run
步驟 5:套用並驗證
# Apply migration
python scripts/database_migration_tool.py --connection $DATABASE_URL \
--migrate migrations/add_indexes.sql
# Verify improvement
python scripts/database_migration_tool.py --connection $DATABASE_URL --analyze
安全性強化工作流程
適用於將 API 準備投入生產環境,或於安全審查完成後。
步驟 1:檢視身份驗證設定
// Verify JWT configuration
const jwtConfig = {
secret: process.env.JWT_SECRET, // Must be from env, never hardcoded
expiresIn: '1h', // Short-lived tokens
algorithm: 'RS256' // Prefer asymmetric
};
步驟 2:新增速率限制
import rateLimit from 'express-rate-limit';
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', apiLimiter);
步驟 3:驗證所有輸入資料
import { z } from 'zod';
const CreateUserSchema = z.object({
email: z.string().email().max(255),
name: z.string().min(1).max(100),
age: z.number().int().positive().optional()
});
// Use in route handler
const data = CreateUserSchema.parse(req.body);
步驟 4:使用攻擊模式進行負載測試
# Test rate limiting
python scripts/api_load_tester.py https://api.example.com/login \
--concurrency 200 --duration 10 --expect-rate-limit
# Test input validation
python scripts/api_load_tester.py https://api.example.com/users \
--method POST \
--body '{"email": "not-an-email"}' \
--expect-status 400
步驟 5:檢視安全性標頭
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: true,
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: true,
crossOriginResourcePolicy: true,
hsts: { maxAge: 31536000, includeSubDomains: true },
}));
參考文件
| 檔案 | 包含 | 適用於 |
|---|---|---|
references/api_design_patterns.md |
REST 與 GraphQL 的比較、版本控制、錯誤處理、分頁 | 設計新 API |
references/database_optimization_guide.md |
索引策略、查詢優化、N+1 問題的解決方案 | 修復緩慢的查詢 |
references/backend_security_practices.md |
OWASP 前 10 大風險、授權模式、輸入驗證 | 安全性強化 |
常見模式快速參考
REST API 回應格式
{
"data": { "id": 1, "name": "John" },
"meta": { "requestId": "abc-123" }
}
錯誤回應格式
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid email format",
"details": [{ "field": "email", "message": "must be valid email" }]
},
"meta": { "requestId": "abc-123" }
}
HTTP 狀態碼
| 代碼 | 用例 |
|---|---|
| 200 | 成功 (GET、PUT、PATCH) |
| 201 | 已建立 (POST) |
| 204 | 無內容 (DELETE) |
| 400 | 驗證錯誤 |
| 401 | 需要驗證 |
| 403 | 權限遭拒絕 |
| 404 | 找不到資源 |
| 429 | 超出速率限制 |
| 500 | 內部伺服器錯誤 |
資料庫索引策略
-- Single column (equality lookups)
CREATE INDEX idx_users_email ON users(email);
-- Composite (multi-column queries)
CREATE INDEX idx_orders_user_status ON orders(user_id, status);
-- Partial (filtered queries)
CREATE INDEX idx_orders_active ON orders(created_at) WHERE status = 'active';
-- Covering (avoid table lookup)
CREATE INDEX idx_users_email_name ON users(email) INCLUDE (name);
常用指令
# API Development
python scripts/api_scaffolder.py openapi.yaml --framework express
python scripts/api_scaffolder.py src/routes/ --generate-spec
# Database Operations
python scripts/database_migration_tool.py --connection $DATABASE_URL --analyze
python scripts/database_migration_tool.py --connection $DATABASE_URL --migrate file.sql
# Performance Testing
python scripts/api_load_tester.py https://api.example.com/endpoint --concurrency 50
python scripts/api_load_tester.py https://api.example.com/endpoint --compare baseline.json
假設與可驗證的成功準則(卡帕西原則)
在該技能進行架構引導、建議模式或修改資料庫結構之前,必須先釐清以下四項假設。若其中任何一項未知,該技能將停止執行,並改為引導使用者瀏覽「強制提問」資料庫。
- 讀寫比例 + 一年期 p99 QPS — 決定資料庫、快取、佇列及分區的選項。Kleppmann, DDIA (2017)。
- 租戶模型 — 單租戶、共用多租戶、隔離多租戶。此決定將主導資料存取模式。
- 資料敏感度層級 — 公開/內部/個人識別資訊(PII)/受保護健康資訊(PHI)/支付卡產業(PCI)。決定合規性的最低門檻。
- 服務水準目標(SLO)+指定錯誤預算的消費者 —— Google SRE 工作手冊的經典準則。無 SLO 即無法為可靠性工作設定優先順序。
可驗證的成功準則(Karpathy 第 4 條)——本技能所產出的每項建議都必須包含:
- 延遲目標(p50、p95、p99,單位:毫秒)
- 正常運作時間/SLO 目標
- RPO + RTO
若上述三項中有任何一項未被明確說明,則該建議不完整 — 請返回「強制提問庫」的第 7 題。
該 scripts/backend_decision_engine.py 工具會將這些檢查條件編碼:若未提供讀寫比例、QPS、租戶數、資料敏感度及模式偏好,該工具將拒絕建議任何設定檔。
自訂設定檔
在 profiles/ 會校準每項建議:
| 設定檔 | 何時選用 | 模式 | 延遲下限 (p99) |
|---|---|---|---|
node-express |
TS 團隊,工程師少於 15 人,面向客戶的 SaaS | 基於 Postgres 的模組化單體架構 | 600 毫秒 |
fastapi-python |
Python 團隊,少於 20 名工程師,與機器學習相關 | 基於 Postgres 的模組化單體架構(非同步) | 500 毫秒 |
django-monolith |
內容密集型 CRUD + 管理後台,工程師少於 25 人 | 基於 Postgres 的模組化單體架構 | 800 毫秒 |
go-or-rust-microservice |
拆分服務,≥ 30 名工程師,平台團隊,QPS ≥ 1000 | 拆分服務 | 200 毫秒 |
透過以下方式選擇配置檔:
python scripts/backend_decision_engine.py \
--team-size 8 --qps-p99 50 --read-write-ratio 20 \
--tenancy shared-multi-tenant --data-sensitivity pii \
--pattern modular-monolith --language-preference typescript
該工具會回傳最適合的配置檔、次佳折衷方案(若差距在 15% 內)、技術堆疊選項、反模式、指定審核者以及 SLO 下限。此工具絕不會自動核准。
若要新增自訂配置檔:請複製 profiles/node-express.json 至 profiles/ 並調整 constraints + success_thresholds + named_approver_chain.
組合映射
此技能並不會重新實作由「POWERFUL」級專家所管轄的範圍。它會分支出這些專家。請參閱 references/composition_map.md 以查看完整的路由表。主要分支:
| 關注 | 分支至 |
|---|---|
| API 合約 / 破壞性變更風險 | engineering/skills/api-design-reviewer/ |
| 模式設計 + 實體關係圖 (ERD) + 索引設定 | engineering/skills/database-designer/ |
| 零停機時間的資料結構遷移 | engineering/skills/migration-architect/ |
| 服務水準目標 (SLO) + 服務指標 (SLI) + 錯誤預算 | engineering/slo-architect/ |
| 可觀測性/黃金訊號 | engineering/skills/observability-designer/ |
| CI/CD 管道 | engineering/skills/ci-cd-pipeline-builder/ |
| 安全性/威脅模型 | engineering-team/skills/senior-security/, adversarial-reviewer |
| 合規證明(HIPAA / ISO 27001) | ra-qm-team/ |
| 提交前 Karpathy 審查 | engineering/karpathy-coder/ |
| 部署前架構詳盡審查 | engineering/grill-me/ |
該 cs-backend-engineer 代理程式透過 context: fork。可透過 Agent({subagent_type: "cs-backend-engineer", prompt: "..."}) ,或透過 /cs:backend-review .
強制提問函式庫(Matt Pocock grill)
在確定任何後端決策之前,請依序檢視 references/forcing_questions.md。規範:
- 每回合僅提一個問題。不得合併提問。
- 回答時務必引用正典作為依據。
- 請在
/tmp/backend-grill-..md - 若觸發「終止條件」,請立即停止。切勿為未解決的漏洞編造解釋。
- 在第7題之後,執行
backend_decision_engine.py這七個答案進行遊戲。
摘要:
- 讀寫比例 + p99 QPS 預測?
- 租戶模型 — 單一/共享/隔離?
- 同步/非同步/事件驅動 — 預設值 + 例外情況?
- 資料敏感度等級 — 個人識別資訊 (PII) / 個人健康資訊 (PHI) / 支付卡產業資料安全標準 (PCI)?
- 單體架構/模組化單體/微服務 — 團隊規模的考量依據?
- RPO + RTO?
- 服務水準目標(SLO)+指定錯誤預算的消費者?
來自其他代理程式與技能的呼叫
三個介面:
- 斜線指令:
/cs:backend-review— 完整查詢介面 + 決策引擎 + 組合路由。 - 代理子代理:
Agent({subagent_type: "cs-backend-engineer", prompt: "..."})— 複製上下文,返回 ≤ 200 字的摘要。 - 直接工具呼叫:
python scripts/backend_decision_engine.py ...— 當輸入已知時,進行確定性特徵檔案比對。
請參閱 agents/engineering/cs-backend-engineer.md 以查看完整的呼叫合約。
---
name: senior-backend
description: Designs and implements backend systems including REST APIs, microservices, database architectures, authentication flows, and security hardening. Covers Node.js/Express/Fastify development, PostgreSQL optimization, API security, and backend architecture patterns.
---
# Senior Backend Engineer
Backend development patterns, API design, database optimization, and security practices.
---
## Quick Start
```bash
# Generate API routes from OpenAPI spec
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
# Analyze database schema and generate migrations
python scripts/database_migration_tool.py --connection postgres://localhost/mydb --analyze
# Load test an API endpoint
python scripts/api_load_tester.py https://api.example.com/users --concurrency 50 --duration 30
```
---
## Tools Overview
### 1. API Scaffolder
Generates API route handlers, middleware, and OpenAPI specifications from schema definitions.
**Input:** OpenAPI spec (YAML/JSON) or database schema
**Output:** Route handlers, validation middleware, TypeScript types
**Usage:**
```bash
# Generate Express routes from OpenAPI spec
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
# Output: Generated 12 route handlers, validation middleware, and TypeScript types
# Generate from database schema
python scripts/api_scaffolder.py --from-db postgres://localhost/mydb --output src/routes/
# Generate OpenAPI spec from existing routes
python scripts/api_scaffolder.py src/routes/ --generate-spec --output openapi.yaml
```
**Supported Frameworks:**
- Express.js (`--framework express`)
- Fastify (`--framework fastify`)
- Koa (`--framework koa`)
---
### 2. Database Migration Tool
Analyzes database schemas, detects changes, and generates migration files with rollback support.
**Input:** Database connection string or schema files
**Output:** Migration files, schema diff report, optimization suggestions
**Usage:**
```bash
# Analyze current schema and suggest optimizations
python scripts/database_migration_tool.py --connection postgres://localhost/mydb --analyze
# Output: Missing indexes, N+1 query risks, and suggested migration files
# Generate migration from schema diff
python scripts/database_migration_tool.py --connection postgres://localhost/mydb \
--compare schema/v2.sql --output migrations/
# Dry-run a migration
python scripts/database_migration_tool.py --connection postgres://localhost/mydb \
--migrate migrations/20240115_add_user_indexes.sql --dry-run
```
---
### 3. API Load Tester
Performs HTTP load testing with configurable concurrency, measuring latency percentiles and throughput.
**Input:** API endpoint URL and test configuration
**Output:** Performance report with latency distribution, error rates, throughput metrics
**Usage:**
```bash
# Basic load test
python scripts/api_load_tester.py https://api.example.com/users --concurrency 50 --duration 30
# Output: Throughput (req/sec), latency percentiles (P50/P95/P99), error counts, and scaling recommendations
# Test with custom headers and body
python scripts/api_load_tester.py https://api.example.com/orders \
--method POST \
--header "Authorization: Bearer token123" \
--body '{"product_id": 1, "quantity": 2}' \
--concurrency 100 \
--duration 60
# Compare two endpoints
python scripts/api_load_tester.py https://api.example.com/v1/users https://api.example.com/v2/users \
--compare --concurrency 50 --duration 30
```
---
## Backend Development Workflows
### API Design Workflow
Use when designing a new API or refactoring existing endpoints.
**Step 1: Define resources and operations**
```yaml
# openapi.yaml
openapi: 3.0.3
info:
title: User Service API
version: 1.0.0
paths:
/users:
get:
summary: List users
parameters:
- name: "limit"
in: query
schema:
type: integer
default: 20
post:
summary: Create user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUser'
```
**Step 2: Generate route scaffolding**
```bash
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
```
**Step 3: Implement business logic**
```typescript
// src/routes/users.ts (generated, then customized)
export const createUser = async (req: Request, res: Response) => {
const { email, name } = req.body;
// Add business logic
const user = await userService.create({ email, name });
res.status(201).json(user);
};
```
**Step 4: Add validation middleware**
```bash
# Validation is auto-generated from OpenAPI schema
# src/middleware/validators.ts includes:
# - Request body validation
# - Query parameter validation
# - Path parameter validation
```
**Step 5: Generate updated OpenAPI spec**
```bash
python scripts/api_scaffolder.py src/routes/ --generate-spec --output openapi.yaml
```
---
### Database Optimization Workflow
Use when queries are slow or database performance needs improvement.
**Step 1: Analyze current performance**
```bash
python scripts/database_migration_tool.py --connection $DATABASE_URL --analyze
```
**Step 2: Identify slow queries**
```sql
-- Check query execution plans
EXPLAIN ANALYZE SELECT * FROM orders
WHERE user_id = 123
ORDER BY created_at DESC
LIMIT 10;
-- Look for: Seq Scan (bad), Index Scan (good)
```
**Step 3: Generate index migrations**
```bash
python scripts/database_migration_tool.py --connection $DATABASE_URL \
--suggest-indexes --output migrations/
```
**Step 4: Test migration (dry-run)**
```bash
python scripts/database_migration_tool.py --connection $DATABASE_URL \
--migrate migrations/add_indexes.sql --dry-run
```
**Step 5: Apply and verify**
```bash
# Apply migration
python scripts/database_migration_tool.py --connection $DATABASE_URL \
--migrate migrations/add_indexes.sql
# Verify improvement
python scripts/database_migration_tool.py --connection $DATABASE_URL --analyze
```
---
### Security Hardening Workflow
Use when preparing an API for production or after a security review.
**Step 1: Review authentication setup**
```typescript
// Verify JWT configuration
const jwtConfig = {
secret: process.env.JWT_SECRET, // Must be from env, never hardcoded
expiresIn: '1h', // Short-lived tokens
algorithm: 'RS256' // Prefer asymmetric
};
```
**Step 2: Add rate limiting**
```typescript
import rateLimit from 'express-rate-limit';
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', apiLimiter);
```
**Step 3: Validate all inputs**
```typescript
import { z } from 'zod';
const CreateUserSchema = z.object({
email: z.string().email().max(255),
name: z.string().min(1).max(100),
age: z.number().int().positive().optional()
});
// Use in route handler
const data = CreateUserSchema.parse(req.body);
```
**Step 4: Load test with attack patterns**
```bash
# Test rate limiting
python scripts/api_load_tester.py https://api.example.com/login \
--concurrency 200 --duration 10 --expect-rate-limit
# Test input validation
python scripts/api_load_tester.py https://api.example.com/users \
--method POST \
--body '{"email": "not-an-email"}' \
--expect-status 400
```
**Step 5: Review security headers**
```typescript
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: true,
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: true,
crossOriginResourcePolicy: true,
hsts: { maxAge: 31536000, includeSubDomains: true },
}));
```
---
## Reference Documentation
| File | Contains | Use When |
|------|----------|----------|
| `references/api_design_patterns.md` | REST vs GraphQL, versioning, error handling, pagination | Designing new APIs |
| `references/database_optimization_guide.md` | Indexing strategies, query optimization, N+1 solutions | Fixing slow queries |
| `references/backend_security_practices.md` | OWASP Top 10, auth patterns, input validation | Security hardening |
---
## Common Patterns Quick Reference
### REST API Response Format
```json
{
"data": { "id": 1, "name": "John" },
"meta": { "requestId": "abc-123" }
}
```
### Error Response Format
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid email format",
"details": [{ "field": "email", "message": "must be valid email" }]
},
"meta": { "requestId": "abc-123" }
}
```
### HTTP Status Codes
| Code | Use Case |
|------|----------|
| 200 | Success (GET, PUT, PATCH) |
| 201 | Created (POST) |
| 204 | No Content (DELETE) |
| 400 | Validation error |
| 401 | Authentication required |
| 403 | Permission denied |
| 404 | Resource not found |
| 429 | Rate limit exceeded |
| 500 | Internal server error |
### Database Index Strategy
```sql
-- Single column (equality lookups)
CREATE INDEX idx_users_email ON users(email);
-- Composite (multi-column queries)
CREATE INDEX idx_orders_user_status ON orders(user_id, status);
-- Partial (filtered queries)
CREATE INDEX idx_orders_active ON orders(created_at) WHERE status = 'active';
-- Covering (avoid table lookup)
CREATE INDEX idx_users_email_name ON users(email) INCLUDE (name);
```
---
## Common Commands
```bash
# API Development
python scripts/api_scaffolder.py openapi.yaml --framework express
python scripts/api_scaffolder.py src/routes/ --generate-spec
# Database Operations
python scripts/database_migration_tool.py --connection $DATABASE_URL --analyze
python scripts/database_migration_tool.py --connection $DATABASE_URL --migrate file.sql
# Performance Testing
python scripts/api_load_tester.py https://api.example.com/endpoint --concurrency 50
python scripts/api_load_tester.py https://api.example.com/endpoint --compare baseline.json
```
---
## Assumptions and Verifiable Success Criteria (Karpathy discipline)
Before this skill scaffolds, recommends a pattern, or modifies a schema, the following four assumptions MUST be surfaced. If any are unknown, the skill stops and walks the [Forcing-question library](#forcing-question-library-matt-pocock-grill) instead.
1. **Read/write ratio + one-year p99 QPS** — drives DB, cache, queue, and partitioning choices. Kleppmann, *DDIA* (2017).
2. **Tenancy model** — single-tenant, shared multi-tenant, isolated multi-tenant. Drives data-access pattern.
3. **Data sensitivity tier** — public / internal / PII / PHI / PCI. Drives compliance floor.
4. **SLO + named error-budget consumer** — Google SRE Workbook canon. No SLO = no reliability work prioritization.
**Verifiable success criteria** (Karpathy #4) — every recommendation this skill emits must include:
- Latency targets (p50, p95, p99 in ms)
- Uptime / SLO target
- RPO + RTO
If any of those three is not stated, the recommendation is incomplete — return to Q7 of the forcing-question library.
The `scripts/backend_decision_engine.py` tool encodes these checks: it refuses to recommend a profile without read/write ratio + QPS + tenancy + data sensitivity + pattern preference.
---
## Customization profiles
Four built-in profiles in `profiles/` calibrate every recommendation:
| Profile | When to pick | Pattern | Latency floor (p99) |
|---|---|---|---|
| `node-express` | TS team, < 15 eng, customer-facing SaaS | Modular monolith on Postgres | 600ms |
| `fastapi-python` | Python team, < 20 eng, ML-adjacent | Modular monolith on Postgres (async) | 500ms |
| `django-monolith` | Content-heavy CRUD + admin, < 25 eng | Modular monolith on Postgres | 800ms |
| `go-or-rust-microservice` | Extracted service, ≥ 30 eng, platform team, QPS ≥ 1000 | Extracted service | 200ms |
Pick a profile via:
```bash
python scripts/backend_decision_engine.py \
--team-size 8 --qps-p99 50 --read-write-ratio 20 \
--tenancy shared-multi-tenant --data-sensitivity pii \
--pattern modular-monolith --language-preference typescript
```
The tool returns the best-fit profile, runner-up tradeoff (if within 15%), stack picks, anti-patterns, named approvers, and SLO floor. **This tool never auto-approves.**
To add a custom profile: copy `profiles/node-express.json` to `profiles/<your-org>.json` and adjust `constraints` + `success_thresholds` + `named_approver_chain`.
---
## Composition map
This skill does NOT reimplement scope owned by the POWERFUL-tier specialists. It forks into them. See `references/composition_map.md` for the full routing table. Key forks:
| Concern | Fork into |
|---|---|
| API contract / breaking-change risk | `engineering/skills/api-design-reviewer/` |
| Schema design + ERD + indexing | `engineering/skills/database-designer/` |
| Zero-downtime schema migration | `engineering/skills/migration-architect/` |
| SLO + SLI + error-budget | `engineering/slo-architect/` |
| Observability / golden signals | `engineering/skills/observability-designer/` |
| CI/CD pipeline | `engineering/skills/ci-cd-pipeline-builder/` |
| Security / threat model | `engineering-team/skills/senior-security/`, `adversarial-reviewer` |
| Compliance evidence (HIPAA / ISO 27001) | `ra-qm-team/` |
| Pre-commit Karpathy review | `engineering/karpathy-coder/` |
| Pre-flight architecture grill | `engineering/grill-me/` |
The `cs-backend-engineer` agent orchestrates these forks via `context: fork`. Invoke it from another agent with `Agent({subagent_type: "cs-backend-engineer", prompt: "..."})` or via `/cs:backend-review <your problem>`.
---
## Forcing-question library (Matt Pocock grill)
Before locking any backend decision, walk the seven forcing questions in `references/forcing_questions.md`. Discipline:
1. One question per turn. No bundling.
2. Always recommend the answer with cited canon.
3. Track answers in `/tmp/backend-grill-<date>.md`.
4. If a kill criterion trips, stop. Don't scaffold around an unresolved gap.
5. After Q7, run `backend_decision_engine.py` with the seven answers.
Summary:
1. Read/write ratio + p99 QPS forecast?
2. Tenancy model — single / shared / isolated?
3. Sync / async / event-driven — default + exceptions?
4. Data sensitivity tier — PII / PHI / PCI?
5. Monolith / modular monolith / microservices — team-size justification?
6. RPO + RTO?
7. SLO + named error-budget consumer?
---
## Invocation from other agents and skills
Three surfaces:
1. **Slash command:** `/cs:backend-review <prompt>` — full grill + decision engine + composition routing.
2. **Agent subagent:** `Agent({subagent_type: "cs-backend-engineer", prompt: "..."})` — forks context, returns ≤ 200-word digest.
3. **Direct tool call:** `python scripts/backend_decision_engine.py ...` — deterministic profile match when inputs are known.
See `agents/engineering/cs-backend-engineer.md` for the full invocation contract.





首頁
