clay-architecture-variants

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Clay Architecture Variants

Clay 架构变体

Overview

概述

Three validated architecture blueprints for Clay integrations.
三种经Clay验证的集成架构蓝图。

Prerequisites

前置条件

  • Understanding of team size and DAU requirements
  • Knowledge of deployment infrastructure
  • Clear SLA requirements
  • Growth projections available
  • 了解团队规模和DAU需求
  • 熟悉部署基础设施
  • 明确SLA要求
  • 具备增长预测数据

Variant A: Monolith (Simple)

变体A:单体架构(简单版)

Best for: MVPs, small teams, < 10K daily active users
my-app/
├── src/
│   ├── clay/
│   │   ├── client.ts          # Singleton client
│   │   ├── types.ts           # Types
│   │   └── middleware.ts      # Express middleware
│   ├── routes/
│   │   └── api/
│   │       └── clay.ts    # API routes
│   └── index.ts
├── tests/
│   └── clay.test.ts
└── package.json
适用场景: MVP、小型团队、日活跃用户(DAU)< 10K
my-app/
├── src/
│   ├── clay/
│   │   ├── client.ts          # 单例客户端
│   │   ├── types.ts           # 类型定义
│   │   └── middleware.ts      # Express 中间件
│   ├── routes/
│   │   └── api/
│   │       └── clay.ts    # API 路由
│   └── index.ts
├── tests/
│   └── clay.test.ts
└── package.json

Key Characteristics

核心特性

  • Single deployment unit
  • Synchronous Clay calls in request path
  • In-memory caching
  • Simple error handling
  • 单一部署单元
  • 请求链路中同步调用Clay
  • 内存缓存
  • 简单错误处理

Code Pattern

代码模式

typescript
// Direct integration in route handler
app.post('/api/create', async (req, res) => {
  try {
    const result = await clayClient.create(req.body);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

typescript
// 直接在路由处理器中集成
app.post('/api/create', async (req, res) => {
  try {
    const result = await clayClient.create(req.body);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Variant B: Service Layer (Moderate)

变体B:服务层架构(中等复杂度)

Best for: Growing startups, 10K-100K DAU, multiple integrations
my-app/
├── src/
│   ├── services/
│   │   ├── clay/
│   │   │   ├── client.ts      # Client wrapper
│   │   │   ├── service.ts     # Business logic
│   │   │   ├── repository.ts  # Data access
│   │   │   └── types.ts
│   │   └── index.ts           # Service exports
│   ├── controllers/
│   │   └── clay.ts
│   ├── routes/
│   ├── middleware/
│   ├── queue/
│   │   └── clay-processor.ts  # Async processing
│   └── index.ts
├── config/
│   └── clay/
└── package.json
适用场景: 成长型创业公司、DAU 10K-100K、多集成场景
my-app/
├── src/
│   ├── services/
│   │   ├── clay/
│   │   │   ├── client.ts      # 客户端封装
│   │   │   ├── service.ts     # 业务逻辑
│   │   │   ├── repository.ts  # 数据访问层
│   │   │   └── types.ts
│   │   └── index.ts           # 服务导出
│   ├── controllers/
│   │   └── clay.ts
│   ├── routes/
│   ├── middleware/
│   ├── queue/
│   │   └── clay-processor.ts  # 异步处理
│   └── index.ts
├── config/
│   └── clay/
└── package.json

Key Characteristics

核心特性

  • Separation of concerns
  • Background job processing
  • Redis caching
  • Circuit breaker pattern
  • Structured error handling
  • 关注点分离
  • 后台任务处理
  • Redis缓存
  • 断路器模式
  • 结构化错误处理

Code Pattern

代码模式

typescript
// Service layer abstraction
class ClayService {
  constructor(
    private client: ClayClient,
    private cache: CacheService,
    private queue: QueueService
  ) {}

  async createResource(data: CreateInput): Promise<Resource> {
    // Business logic before API call
    const validated = this.validate(data);

    // Check cache
    const cached = await this.cache.get(cacheKey);
    if (cached) return cached;

    // API call with retry
    const result = await this.withRetry(() =>
      this.client.create(validated)
    );

    // Cache result
    await this.cache.set(cacheKey, result, 300);

    // Async follow-up
    await this.queue.enqueue('clay.post-create', result);

    return result;
  }
}

typescript
// 服务层抽象
class ClayService {
  constructor(
    private client: ClayClient,
    private cache: CacheService,
    private queue: QueueService
  ) {}

  async createResource(data: CreateInput): Promise<Resource> {
    // API调用前的业务逻辑
    const validated = this.validate(data);

    // 检查缓存
    const cached = await this.cache.get(cacheKey);
    if (cached) return cached;

    // 带重试的API调用
    const result = await this.withRetry(() =>
      this.client.create(validated)
    );

    // 缓存结果
    await this.cache.set(cacheKey, result, 300);

    // 异步后续操作
    await this.queue.enqueue('clay.post-create', result);

    return result;
  }
}

Variant C: Microservice (Complex)

变体C:微服务架构(复杂版)

Best for: Enterprise, 100K+ DAU, strict SLAs
clay-service/              # Dedicated microservice
├── src/
│   ├── api/
│   │   ├── grpc/
│   │   │   └── clay.proto
│   │   └── rest/
│   │       └── routes.ts
│   ├── domain/
│   │   ├── entities/
│   │   ├── events/
│   │   └── services/
│   ├── infrastructure/
│   │   ├── clay/
│   │   │   ├── client.ts
│   │   │   ├── mapper.ts
│   │   │   └── circuit-breaker.ts
│   │   ├── cache/
│   │   ├── queue/
│   │   └── database/
│   └── index.ts
├── config/
├── k8s/
│   ├── deployment.yaml
│   ├── service.yaml
│   └── hpa.yaml
└── package.json

other-services/
├── order-service/       # Calls clay-service
├── payment-service/
└── notification-service/
适用场景: 企业级应用、DAU 100K+、严格SLA要求
clay-service/              # 独立微服务
├── src/
│   ├── api/
│   │   ├── grpc/
│   │   │   └── clay.proto
│   │   └── rest/
│   │       └── routes.ts
│   ├── domain/
│   │   ├── entities/
│   │   ├── events/
│   │   └── services/
│   ├── infrastructure/
│   │   ├── clay/
│   │   │   ├── client.ts
│   │   │   ├── mapper.ts
│   │   │   └── circuit-breaker.ts
│   │   ├── cache/
│   │   ├── queue/
│   │   └── database/
│   └── index.ts
├── config/
├── k8s/
│   ├── deployment.yaml
│   ├── service.yaml
│   └── hpa.yaml
└── package.json

other-services/
├── order-service/       # 调用clay-service
├── payment-service/
└── notification-service/

Key Characteristics

核心特性

  • Dedicated Clay microservice
  • gRPC for internal communication
  • Event-driven architecture
  • Database per service
  • Kubernetes autoscaling
  • Distributed tracing
  • Circuit breaker per service
  • 独立的Clay微服务
  • 内部通信使用gRPC
  • 事件驱动架构
  • 服务专属数据库
  • Kubernetes自动扩缩容
  • 分布式追踪
  • 每个服务独立配置断路器

Code Pattern

代码模式

typescript
// Event-driven with domain isolation
class ClayAggregate {
  private events: DomainEvent[] = [];

  process(command: ClayCommand): void {
    // Domain logic
    const result = this.execute(command);

    // Emit domain event
    this.events.push(new ClayProcessedEvent(result));
  }

  getUncommittedEvents(): DomainEvent[] {
    return [...this.events];
  }
}

// Event handler
@EventHandler(ClayProcessedEvent)
class ClayEventHandler {
  async handle(event: ClayProcessedEvent): Promise<void> {
    // Saga orchestration
    await this.sagaOrchestrator.continue(event);
  }
}

typescript
// 领域隔离的事件驱动模式
class ClayAggregate {
  private events: DomainEvent[] = [];

  process(command: ClayCommand): void {
    // 领域逻辑
    const result = this.execute(command);

    // 发布领域事件
    this.events.push(new ClayProcessedEvent(result));
  }

  getUncommittedEvents(): DomainEvent[] {
    return [...this.events];
  }
}

// 事件处理器
@EventHandler(ClayProcessedEvent)
class ClayEventHandler {
  async handle(event: ClayProcessedEvent): Promise<void> {
    // 流程编排
    await this.sagaOrchestrator.continue(event);
  }
}

Decision Matrix

决策矩阵

FactorMonolithService LayerMicroservice
Team Size1-55-2020+
DAU< 10K10K-100K100K+
Deployment FrequencyWeeklyDailyContinuous
Failure IsolationNonePartialFull
Operational ComplexityLowMediumHigh
Time to MarketFastestModerateSlowest
因素单体架构服务层架构微服务架构
团队规模1-5人5-20人20人以上
DAU< 10K10K-100K100K+
部署频率每周每日持续部署
故障隔离部分隔离完全隔离
运维复杂度中等
上市时间最快中等最慢

Migration Path

迁移路径

Monolith → Service Layer:
1. Extract Clay code to service/
2. Add caching layer
3. Add background processing

Service Layer → Microservice:
1. Create dedicated clay-service repo
2. Define gRPC contract
3. Add event bus
4. Deploy to Kubernetes
5. Migrate traffic gradually
单体架构 → 服务层架构:
1. 将Clay代码提取至service/目录
2. 添加缓存层
3. 引入后台处理

服务层架构 → 微服务架构:
1. 创建独立的clay-service代码仓库
2. 定义gRPC契约
3. 添加事件总线
4. 部署至Kubernetes
5. 逐步迁移流量

Instructions

操作步骤

Step 1: Assess Requirements

步骤1:评估需求

Use the decision matrix to identify appropriate variant.
使用决策矩阵确定合适的架构变体。

Step 2: Choose Architecture

步骤2:选择架构

Select Monolith, Service Layer, or Microservice based on needs.
根据需求选择单体架构、服务层架构或微服务架构。

Step 3: Implement Structure

步骤3:实现架构结构

Set up project layout following the chosen blueprint.
按照选定的蓝图搭建项目结构。

Step 4: Plan Migration Path

步骤4:规划迁移路径

Document upgrade path for future scaling.
记录未来的升级迁移路径。

Output

输出成果

  • Architecture variant selected
  • Project structure implemented
  • Migration path documented
  • Appropriate patterns applied
  • 选定的架构变体
  • 已实现的项目结构
  • 已记录的迁移路径
  • 已应用的合适模式

Error Handling

错误处理

IssueCauseSolution
Over-engineeringWrong variant choiceStart simpler
Performance issuesWrong layerAdd caching/async
Team frictionComplex architectureSimplify or train
Deployment complexityMicroservice overheadConsider service layer
问题原因解决方案
过度设计选择了错误的架构变体从更简单的架构开始
性能问题架构层级选择不当添加缓存/异步处理
团队协作摩擦架构过于复杂简化架构或开展培训
部署复杂度高微服务带来的额外开销考虑使用服务层架构

Examples

示例

Quick Variant Check

快速变体检查

bash
undefined
bash
undefined

Count team size and DAU to select variant

统计团队规模和DAU以选择合适的架构变体

echo "Team: $(git log --format='%ae' | sort -u | wc -l) developers" echo "DAU: Check analytics dashboard"
undefined
echo "Team: $(git log --format='%ae' | sort -u | wc -l) developers" echo "DAU: Check analytics dashboard"
undefined

Resources

参考资源

Next Steps

下一步

For common anti-patterns, see
clay-known-pitfalls
.
如需了解常见反模式,请查看
clay-known-pitfalls