SuperAPI AI Directory

build-backend-service-patterns

Coding & development

View repository

Updated 10-16 09:45

About this skill

Service Patterns — Service Architecture Patterns

Entry/Exit

  • Entry: Boundary design, communication pattern selection, and resilience strategies involving multiple services/modules
  • Exit: Pattern selection record + interface definitions + resilience configuration
  • Points to: After the architecture is determined, proceed to build-backend-api-design(define concrete interfaces)
  • Output path: verify-workflow-review(downstream validation skill)
  • Preload: CANON.md

When not to use

  • Only implementing a clear function or endpoint within a single service
  • Service boundaries, communication methods, and fault-tolerance strategies are already specified by the spec/ADR
  • The problem is focused on a concrete API contract or database schema, not service architecture

Service layering

Presentation  →  API Handler / Controller(HTTP、验证、序列化)
     │
Business      →  Service(领域逻辑、规则、工作流)
     │
Data          →  Repository / Adapter(数据访问、外部 API 封装)
     │
Infrastructure →  DB、Cache、Queue、外部服务

Dependency direction: Upper layers depend on lower layers, and layers do not skip layers. Business does not directly import HTTP framework types.

Communication patterns

Pattern Applicable scenarios Example
Synchronous Request-Response Requires immediate results and strong consistency Create order → return order number
Asynchronous Message Queue Can be delayed, high throughput Send email notification after order creation
Event-Driven Pub/Sub Multiple consumers, decoupling Order completed → (notification service + analytics service + points service)
Saga (orchestration) Long-running cross-service transactions Place order → deduct inventory → charge payment → notify (failure at any step = compensating rollback)

Selection principles:

需要立即响应 + 强一致?→ 同步
可延迟 + 需要韧性?  → 异步
多消费者 + 解耦?   → Event-Driven
跨服务长事务?      → Saga

Resilience patterns

Retry and backoff

async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt === maxRetries) throw err;
      const delay = Math.pow(2, attempt) * 100;  // 100ms → 200ms → 400ms
      await sleep(delay);
    }
  }
  throw new Error('unreachable');
}

Circuit breaker

状态机:
  CLOSED → (连续失败 N 次) → OPEN(立即失败,不调用)
  OPEN → (等待 timeout) → HALF_OPEN(尝试一次)
  HALF_OPEN → 成功 → CLOSED | 失败 → OPEN

The circuit breaker protects downstream services from being overwhelmed by an avalanche. When calls have already failed repeatedly, failing fast > continuing to retry and dragging down the upstream.

Idempotency

// 每个写操作需要幂等键
interface CreateOrderRequest {
  idempotencyKey: string;  // 客户端生成 UUID
  items: OrderItem[];
}

// 服务端: 相同幂等键 → 返回相同结果(不重复创建)
async function createOrder(req: CreateOrderRequest): Promise<Order> {
  const existing = await db.orders.findBy({ idempotencyKey: req.idempotencyKey });
  if (existing) return existing;
  return db.orders.create(req);
}

Any endpoint involving payment must have an idempotency key. Network retry + duplicate charge = disaster.

Pattern selection

Requirement Pattern Complexity cost
CRUD around a single entity Repository + Service Low
Asymmetric read/write load CQRS (read/write separation) Medium
Cross-service transactions Saga High
Complex business rule chains Chain of Responsibility / Pipeline Medium
Multiple switchable strategies Strategy Pattern Low
Domain-logic intensive Domain-Driven(Entity + Value Object + Aggregate) Medium-High

Principle: Start with the simplest pattern. Upgrade when the code becomes complexbecause the pattern is insufficient, not because "it should be done this way".

Error handling

// 区分可恢复错误 vs 不可恢复错误
class RetryableError extends Error { /* 网络超时、503 */ }
class FatalError extends Error { /* 验证失败、404 */ }

async function handleServiceCall(fn: () => Promise<T>): Promise<T> {
  try {
    return await fn();
  } catch (err) {
    if (err instanceof RetryableError) {
      return withRetry(fn);
    }
    throw err;  // Fatal — 上层处理
  }
}

Common claims

Claim Reality Consequence
"Add retries later when needed" Networks are unreliable. Add retries starting from the first cross-service call. No retries → a single network jitter causes the request failure rate to spike from 0.1% to 5-10%, with production troubleshooting time of 2-8 hours
"The circuit breaker is too complex, just retry directly" Continuously retrying a failed service = dragging upstream down with it. The circuit breaker is a protection mechanism. No circuit breaker → when downstream goes down, upstream keeps retrying and exhausts the thread pool, cascading failures spread to 3-5 services
"Add idempotency later" Systems with payments need it from day one. Adding idempotency requires changing the API contract. Missing idempotency key → network retries cause duplicate charges/duplicate creation, single incident compensation cost > 10x development cost
"Synchronous coupling is fine, calls between microservices are fast" It's fast now. The call chain lengthens, the failure surface expands. Avoid coupling if you can. Sync chain > 3 layers → average failure recovery time doubles, any layer timing out causes the entire chain to fail
"Choose CQRS, even though it's simple now, what if we need read scaling later" Adding complexity for "what if" = premature engineering. Simple requirements, simple solutions. Premature CQRS → read-write model sync delay bugs, operational complexity increases 3-5x, 90% of projects don't need it

Validation failure handling

Failure scenario Handling method
Cross-service HTTP calls without retries and timeouts Stop, add withRetry + timeout configuration to each cross-service call before continuing
Payment-related endpoints missing idempotency key Stop, add idempotencyKey field to the API contract, implement idempotency check on the server before continuing
Queue consumer without dead letter queue Add DLQ configuration, failed messages go to DLQ instead of being repeatedly consumed, avoiding queue blockage
Sync call chain > 3 layers Refactor to asynchronous decoupling or introduce Saga orchestration, do not allow serial penetration through more than 3 services
Service boundaries divided by technical layer instead of business domain Redraw the service boundary diagram, re-divide by business domain (e.g. orders, payments, users)

Good and bad examples

✅ Good: Simplest pattern + complete resilience

订单创建流程:
- API Handler → 调用 OrderService.createOrder()
- OrderService → 写入 DB + 发事件到 Queue(异步解耦)
- 邮件服务消费 Queue 事件(异步,不阻塞订单创建)

韧性配置:
- OrderService → DB: withRetry(3, exponentialBackoff)
- OrderService → Queue: 断路器(5 次连续失败打开)
- createOrder API: idempotencyKey 必填
- Queue 消费者: 死信队列(失败 3 次进入 DLQ)

模式选择: Repository + Service(最简,匹配 CRUD 围绕单一实体需求)

❌ Bad: Premature engineering + missing resilience

订单创建流程:
- API → OrderService → InventoryService → PaymentService → NotificationService
  (同步链 4 层,任何一层超时整条链失败)

韧性配置: (未配置重试、断路器、幂等键)

模式选择: CQRS + Saga + Event Sourcing
  (当前只需 CRUD,过早引入 3 个高复杂度模式)

Red flag — STOP

  • Monolith split into microservices but failure modes not defined (network partition, timeout, downstream outage)
  • Cross-service HTTP calls without retries/circuit breakers
  • Payment-related endpoints missing idempotency key
  • Queue consumer without dead letter queue (DLQ) — bad messages repeatedly consumed
  • Sync call chain > 3 layers (requests serially penetrating multiple services)
  • Calling the data layer directly from the presentation layer (skipping Business/Service)

Output template

After the service architecture design is complete, the following structure should be recorded in the ADR or 03-plan.md :

## Service Architecture — [功能名称]

### 服务边界
| 服务 | 业务领域 | 负责范围 |
|------|---------|---------|
| [服务 A] | [领域] | [职责描述] |
| [服务 B] | [领域] | [职责描述] |

### 通信模式
| 调用路径 | 模式 | 理由 |
|---------|------|------|
| [A → B] | 同步 / 异步 / Event / Saga | [需要立即结果 / 可延迟 / 多消费者 / 跨服务长事务] |

### 韧性配置
| 调用路径 | 重试策略 | 断路器 | 幂等性 | 超时 |
|---------|---------|--------|-------|------|
| [A → B] | [次数 + 退避] | [阈值] | [是否需要] | [毫秒值] |

| 队列 | 消费者 | 死信队列 | 重试次数 |
|------|--------|---------|---------|
| [Queue A] | [消费者] | [DLQ 配置] | [次数] |

### 模式选择
| 需求 | 选定模式 | 复杂度代价 | 选择理由 |
|------|---------|-----------|---------|
| [需求描述] | [模式名] | [低/中/高] | [当前需求最简方案] |

### 故障模式
| 单点 | 降级方案 | 影响范围 |
|------|---------|---------|
| [单点描述] | [降级策略] | [受影响服务/用户] |

Validation checklist

  • Service boundaries are clear (by business domain, not by technical layer)
  • Cross-service calls have retry and timeout configuration
  • Payment/charge-related have idempotency keys
  • Async consumers have dead letter queues
  • Failure modes identified (where are the single points? What are the degradation plans?)
  • The simplest pattern currently needed was chosen