关于 senior-backend
senior-backend 是面向 API 设计、数据库工作和安全实践的后端工程技能。它结合脚手架、架构分析与负载测试脚本,并要求决策注明系统约束和可衡量目标。
主要功能
- 01生成 API 路由与校验
- 02分析数据库架构并创建迁移
- 03对 HTTP 端点进行负载测试
- 04依据约束检查后端决策
- 05提供框架配置档与模式参考
适用场景
- 01根据 OpenAPI 规范搭建路由
- 02检查架构变更并生成迁移
- 03测量 API 延迟与吞吐量
- 04按系统需求选择后端模式
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alirezarezvani/ claude-skills --skill senior-backend安装后在 Claude Code 中输入/senior-backend确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
profiles/django-monolith.jsonfastapi-python.jsongo-or-rust-microservice.jsonnode-express.jsonreferences/api_design_patterns.mdbackend_security_practices.mdcomposition_map.mddatabase_optimization_guide.mdforcing_questions.mdscripts/api_load_tester.pyapi_scaffolder.pybackend_decision_engine.pydatabase_migration_tool.py详细介绍
高级后端工程师
后端开发模式、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 脚手架生成器
根据 schema 定义生成 API 路由处理器、中间件和 OpenAPI 规范。
输入: OpenAPI 规范(YAML/JSON)或数据库 schema 输出: 路由处理器、校验中间件、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. 数据库迁移工具
分析数据库 schema,检测变更,并生成支持回滚的迁移文件。
输入: 数据库连接字符串或 schema 文件 输出: 迁移文件、schema 差异报告、优化建议
用法:
# 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 Top 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
假设与可验证的成功标准(Karpathy 纪律)
在此技能搭建脚手架、推荐模式或修改架构前,必须先明确以下四项假设。如果其中任何一项未知,此技能将停止,并转而使用引导式提问库(Matt Pocock 盘问法)。
- 读写比率 + 一年后的 p99 QPS —— 决定数据库、缓存、队列和分区策略。Kleppmann,《DDIA》(2017)。
- 租户模型 —— 单租户、共享多租户、隔离多租户。决定数据访问模式。
- 数据敏感级别 —— 公开 / 内部 / PII / PHI / PCI。决定合规底线。
- SLO + 指定的错误预算负责人 —— Google SRE Workbook 的准则。没有 SLO = 无法确定可靠性工作的优先级。
可验证的成功标准(Karpathy #4)—— 此技能给出的每条建议都必须包含:
- 延迟目标(p50、p95、p99,单位为 ms)
- 正常运行时间 / SLO 目标
- RPO + RTO
如果未说明上述三项中的任何一项,该建议就不完整——返回引导式提问库的 Q7。
script 中的 scripts/backend_decision_engine.py 工具会执行这些检查:如果缺少读写比率 + QPS + 租户模型 + 数据敏感级别 + 模式偏好,它就不会给出配置建议。
自定义配置
profiles/ 中的四种内置配置会校准每条建议:
| 配置 | 适用场景 | 模式 | 延迟下限(p99) |
|---|---|---|---|
node-express | TS 团队,< 15 名工程师,面向客户的 SaaS | 基于 Postgres 的模块化单体 | 600ms |
fastapi-python | Python 团队,< 20 名工程师,邻近 ML | 基于 Postgres 的模块化单体(异步) | 500ms |
django-monolith | 内容密集型 CRUD + 管理后台,< 25 名工程师 | 基于 Postgres 的模块化单体 | 800ms |
go-or-rust-microservice | 拆分出的服务,≥ 30 名工程师,平台团队,QPS ≥ 1000 | 拆分出的服务 | 200ms |
通过以下方式选择配置:
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/<your-org>.json,然后调整 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 Agent 通过 context: fork 协调这些分派。从另一个 Agent 调用它:Agent({subagent_type: "cs-backend-engineer", prompt: "..."});或通过 /cs-backend-review <your problem> 调用。
强制问题库(Matt Pocock grill)
在敲定任何后端决策之前,先逐一回答 references/forcing_questions.md 中的七个强制问题。要求:
- 每轮只问一个问题,不要捆绑提问。
- 始终引用权威依据,推荐一个答案。
- 将答案记录在
/tmp/backend-grill-<date>.md中。 - 如果触发了淘汰标准,就停止。不要针对尚未解决的问题搭建脚手架。
- 回答完 Q7 后,使用这七个答案运行
backend_decision_engine.py。
摘要:
- 读写比率 + p99 QPS 预测?
- 租户模型——单租户 / 共享 / 隔离?
- 同步 / 异步 / 事件驱动——默认方案 + 例外情况?
- 数据敏感级别——PII / PHI / PCI?
- 单体 / 模块化单体 / 微服务——如何根据团队规模论证?
- RPO + RTO?
- SLO + 指定的错误预算负责人?
从其他 Agent 和技能调用
有三个入口:
- 斜杠命令:
/cs-backend-review <prompt>— 完整的强制提问流程 + 决策引擎 + 组合路由。 - Agent 子 Agent:
Agent({subagent_type: "cs-backend-engineer", prompt: "..."})— 分叉上下文,返回不超过 200 个词的摘要。 - 直接调用工具:
python scripts/backend_decision_engine.py ...— 输入已知时进行确定性的配置匹配。
完整调用约定请参阅 agents/engineering/cs-backend-engineer.md。