Backend Service Patterns 标志

Backend Service Patterns

社区
korallis
backend-service-patterns

使用分层架构、依赖注入、中间件模式、服务类和关注点分离,设计可扩展的后端服务。适用于构建 API 服务、实现业务逻辑层、创建服务类、设置中间件链、实现依赖注入、设计控制器-服务-仓储模式、处理横切关注点、创建领域模型、实现 CQRS 模式,或制定后端架构标准。

Add to TypingMind

概览

发布者korallis
代码仓库Droidz
技能名称backend-service-patterns
星标数
89
复刻数
9
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 korallis 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Backend Service Patterns AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/korallis/Droidz/tree/main/droidz_installer/payloads/claude/default/skills/backend-service-patterns
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/korallis/Droidz.git /tmp/Droidz
mkdir -p .claude/skills
cp -r /tmp/Droidz/droidz_installer/payloads/claude/default/skills/backend-service-patterns .claude/skills/backend-service-patterns
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Backend Service Patterns,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Backend Service Patterns。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Backend Service Patterns 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Backend Service Patterns - Building Scalable Server Applications

When to use this skill

  • Building API services and backend applications
  • Implementing business logic in service layers
  • Creating controller-service-repository architectures
  • Setting up Express/Fastify middleware chains
  • Implementing dependency injection containers
  • Designing domain models and business entities
  • Handling cross-cutting concerns (logging, auth, validation)
  • Implementing CQRS (Command Query Responsibility Segregation)
  • Creating background job processing services
  • Designing event-driven service architectures
  • Implementing API gateway patterns
  • Building microservices with clear boundaries

When to use this skill

  • Designing backend architecture, implementing APIs, handling business logic, managing microservices, or building serverless functions.
  • When working on related tasks or features
  • During development that requires this expertise

Use when: Designing backend architecture, implementing APIs, handling business logic, managing microservices, or building serverless functions.

Core Principles

  1. Separation of Concerns - Clear boundaries between layers
  2. Single Responsibility - Each service does one thing well
  3. Stateless Design - Easy to scale horizontally
  4. Idempotency - Safe to retry operations
  5. Fail Fast, Recover Gracefully - Handle errors explicitly

Layered Architecture

1. Three-Tier Architecture

typescript
// ✅ Routes Layer - HTTP endpoints
// routes/users.ts
import express from 'express';
import { UserController } from '../controllers/UserController';

const router = express.Router();
const userController = new UserController();

router.get('/users', userController.list);
router.post('/users', userController.create);
router.get('/users/:id', userController.get);

export default router;

// ✅ Controller Layer - Request/response handling
// controllers/UserController.ts
import { Request, Response } from 'express';
import { UserService } from '../services/UserService';
import { CreateUserSchema } from '../schemas/user';

export class UserController {
  private userService = new UserService();

  list = async (req: Request, res: Response) => {
    try {
      const users = await this.userService.listUsers({
        page: parseInt(req.query.page as string) || 1,
        limit: parseInt(req.query.limit as string) || 20
      });
      res.json(users);
    } catch (error) {
      res.status(500).json({ error: 'Failed to fetch users' });
    }
  };

  create = async (req: Request, res: Response) => {
    try {
      const validated = CreateUserSchema.parse(req.body);
      const user = await this.userService.createUser(validated);
      res.status(201).json(user);
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  };
}

// ✅ Service Layer - Business logic
// services/UserService.ts
import { UserRepository } from '../repositories/UserRepository';
import { EmailService } from './EmailService';

export class UserService {
  private userRepo = new UserRepository();
  private emailService = new EmailService();

  async createUser(data: CreateUserInput) {
    // Business logic here
    const existingUser = await this.userRepo.findByEmail(data.email);
    if (existingUser) {
      throw new Error('Email already exists');
    }

    const hashedPassword = await bcrypt.hash(data.password, 10);
    const user = await this.userRepo.create({
      ...data,
      passwordHash: hashedPassword
    });

    // Send welcome email asynchronously
    await this.emailService.sendWelcome(user.email);

    return user;
  }

  async listUsers(params: { page: number; limit: number }) {
    return await this.userRepo.findMany({
      skip: (params.page - 1) * params.limit,
      take: params.limit
    });
  }
}

// ✅ Repository Layer - Data access
// repositories/UserRepository.ts
import { prisma } from '../db';

export class UserRepository {
  async create(data: CreateUserData) {
    return await prisma.user.create({ data });
  }

  async findByEmail(email: string) {
    return await prisma.user.findUnique({ where: { email } });
  }

  async findMany(params: { skip: number; take: number }) {
    return await prisma.user.findMany(params);
  }
}

2. Dependency Injection

typescript
// ✅ Constructor injection for testability
export class OrderService {
  constructor(
    private orderRepo: OrderRepository,
    private paymentService: PaymentService,
    private emailService: EmailService
  ) {}

  async processOrder(orderId: string) {
    const order = await this.orderRepo.findById(orderId);
    const payment = await this.paymentService.charge(order);
    await this.emailService.sendReceipt(order, payment);
    return payment;
  }
}

// Easy to mock in tests
const mockOrderRepo = {
  findById: jest.fn().mockResolvedValue({ id: '1', total: 100 })
};
const mockPaymentService = {
  charge: jest.fn().mockResolvedValue({ id: 'pay_123' })
};
const service = new OrderService(mockOrderRepo, mockPaymentService, mockEmailService);

Design Patterns

1. Repository Pattern

typescript
// ✅ Abstract data access behind interface
interface IUserRepository {
  create(data: CreateUserData): Promise<User>;
  findById(id: string): Promise<User | null>;
  update(id: string, data: UpdateUserData): Promise<User>;
  delete(id: string): Promise<void>;
}

// PostgreSQL implementation
export class PostgresUserRepository implements IUserRepository {
  async create(data: CreateUserData) {
    return await prisma.user.create({ data });
  }
  
  async findById(id: string) {
    return await prisma.user.findUnique({ where: { id } });
  }
  
  // ... other methods
}

// MongoDB implementation (easy to swap)
export class MongoUserRepository implements IUserRepository {
  async create(data: CreateUserData) {
    return await User.create(data);
  }
  
  // ... other methods
}

2. Service Layer Pattern

typescript
// ✅ Encapsulate business logic
export class OrderService {
  async placeOrder(userId: string, items: OrderItem[]) {
    // Validate inventory
    for (const item of items) {
      const product = await this.productRepo.findById(item.productId);
      if (product.stock < item.quantity) {
        throw new InsufficientStockError(item.productId);
      }
    }

    // Calculate total
    const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);

    // Apply discount
    const discount = await this.discountService.calculateDiscount(userId, total);

    // Create order
    const order = await this.orderRepo.create({
      userId,
      items,
      subtotal: total,
      discount,
      total: total - discount,
      status: 'pending'
    });

    // Reserve inventory
    for (const item of items) {
      await this.inventoryService.reserve(item.productId, item.quantity);
    }

    // Queue payment processing
    await this.paymentQueue.add({ orderId: order.id });

    return order;
  }
}

3. Factory Pattern

typescript
// ✅ Create objects based on conditions
interface PaymentProvider {
  charge(amount: number, currency: string): Promise<PaymentResult>;
}

class StripeProvider implements PaymentProvider {
  async charge(amount: number, currency: string) {
    return await stripe.charges.create({ amount, currency });
  }
}

class PayPalProvider implements PaymentProvider {
  async charge(amount: number, currency: string) {
    return await paypal.payment.create({ amount, currency });
  }
}

class PaymentProviderFactory {
  static create(provider: string): PaymentProvider {
    switch (provider) {
      case 'stripe':
        return new StripeProvider();
      case 'paypal':
        return new PayPalProvider();
      default:
        throw new Error(`Unknown provider: ${provider}`);
    }
  }
}

// Usage
const provider = PaymentProviderFactory.create(user.preferredPaymentMethod);
await provider.charge(100, 'USD');

4. Strategy Pattern

typescript
// ✅ Swap algorithms at runtime
interface ShippingStrategy {
  calculateCost(weight: number, distance: number): number;
}

class StandardShipping implements ShippingStrategy {
  calculateCost(weight: number, distance: number) {
    return weight * 0.5 + distance * 0.1;
  }
}

class ExpressShipping implements ShippingStrategy {
  calculateCost(weight: number, distance: number) {
    return weight * 1.0 + distance * 0.3;
  }
}

class OvernightShipping implements ShippingStrategy {
  calculateCost(weight: number, distance: number) {
    return weight * 2.0 + distance * 0.5;
  }
}

class ShippingCalculator {
  constructor(private strategy: ShippingStrategy) {}

  calculate(weight: number, distance: number) {
    return this.strategy.calculateCost(weight, distance);
  }
}

// Usage
const calculator = new ShippingCalculator(new ExpressShipping());
const cost = calculator.calculate(10, 500);

5. Observer Pattern (Event-Driven)

typescript
// ✅ Decouple components with events
import { EventEmitter } from 'events';

class OrderEvents extends EventEmitter {
  static CREATED = 'order.created';
  static PAID = 'order.paid';
  static SHIPPED = 'order.shipped';
  static CANCELLED = 'order.cancelled';
}

const orderEvents = new OrderEvents();

// Listeners
orderEvents.on(OrderEvents.CREATED, async (order) => {
  await emailService.sendOrderConfirmation(order);
  await analyticsService.trackOrderCreated(order);
});

orderEvents.on(OrderEvents.PAID, async (order) => {
  await inventoryService.deductStock(order.items);
  await shippingService.createShipment(order);
});

// Emit events
export class OrderService {
  async createOrder(data: CreateOrderData) {
    const order = await this.orderRepo.create(data);
    orderEvents.emit(OrderEvents.CREATED, order);
    return order;
  }

  async markAsPaid(orderId: string) {
    const order = await this.orderRepo.update(orderId, { status: 'paid' });
    orderEvents.emit(OrderEvents.PAID, order);
    return order;
  }
}

Microservices Patterns

1. API Gateway

typescript
// ✅ Single entry point for multiple services
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';

const app = express();

// Route to different services
app.use('/api/users', createProxyMiddleware({ 
  target: 'http://user-service:3001',
  changeOrigin: true 
}));

app.use('/api/orders', createProxyMiddleware({ 
  target: 'http://order-service:3002',
  changeOrigin: true 
}));

app.use('/api/payments', createProxyMiddleware({ 
  target: 'http://payment-service:3003',
  changeOrigin: true 
}));

// Add authentication, rate limiting, logging here
app.use(authMiddleware);
app.use(rateLimiter);
app.use(logger);

2. Service-to-Service Communication

typescript
// ✅ HTTP/REST communication
export class UserService {
  private orderServiceUrl = process.env.ORDER_SERVICE_URL;

  async getUserWithOrders(userId: string) {
    const user = await this.userRepo.findById(userId);
    
    // Call order service
    const response = await fetch(`${this.orderServiceUrl}/orders?userId=${userId}`);
    const orders = await response.json();

    return { ...user, orders };
  }
}

// ✅ Message queue communication (async)
import { Queue } from 'bullmq';

const emailQueue = new Queue('emails', {
  connection: { host: 'redis', port: 6379 }
});

// Producer (User Service)
export class UserService {
  async createUser(data: CreateUserData) {
    const user = await this.userRepo.create(data);
    
    // Async notification
    await emailQueue.add('welcome', {
      userId: user.id,
      email: user.email
    });

    return user;
  }
}

// Consumer (Email Service)
import { Worker } from 'bullmq';

const worker = new Worker('emails', async (job) => {
  if (job.name === 'welcome') {
    await sendWelcomeEmail(job.data.email);
  }
});

3. Circuit Breaker Pattern

typescript
// ✅ Prevent cascading failures
import CircuitBreaker from 'opossum';

const options = {
  timeout: 3000,        // If function takes > 3s, trigger failure
  errorThresholdPercentage: 50,  // When 50% of requests fail...
  resetTimeout: 30000   // ...open circuit for 30s
};

const breaker = new CircuitBreaker(callExternalAPI, options);

breaker.fallback(() => {
  return { data: null, fromCache: true }; // Fallback response
});

breaker.on('open', () => {
  console.log('Circuit breaker opened - too many failures');
});

async function callExternalAPI() {
  const response = await fetch('https://external-api.com/data');
  return response.json();
}

// Usage
try {
  const data = await breaker.fire();
} catch (error) {
  // Circuit is open or request failed
}

Serverless Patterns

1. Function-as-a-Service

typescript
// ✅ AWS Lambda handler
import { APIGatewayProxyHandler } from 'aws-lambda';

export const handler: APIGatewayProxyHandler = async (event) => {
  try {
    const body = JSON.parse(event.body || '{}');
    
    // Business logic
    const result = await processOrder(body);

    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify(result)
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: error.message })
    };
  }
};

// ✅ Vercel Edge Function
export const config = {
  runtime: 'edge'
};

export default async function handler(request: Request) {
  const data = await processData();
  
  return new Response(JSON.stringify(data), {
    headers: { 'content-type': 'application/json' }
  });
}

2. Cold Start Optimization

typescript
// ✅ Initialize outside handler (persists across invocations)
import { PrismaClient } from '@prisma/client';

// Created once, reused across warm invocations
const prisma = new PrismaClient();

export const handler = async (event) => {
  // This runs on every invocation
  const users = await prisma.user.findMany();
  return { statusCode: 200, body: JSON.stringify(users) };
};

// ✅ Lazy initialization
let connection: Connection | null = null;

async function getConnection() {
  if (!connection) {
    connection = await createConnection();
  }
  return connection;
}

export const handler = async (event) => {
  const conn = await getConnection();
  // Use connection
};

Background Jobs

1. Job Queue Pattern

typescript
// ✅ BullMQ job processing
import { Queue, Worker } from 'bullmq';

const videoQueue = new Queue('video-processing', {
  connection: { host: 'redis', port: 6379 }
});

// Add jobs
export class VideoService {
  async uploadVideo(file: File) {
    const video = await this.videoRepo.create({ 
      filename: file.name,
      status: 'pending'
    });

    // Queue processing job
    await videoQueue.add('transcode', {
      videoId: video.id,
      inputPath: file.path
    }, {
      attempts: 3,           // Retry up to 3 times
      backoff: {
        type: 'exponential',
        delay: 5000          // 5s, 10s, 20s
      }
    });

    return video;
  }
}

// Worker process
const worker = new Worker('video-processing', async (job) => {
  if (job.name === 'transcode') {
    await transcodeVideo(job.data.videoId, job.data.inputPath);
    
    // Update progress
    job.updateProgress(50);
    
    await generateThumbnail(job.data.videoId);
    
    job.updateProgress(100);
  }
}, {
  connection: { host: 'redis', port: 6379 },
  concurrency: 5  // Process 5 jobs concurrently
});

worker.on('completed', (job) => {
  console.log(`Job ${job.id} completed`);
});

worker.on('failed', (job, err) => {
  console.error(`Job ${job.id} failed:`, err);
});

2. Scheduled Tasks

typescript
// ✅ Cron jobs with node-cron
import cron from 'node-cron';

// Run every day at midnight
cron.schedule('0 0 * * *', async () => {
  await cleanupExpiredSessions();
  await generateDailyReport();
});

// Run every 5 minutes
cron.schedule('*/5 * * * *', async () => {
  await checkPaymentStatus();
});

// ✅ Or use BullMQ repeat
await queue.add('daily-report', {}, {
  repeat: {
    pattern: '0 0 * * *'  // Cron expression
  }
});

Backend Best Practices

1. Configuration Management

typescript
// ✅ Environment-based config
export const config = {
  port: parseInt(process.env.PORT || '3000'),
  database: {
    url: process.env.DATABASE_URL,
    poolSize: parseInt(process.env.DB_POOL_SIZE || '10')
  },
  redis: {
    host: process.env.REDIS_HOST || 'localhost',
    port: parseInt(process.env.REDIS_PORT || '6379')
  },
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: '1h'
  }
};

// Validate required vars on startup
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
  if (!process.env[key]) {
    throw new Error(`Missing required environment variable: ${key}`);
  }
}

2. Health Checks

typescript
// ✅ Health check endpoint
app.get('/health', async (req, res) => {
  const health = {
    uptime: process.uptime(),
    timestamp: Date.now(),
    status: 'ok',
    checks: {
      database: 'ok',
      redis: 'ok'
    }
  };

  try {
    await prisma.$queryRaw`SELECT 1`;
  } catch (error) {
    health.status = 'degraded';
    health.checks.database = 'error';
  }

  try {
    await redis.ping();
  } catch (error) {
    health.status = 'degraded';
    health.checks.redis = 'error';
  }

  const statusCode = health.status === 'ok' ? 200 : 503;
  res.status(statusCode).json(health);
});

Backend Service Checklist

Architecture:
□ Clear separation of concerns (routes/controllers/services/repos)
□ Dependency injection for testability
□ Business logic in service layer (not controllers)
□ Data access abstracted in repositories
□ No database queries in controllers

API Design:
□ RESTful endpoints
□ Proper HTTP methods and status codes
□ Input validation on all endpoints
□ Pagination for lists
□ API versioning strategy

Error Handling:
□ Try/catch in all async functions
□ Meaningful error messages
□ Proper error status codes
□ Error logging with context
□ No sensitive data in error responses

Performance:
□ Database queries optimized
□ Connection pooling configured
□ Caching strategy implemented
□ Background jobs for heavy operations
□ Rate limiting on public endpoints

Security:
□ Authentication required
□ Authorization checks
□ Input sanitization
□ SQL injection prevention
□ CORS configured properly

Monitoring:
□ Health check endpoint
□ Logging configured
□ Metrics collected
□ Error tracking (Sentry, etc.)
□ Performance monitoring

Resources


Remember: Great backend services are maintainable, testable, scalable, and resilient. Design for failure, optimize for readability.

常见问题

Backend Service Patterns AI 技能有什么作用?

使用分层架构、依赖注入、中间件模式、服务类和关注点分离,设计可扩展的后端服务。适用于构建 API 服务、实现业务逻辑层、创建服务类、设置中间件链、实现依赖注入、设计控制器-服务-仓储模式、处理横切关注点、创建领域模型、实现 CQRS 模式,或制定后端架构标准。

为什么在 TypingMind 中使用 Backend Service Patterns?

因为您只需安装一次,就能搭配任何模型使用。Backend Service Patterns 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Backend Service Patterns?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/korallis/Droidz/tree/main/droidz_installer/payloads/claude/default/skills/backend-service-patterns。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Backend Service Patterns?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Backend Service Patterns 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Backend Service Patterns 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Backend Service Patterns AI 技能免费吗?

korallis 已在 GitHub 上发布了该技能。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇