backend-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Backend Development

后端开发

Node.js/TypeScript and Go. PostgreSQL, Redis. REST APIs.
Related Skills:
  • kavak-documentation
    - USE FIRST for Kavak-specific patterns, kbroker, STS, GitLab CI, Docker templates
  • test-driven-development
    - USE PROACTIVELY for new features and bug fixes (Red-Green-Refactor)
  • Check
    .claude/CLAUDE.md
    or
    .cursor/rules/*
    for project-specific conventions
MCP: Use
kavak-platform/plati_query
tool to query Kavak internal documentation before implementing.
Node.js/TypeScript 和 Go。PostgreSQL、Redis。REST APIs。
相关技能:
  • kavak-documentation
    - 优先使用 用于Kavak特定模式、kbroker、STS、GitLab CI、Docker模板
  • test-driven-development
    - 主动使用 用于新功能开发和Bug修复(红-绿-重构)
  • 查看
    .claude/CLAUDE.md
    .cursor/rules/*
    获取项目特定规范
MCP:在实现前使用
kavak-platform/plati_query
工具查询Kavak内部文档。

🔴 MANDATORY: Code Reuse Analysis (GATE)

🔴 强制要求:代码复用分析(关卡)

This is a GATE. You cannot write new code until you complete this analysis.
这是一个关卡。在完成此分析前,你不能编写新代码。

Why This Matters

为什么这很重要

AI-generated code often duplicates existing logic because the model doesn't "see" all relevant files. This creates:
  • Bugs that need fixing in multiple places
  • Inconsistent behavior across the codebase
  • Maintenance nightmare for humans
Your job: Find existing code FIRST, reuse it, extend it, or extract shared logic.
AI生成的代码通常会重复现有逻辑,因为模型无法"看到"所有相关文件。这会导致:
  • 多处需要修复的Bug
  • 代码库中行为不一致
  • 给开发人员带来维护噩梦
你的任务:先找到现有代码,复用、扩展它,或者提取共享逻辑。

Step 1: Search Comprehensively

步骤1:全面搜索

STOP and think: Before searching, extract keywords from YOUR task:
  1. VERBS - What actions? (create, save, send, process, calculate, update, delete, etc.)
  2. NOUNS - What domain concepts? (the entities mentioned in your task)
  3. OUTPUT - What type of result? (Model, Response, Event, etc.)
Then search using YOUR task's actual keywords:
bash
undefined
停下来思考: 在搜索前,从你的任务中提取关键词:
  1. 动词 - 要执行什么操作?(创建、保存、发送、处理、计算、更新、删除等)
  2. 名词 - 涉及哪些领域概念?(任务中提到的实体)
  3. 输出 - 结果类型是什么?(模型、响应、事件等)
然后使用任务的实际关键词进行搜索:
bash
undefined

Search pattern - replace KEYWORD with your actual task keywords:

搜索模式 - 将 KEYWORD 替换为你的任务实际关键词:

grep -rn "KEYWORD" --include=".go" --include=".ts" . | head -50
grep -rn "KEYWORD" --include=".go" --include=".ts" . | head -50

Search for existing services/usecases with your domain term:

搜索包含你的领域术语的现有服务/用例:

grep -rn "func.*KEYWORD|KEYWORD.*Service|KEYWORD.Repository" --include=".go" . | head -30
grep -rn "func.*KEYWORD|KEYWORD.*Service|KEYWORD.Repository" --include=".go" . | head -30

Use codebase_search for semantic search:

使用 codebase_search 进行语义搜索:

codebase_search "how does existing code [your task action]" codebase_search "where is [your domain concept] implemented"

**The goal:** Find ANY existing code that does something similar to what your task needs.
codebase_search "how does existing code [your task action]" codebase_search "where is [your domain concept] implemented"

**目标:** 找到任何与你的任务需求类似的现有代码。

Step 2: Read and Evaluate Found Code

步骤2:阅读并评估找到的代码

For EACH potentially relevant file, read it and answer:
QuestionIf YES...
Does this do exactly what I need?Call it directly - inject as dependency
Does this do 70%+ of what I need?Extend it - add method/parameter
Does this share 50%+ logic with what I need?Extract shared helper first
Is this only 30% similar?OK to create new, but document why
对于每个潜在相关的文件,阅读并回答:
问题如果是YES...
它是否完全符合我的需求?直接调用 - 作为依赖注入
它是否满足我70%以上的需求?扩展它 - 添加方法/参数
它是否与我的需求有50%以上的逻辑重合?先提取共享辅助函数
相似度仅为30%?可以创建新代码,但需记录原因

Step 3: Document Your Decision (MANDATORY - Must Output This)

步骤3:记录你的决策(强制要求 - 必须输出此内容)

Before writing ANY code, you MUST output this analysis in your response:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ REUSE ANALYSIS                                                  ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
┃ Task: [brief description of what you need to implement]         ┃
┃                                                                 ┃
┃ Keywords searched:                                              ┃
┃   - Verbs: [actual verbs you searched]                          ┃
┃   - Nouns: [actual domain terms you searched]                   ┃
┃                                                                 ┃
┃ Existing code found:                                            ┃
┃   1. [file:line] - [function name] - [what it does]             ┃
┃   2. [file:line] - [function name] - [what it does]             ┃
┃                                                                 ┃
┃ Similarity assessment:                                          ┃
┃   - [file1]: [X]% similar because [reason]                      ┃
┃                                                                 ┃
┃ Decision: [REUSE | EXTEND | EXTRACT | NEW]                      ┃
┃ Rationale: [1-2 sentences why]                                  ┃
┃ Action: [specific action - e.g., "inject existing service"]     ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
If you skip this analysis or create code without it, the task FAILS.
在编写任何代码前,你必须在响应中输出此分析:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ 复用分析                                                  ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
┃ 任务: [你需要实现的内容简要描述]         ┃
┃                                                                 ┃
┃ 搜索的关键词:                                              ┃
┃   - 动词: [你实际搜索的动词]                          ┃
┃   - 名词: [你实际搜索的领域术语]                   ┃
┃                                                                 ┃
┃ 找到的现有代码:                                            ┃
┃   1. [文件:行号] - [函数名] - [功能描述]             ┃
┃   2. [文件:行号] - [函数名] - [功能描述]             ┃
┃                                                                 ┃
┃ 相似度评估:                                          ┃
┃   - [文件1]: [X]% 相似,原因是 [具体理由]                      ┃
┃                                                                 ┃
┃ 决策: [复用 | 扩展 | 提取 | 新建]                      ┃
┃ 理由: [1-2句话说明原因]                                  ┃
┃ 行动: [具体操作 - 例如:"注入现有服务"]     ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
如果你跳过此分析或未进行分析就创建代码,任务将失败。

Step 4: Apply Decision Matrix

步骤4:应用决策矩阵

SimilarityActionExample
>70%REUSE directlyInject existing service as dependency, call its method
50-70%EXTRACT shared helperCreate helper function, refactor existing + use in new
30-50%Consider interfaceCreate interface both can implement
<30%OK to create newDocument why existing code doesn't fit
相似度操作示例
>70%直接复用将现有服务作为依赖注入,调用其方法
50-70%提取共享辅助函数创建辅助函数,重构现有代码并在新代码中使用
30-50%考虑接口创建两者都可实现的接口
<30%可以创建新代码记录现有代码不适用的原因

🔴 Failure Conditions

🔴 失败条件

Your implementation FAILS the Code Reuse Analysis if:
  • You create a new file >100 lines without documenting reuse analysis
  • You duplicate >50% of logic from an existing file
  • You copy-paste code instead of calling existing functions
  • You create a new method that does the same thing as an existing one

如果出现以下情况,你的实现将无法通过代码复用分析:
  • 你创建了超过100行的新文件但未记录复用分析
  • 你重复了现有文件中50%以上的逻辑
  • 你复制粘贴代码而非调用现有函数
  • 你创建了一个与现有方法功能相同的新方法

Core Principles

核心原则

Architecture: Clean Architecture (4-layer) for new projects →
references/architecture.md
Design Principles:
  • SOLID - Single Responsibility, Open/Closed, Liskov, Interface Segregation, Dependency Inversion
  • DRY - Don't Repeat Yourself (extract reusable code) →
    references/dry-detection.md
  • YAGNI - You Aren't Gonna Need It (don't build unused features)
  • KISS - Keep It Simple, Stupid (simplest solution that works)
Comments Rule: Code should be self-documenting. Only add comments when:
  • Logic is complex/non-obvious (explain "why", not "what")
  • Workarounds or edge cases need context
  • Public API documentation (JSDoc/GoDoc)
typescript
// ❌ BAD: Obvious comment
const age = user.age; // Get user age

// ✅ GOOD: Explains WHY
// Add 1 day buffer for timezone edge cases in billing cycle
const billingDate = addDays(cycleEnd, 1);
See
references/code-quality.md
for detailed examples.
架构: 新项目采用Clean Architecture(4层架构)→
references/architecture.md
设计原则:
  • SOLID - 单一职责、开闭原则、里氏替换、接口隔离、依赖倒置
  • DRY - 不要重复自己(提取可复用代码)→
    references/dry-detection.md
  • YAGNI - 你不会需要它(不要构建未使用的功能)
  • KISS - 保持简单(选择可行的最简方案)
注释规则: 代码应具备自文档性。仅在以下情况添加注释:
  • 逻辑复杂/不明显(解释"为什么",而非"是什么")
  • 变通方案或边缘情况需要上下文说明
  • 公共API文档(JSDoc/GoDoc)
typescript
// ❌ 错误:注释冗余
const age = user.age; // 获取用户年龄

// ✅ 正确:解释原因
// 为计费周期的时区边缘情况添加1天缓冲
const billingDate = addDays(cycleEnd, 1);
详细示例请查看
references/code-quality.md

⚠️ Existing Projects Rule

⚠️ 现有项目规则

ALWAYS respect existing project structure and patterns:
  1. Read first - Explore the codebase before making changes
  2. Follow existing patterns - If project uses a pattern, continue using it
  3. Don't force architecture - Don't refactor to Clean Architecture unless asked
  4. Incremental improvement - Apply good practices to NEW code you write
  5. Ask if unclear - When patterns conflict, ask the user
Existing project has flat structure? → Keep flat structure
Existing project has no interfaces? → Don't add interfaces everywhere
Existing project uses callbacks? → Use callbacks (unless migrating)
Only apply Clean Architecture patterns to:
  • New greenfield projects
  • New modules/features in existing projects (when it fits)
  • When explicitly asked to refactor
始终尊重现有项目的结构和模式:
  1. 先阅读 - 在修改前探索代码库
  2. 遵循现有模式 - 如果项目使用某种模式,继续沿用
  3. 不要强行变更架构 - 除非明确要求,否则不要重构为Clean Architecture
  4. 渐进式改进 - 在你编写的新代码中应用良好实践
  5. 不确定时询问 - 当模式冲突时,询问用户
现有项目是扁平结构?→ 保持扁平结构
现有项目没有使用接口?→ 不要到处添加接口
现有项目使用回调?→ 使用回调(除非正在迁移)
仅在以下场景应用Clean Architecture模式:
  • 全新的项目
  • 现有项目中的新模块/功能(当适用时)
  • 明确要求重构时

Quick Start

快速开始

LanguageTestLint
Node/TS
npm test
npm run lint
Go
go test ./...
golangci-lint run
语言测试命令代码检查命令
Node/TS
npm test
npm run lint
Go
go test ./...
golangci-lint run

Technology Selection

技术选型

NeedChoose
TypeScript APINestJS
High concurrencyGo + Chi
Go databasepgx/v5 + sqlc
Node databaseDrizzle (new), keep existing
Go Redisrueidis (new), keep existing
Go job queueRiver (PostgreSQL-backed)
Node job queuepg-boss (PostgreSQL-backed)
Events (Kavak)kbroker (Kafka-by-REST)
Rate limitingpg-boss throttle / River snooze
TestingVitest (new Node), Jest (existing)
TracingOpenTelemetry + dd-trace
Note: Use kbroker for events between services. Use pg-boss (Node) or River (Go) for job queues.
需求选择
TypeScript APINestJS
高并发场景Go + Chi
Go 数据库pgx/v5 + sqlc
Node 数据库Drizzle(新项目),沿用现有方案
Go Redisrueidis(新项目),沿用现有方案
Go 任务队列River(基于PostgreSQL)
Node 任务队列pg-boss(基于PostgreSQL)
事件(Kavak)kbroker(Kafka-by-REST)
限流pg-boss throttle / River snooze
测试Vitest(新Node项目),Jest(现有项目)
链路追踪OpenTelemetry + dd-trace
注意: 服务间事件使用kbroker。任务队列使用pg-boss(Node)或River(Go)。

Common Workflows

常见工作流

New API Endpoint (TDD Approach)

新API端点(TDD方法)

Use
test-driven-development
skill
for Red-Green-Refactor cycle
  1. Write failing test first
    test-driven-development
    skill
  2. Design endpoint →
    references/api-design.md
  3. Set up handler →
    references/go/http-handlers.md
    or
    references/node/frameworks.md
  4. Add database access →
    references/go/database.md
    or
    references/node/database.md
  5. Implement auth →
    references/authentication.md
  6. Refactor with tests passing →
    references/code-quality.md
使用
test-driven-development
技能
进行红-绿-重构循环
  1. 先编写失败的测试
    test-driven-development
    技能
  2. 设计端点 →
    references/api-design.md
  3. 设置处理器 →
    references/go/http-handlers.md
    references/node/frameworks.md
  4. 添加数据库访问 →
    references/go/database.md
    references/node/database.md
  5. 实现权限认证 →
    references/authentication.md
  6. 测试通过后重构 →
    references/code-quality.md

Add Similar Feature (DRY-First Approach)

添加类似功能(优先DRY原则)

CRITICAL: When task says "do X like Y" or "add similar to existing"
  1. Find existing implementation first - search for the feature mentioned in the task
  2. Analyze similarity → Is >50% of logic the same?
  3. If similar, REUSE or EXTRACT:
    • >70% similar: Inject existing service, call its method
    • 50-70% similar: Extract shared helper, refactor existing to use it
    • <50% similar: OK to create new, but keep it small
  4. New code should be <50 lines - if more, you probably missed reuse opportunity
  5. Test both old and new paths → Ensure refactoring didn't break existing
WRONG vs RIGHT:
ApproachResult
❌ WRONGCreate new file (50-100+ lines) that duplicates existing logic
✅ RIGHTInject existing service, call its method (5-10 lines)
重要提示:当任务要求"像实现Y一样实现X"或"添加与现有功能类似的功能"时
  1. 先找到现有实现 - 搜索任务中提到的功能
  2. 分析相似度 → 是否有50%以上的逻辑重合?
  3. 如果相似,选择复用或提取:
    • 相似度>70%:注入现有服务,调用其方法
    • 相似度50-70%:提取共享辅助函数,重构现有代码并在新代码中使用
    • 相似度<50%:可以创建新代码,但保持代码简洁
  4. 新代码应少于50行 - 如果超过,你可能错过了复用机会
  5. 测试新旧路径 → 确保重构未破坏现有功能
错误 vs 正确做法:
方法结果
❌ 错误创建新文件(50-100+行),重复现有逻辑
✅ 正确注入现有服务,调用其方法(5-10行)

Fix Slow Query

修复慢查询

  1. Profile query →
    references/debugging.md
    (EXPLAIN ANALYZE)
  2. Add indexes →
    references/performance.md
  3. Add caching →
    references/go/redis-queues.md
    or
    references/node/database.md
  1. 分析查询 →
    references/debugging.md
    (EXPLAIN ANALYZE)
  2. 添加索引 →
    references/performance.md
  3. 添加缓存 →
    references/go/redis-queues.md
    references/node/database.md

Deploy New Service

部署新服务

  1. Write Dockerfile →
    references/devops/docker.md
  2. Set up CI/CD →
    references/devops/ci-cd.md
  1. 编写Dockerfile →
    references/devops/docker.md
  2. 设置CI/CD →
    references/devops/ci-cd.md

Debug Production Issue

调试生产环境问题

  1. Check logs/traces →
    references/debugging.md
  2. Profile if slow →
    references/debugging.md
    (pprof/clinic.js)
  3. Check DB queries →
    references/debugging.md
    (pg_stat_statements)
  1. 查看日志/链路追踪 →
    references/debugging.md
  2. 如果性能慢,进行性能分析 →
    references/debugging.md
    (pprof/clinic.js)
  3. 检查数据库查询 →
    references/debugging.md
    (pg_stat_statements)

References

参考文档

ReferenceWhen to Use
Go
references/go/http-handlers.md
Set up Chi routes, handlers, middleware
references/go/database.md
Implement pgx/v5, sqlc queries
references/go/patterns.md
Apply error handling, validation, testing
references/go/redis-queues.md
Add rueidis caching, River job queue
Node.js
references/node/frameworks.md
Set up NestJS, Express, Fastify
references/node/database.md
Implement Drizzle, Prisma, caching
references/node/patterns.md
Apply validation, errors, testing
DevOps
references/devops/docker.md
Write Dockerfiles, compose, health checks, DataDog metrics
references/devops/ci-cd.md
Configure GitLab CI pipelines
Cross-Cutting
references/architecture.md
Clean Architecture (4-layer), microservices, events
references/code-quality.md
SOLID, DRY, YAGNI, KISS, design patterns
references/dry-detection.md
MANDATORY - DRY detection, code reuse patterns
references/api-design.md
Design REST endpoints, versioning
references/authentication.md
Implement OAuth 2.1, JWT, RBAC
references/security.md
Apply OWASP Top 10, input validation
references/performance.md
Optimize caching, queries, pooling
references/testing.md
Write unit, integration, E2E tests
references/debugging.md
Debug with logs, profilers, tracing
参考文档使用场景
Go
references/go/http-handlers.md
设置Chi路由、处理器、中间件
references/go/database.md
实现pgx/v5、sqlc查询
references/go/patterns.md
应用错误处理、验证、测试
references/go/redis-queues.md
添加rueidis缓存、River任务队列
Node.js
references/node/frameworks.md
设置NestJS、Express、Fastify
references/node/database.md
实现Drizzle、Prisma、缓存
references/node/patterns.md
应用验证、错误处理、测试
DevOps
references/devops/docker.md
编写Dockerfile、compose、健康检查、DataDog指标
references/devops/ci-cd.md
配置GitLab CI流水线
跨领域
references/architecture.md
Clean Architecture(4层架构)、微服务、事件
references/code-quality.md
SOLID、DRY、YAGNI、KISS、设计模式
references/dry-detection.md
强制要求 - DRY原则检测、代码复用模式
references/api-design.md
设计REST端点、版本控制
references/authentication.md
实现OAuth 2.1、JWT、RBAC
references/security.md
应用OWASP Top 10、输入验证
references/performance.md
优化缓存、查询、连接池
references/testing.md
编写单元测试、集成测试、E2E测试
references/debugging.md
使用日志、性能分析器、链路追踪进行调试

Kavak-Only References

Kavak专属参考文档

Use when working on Kavak projects.
ReferenceWhen to Use
references/kavak/kbroker.md
Publish/subscribe events between services
references/kavak/queues-ratelimit.md
Job queues, rate limiting with River/pg-boss
references/kavak/microservice-auth.md
Authenticate between services (STS)
references/kavak/gitlab-ci.md
Set up kavak-it/ci-jobs v3 pipelines
references/kavak/docker-images.md
Build with docker-debian base
references/kavak/workload-config.md
Configure
.kavak/
dir, cron jobs
references/kavak/logging-metrics.md
Use kvklog, kvkmetric SDKs
在处理Kavak项目时使用。
参考文档使用场景
references/kavak/kbroker.md
服务间发布/订阅事件
references/kavak/queues-ratelimit.md
任务队列、限流 使用River/pg-boss
references/kavak/microservice-auth.md
服务间认证(STS)
references/kavak/gitlab-ci.md
设置kavak-it/ci-jobs v3流水线
references/kavak/docker-images.md
使用docker-debian基础镜像构建
references/kavak/workload-config.md
配置
.kavak/
目录、定时任务
references/kavak/logging-metrics.md
使用kvklog、kvkmetric SDKs