Senior Backend Engineer
Backend development patterns, API design, database optimization, and security practices.
Quick Start
CODEBLOCK0
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:
CODEBLOCK1
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:
# 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:
# 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
CODEBLOCK4
Step 2: Generate route scaffolding
CODEBLOCK5
Step 3: Implement business logic
CODEBLOCK6
Step 4: Add validation middleware
CODEBLOCK7
Step 5: Generate updated OpenAPI spec
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
CODEBLOCK9
Step 2: Identify slow queries
CODEBLOCK10
Step 3: Generate index migrations
CODEBLOCK11
Step 4: Test migration (dry-run)
CODEBLOCK12
Step 5: Apply and verify
# 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
CODEBLOCK14
Step 2: Add rate limiting
CODEBLOCK15
Step 3: Validate all inputs
CODEBLOCK16
Step 4: Load test with attack patterns
CODEBLOCK17
Step 5: Review security headers
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 |
|---|
| INLINECODE3 | REST vs GraphQL, versioning, error handling, pagination | Designing new APIs |
| INLINECODE4 |
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
CODEBLOCK19
Error Response Format
CODEBLOCK20
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
-- 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
CODEBLOCK22
高级后端工程师
后端开发模式、API设计、数据库优化和安全实践。
快速开始
bash
从OpenAPI规范生成API路由
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
分析数据库模式并生成迁移文件
python scripts/database
migrationtool.py --connection postgres://localhost/mydb --analyze
对API端点进行负载测试
python scripts/api
loadtester.py https://api.example.com/users --concurrency 50 --duration 30
工具概述
1. API脚手架生成器
根据模式定义生成API路由处理器、中间件和OpenAPI规范。
输入: OpenAPI规范(YAML/JSON)或数据库模式
输出: 路由处理器、验证中间件、TypeScript类型
用法:
bash
从OpenAPI规范生成Express路由
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
输出:生成了12个路由处理器、验证中间件和TypeScript类型
从数据库模式生成
python scripts/api_scaffolder.py --from-db postgres://localhost/mydb --output src/routes/
从现有路由生成OpenAPI规范
python scripts/api_scaffolder.py src/routes/ --generate-spec --output openapi.yaml
支持的框架:
- - Express.js(--framework express)
- Fastify(--framework fastify)
- Koa(--framework koa)
2. 数据库迁移工具
分析数据库模式,检测变更,并生成支持回滚的迁移文件。
输入: 数据库连接字符串或模式文件
输出: 迁移文件、模式差异报告、优化建议
用法:
bash
分析当前模式并建议优化
python scripts/database
migrationtool.py --connection postgres://localhost/mydb --analyze
输出:缺失索引、N+1查询风险和建议的迁移文件
从模式差异生成迁移
python scripts/database
migrationtool.py --connection postgres://localhost/mydb \
--compare schema/v2.sql --output migrations/
预演迁移
python scripts/database
migrationtool.py --connection postgres://localhost/mydb \
--migrate migrations/20240115
adduser_indexes.sql --dry-run
3. API负载测试工具
执行可配置并发数的HTTP负载测试,测量延迟百分位数和吞吐量。
输入: API端点URL和测试配置
输出: 包含延迟分布、错误率、吞吐量指标的性能报告
用法:
bash
基本负载测试
python scripts/api
loadtester.py https://api.example.com/users --concurrency 50 --duration 30
输出:吞吐量(请求/秒)、延迟百分位数(P50/P95/P99)、错误计数和扩展建议
使用自定义头部和请求体进行测试
python scripts/api
loadtester.py https://api.example.com/orders \
--method POST \
--header Authorization: Bearer token123 \
--body {product_id: 1, quantity: 2} \
--concurrency 100 \
--duration 60
比较两个端点
python scripts/api
loadtester.py https://api.example.com/v1/users https://api.example.com/v2/users \
--compare --concurrency 50 --duration 30
后端开发工作流程
API设计工作流程
在设计新API或重构现有端点时使用。
步骤1:定义资源和操作
yaml
openapi.yaml
openapi: 3.0.3
info:
title: 用户服务API
version: 1.0.0
paths:
/users:
get:
summary: 列出用户
parameters:
- name: limit
in: query
schema:
type: integer
default: 20
post:
summary: 创建用户
requestBody:
required: true
content:
application/json:
schema:
$ref: #/components/schemas/CreateUser
步骤2:生成路由脚手架
bash
python scripts/api_scaffolder.py openapi.yaml --framework express --output src/routes/
步骤3:实现业务逻辑
typescript
// src/routes/users.ts(生成后自定义)
export const createUser = async (req: Request, res: Response) => {
const { email, name } = req.body;
// 添加业务逻辑
const user = await userService.create({ email, name });
res.status(201).json(user);
};
步骤4:添加验证中间件
bash
验证从OpenAPI模式自动生成
src/middleware/validators.ts 包含:
- 请求体验证
- 查询参数验证
- 路径参数验证
步骤5:生成更新的OpenAPI规范
bash
python scripts/api_scaffolder.py src/routes/ --generate-spec --output openapi.yaml
数据库优化工作流程
在查询缓慢或数据库性能需要改进时使用。
步骤1:分析当前性能
bash
python scripts/databasemigrationtool.py --connection $DATABASE_URL --analyze
步骤2:识别慢查询
sql
-- 检查查询执行计划
EXPLAIN ANALYZE SELECT * FROM orders
WHERE user_id = 123
ORDER BY created_at DESC
LIMIT 10;
-- 查找:Seq Scan(差),Index Scan(好)
步骤3:生成索引迁移
bash
python scripts/databasemigrationtool.py --connection $DATABASE_URL \
--suggest-indexes --output migrations/
步骤4:测试迁移(预演)
bash
python scripts/databasemigrationtool.py --connection $DATABASE_URL \
--migrate migrations/add_indexes.sql --dry-run
步骤5:应用并验证
bash
应用迁移
python scripts/database
migrationtool.py --connection $DATABASE_URL \
--migrate migrations/add_indexes.sql
验证改进
python scripts/database
migrationtool.py --connection $DATABASE_URL --analyze
安全加固工作流程
在准备API上线或安全审查后使用。
步骤1:审查认证设置
typescript
// 验证JWT配置
const jwtConfig = {
secret: process.env.JWT_SECRET, // 必须来自环境变量,绝不硬编码
expiresIn: 1h, // 短生命周期令牌
algorithm: RS256 // 优先使用非对称算法
};
步骤2:添加速率限制
typescript
import rateLimit from express-rate-limit;
const apiLimiter = rateLimit({
windowMs: 15 60 1000, // 15分钟
max: 100, // 每个窗口100个请求
standardHeaders: true,
legacyHeaders: false,
});
app.use(/api/, apiLimiter);
步骤3:验证所有输入
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()
});
// 在路由处理器中使用
const data = CreateUserSchema.parse(req.body);
步骤4:使用攻击模式进行负载测试
bash
测试速率限制
python scripts/api
loadtester.py https://api.example.com/login \
--concurrency 200 --duration 10 --expect-rate-limit
测试输入验证
python scripts/api
loadtester.py https://api.example.com/users \
--method POST \
--body {email: not-an-email} \
--expect-status 400
步骤5:审查安全头部
typescript
import helmet from helmet;
app.use(helmet({
contentSecurityPolicy: true,
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: true,
crossOriginResourcePolicy: true,
hsts: { maxAge: 31536000, includeSubDomains: true },
}));
参考文档
| 文件 | 内容 | 使用场景 |
|---|
| references/apidesignpatterns.md | REST与GraphQL、版本控制、错误处理、分页 | 设计新API |
| references/databaseoptimizationguide.md |
索引策略、查询优化、N+1解决方案 | 修复慢查询 |
| references/backend
securitypractices.md | OWASP Top 10、认证模式、输入验证 | 安全加固 |
常见模式快速参考
REST API响应格式
json
{
data: { id: 1, name: John },
meta: {