Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

我想做一个海外AI纹身APP,目前设计几个模块:登录模块、支付模块、业务模块、AI生图模块,业务模块将生成任务写入Redis种,多个AI生图服务通过令牌桶算法限流从Redis中获…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Coherecommand-a-03-2025’s answer.
  1. User

    我想做一个海外AI纹身APP,目前设计几个模块:登录模块、支付模块、业务模块、AI生图模块,业务模块将生成任务写入Redis种,多个AI生图服务通过令牌桶算法限流从Redis中获取任务,帮我完成整个APP的详细架构设计

  2. Claude Assistant

    我来为你设计这个海外AI纹身APP的详细架构方案。

    整体架构设计

    系统架构图

    ┌─────────────────────────────────────────────────────────────┐
    │                        客户端层                               │
    │    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐   │
    │    │   iOS App   │    │Android App  │    │   Web App   │   │
    │    └─────────────┘    └─────────────┘    └─────────────┘   │
    └─────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────┐
    │                        网关层                                 │
    │    ┌────────────────────────────────────────────────────┐   │
    │    │          API Gateway (Kong/AWS API Gateway)        │   │
    │    │         负载均衡、限流、认证、路由                    │   │
    │    └────────────────────────────────────────────────────┘   │
    └─────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────┐
    │                        服务层                                 │
    │ ┌──────────────┐  ┌──────────────┐  ┌──────────────┐       │
    │ │   Auth       │  │   Payment    │  │   Business   │       │
    │ │   Service    │  │   Service    │  │   Service    │       │
    │ └──────────────┘  └──────────────┘  └──────────────┘       │
    │ ┌──────────────┐  ┌──────────────┐  ┌──────────────┐       │
    │ │   User       │  │   Order      │  │   AI Task    │       │
    │ │   Service    │  │   Service    │  │   Manager    │       │
    │ └──────────────┘  └──────────────┘  └──────────────┘       │
    └─────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────┐
    │                      AI生图服务集群                            │
    │ ┌────────────┐  ┌────────────┐  ┌────────────┐             │
    │ │ AI Worker  │  │ AI Worker  │  │ AI Worker  │             │
    │ │  Node 1    │  │  Node 2    │  │  Node N    │             │
    │ └────────────┘  └────────────┘  └────────────┘             │
    │         令牌桶限流器 + 任务消费者                              │
    └─────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────┐
    │                        数据层                                 │
    │ ┌──────────────┐  ┌──────────────┐  ┌──────────────┐       │
    │ │  PostgreSQL  │  │    Redis     │  │     S3/OSS   │       │
    │ │   主数据库    │  │  缓存/队列    │  │   图片存储    │       │
    │ └──────────────┘  └──────────────┘  └──────────────┘       │
    └─────────────────────────────────────────────────────────────┘
    

    各模块详细设计

    1. 登录模块(Auth Service)

    功能设计:

    • 多种登录方式:邮箱/手机号、Google、Facebook、Apple ID
    • JWT token认证机制
    • 支持多设备登录管理
    • 密码找回功能

    技术实现:

    // Auth Service 核心接口
    class AuthService {
      // 邮箱注册
      async register(email, password) {
        // 验证邮箱格式
        // 密码加密 (bcrypt)
        // 生成验证码
        // 发送验证邮件
        // 存储用户信息
      }
      
      // 社交登录
      async socialLogin(provider, token) {
        // 验证第三方token
        // 获取用户信息
        // 创建或更新用户
        // 生成JWT token
      }
      
      // JWT生成
      generateToken(userId) {
        return jwt.sign({
          userId,
          exp: Date.now() + 7 * 24 * 60 * 60 * 1000
        }, SECRET_KEY);
      }
    }
    

    2. 支付模块(Payment Service)

    支付集成:

    • Stripe(主要)- 支持全球信用卡支付
    • PayPal(备选)- 覆盖更多地区
    • Apple Pay / Google Pay - 移动端快捷支付

    订阅模式设计:

    // 支付方案
    const PRICING_PLANS = {
      FREE: {
        credits: 5,
        price: 0,
        features: ['basic_styles', 'watermark']
      },
      BASIC: {
        credits: 50,
        price: 9.99,
        features: ['all_styles', 'no_watermark', 'priority_queue']
      },
      PRO: {
        credits: 200,
        price: 29.99,
        features: ['all_styles', 'no_watermark', 'priority_queue', 'custom_model']
      }
    };
    

    3. 业务模块(Business Service)

    核心功能:

    class TattooBusinessService {
      // 创建纹身生成任务
      async createTattooTask(userId, params) {
        // 验证用户额度
        const user = await userService.getUser(userId);
        if (user.credits <= 0) {
          throw new Error('Insufficient credits');
        }
        
        // 创建任务
        const task = {
          id: uuid(),
          userId,
          prompt: params.prompt,
          style: params.style,
          size: params.size,
          bodyPart: params.bodyPart,
          status: 'pending',
          priority: user.plan === 'PRO' ? 10 : 1,
          createdAt: new Date()
        };
        
        // 写入Redis任务队列
        await redis.zadd('tattoo:tasks', task.priority, JSON.stringify(task));
        
        // 扣除额度
        await userService.deductCredits(userId, 1);
        
        return task.id;
      }
      
      // 获取任务状态
      async getTaskStatus(taskId) {
        return await redis.hget(`task:${taskId}`, 'status');
      }
    }
    

    4. AI生图模块(AI Worker Service)

    令牌桶限流实现:

    class TokenBucket {
      constructor(capacity, refillRate) {
        this.capacity = capacity;
        this.tokens = capacity;
        this.refillRate = refillRate;
        this.lastRefill = Date.now();
      }
      
      async consume(tokens = 1) {
        this.refill();
        
        if (this.tokens >= tokens) {
          this.tokens -= tokens;
          return true;
        }
        return false;
      }
      
      refill() {
        const now = Date.now();
        const timePassed = (now - this.lastRefill) / 1000;
        const tokensToAdd = timePassed * this.refillRate;
        this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
        this.lastRefill = now;
      }
    }
    

    AI Worker实现:

    class AIWorker {
      constructor(workerId) {
        this.workerId = workerId;
        this.tokenBucket = new TokenBucket(10, 2); // 每秒2个请求
        this.isRunning = true;
      }
      
      async start() {
        while (this.isRunning) {
          // 检查令牌桶
          if (!await this.tokenBucket.consume()) {
            await sleep(500);
            continue;
          }
          
          // 从Redis获取任务
          const task = await this.fetchTask();
          if (!task) {
            await sleep(1000);
            continue;
          }
          
          // 处理任务
          await this.processTask(task);
        }
      }
      
      async fetchTask() {
        // 使用ZPOPMAX获取高优先级任务
        const result = await redis.zpopmax('tattoo:tasks');
        if (result && result.length > 0) {
          return JSON.parse(result[0]);
        }
        return null;
      }
      
      async processTask(task) {
        try {
          // 更新任务状态
          await redis.hset(`task:${task.id}`, 'status', 'processing');
          
          // 调用AI模型生成图片
          const imageUrl = await this.generateTattoo(task);
          
          // 上传到S3
          const s3Url = await this.uploadToS3(imageUrl, task.id);
          
          // 更新任务结果
          await redis.hset(`task:${task.id}`, {
            status: 'completed',
            resultUrl: s3Url,
            completedAt: new Date().toISOString()
          });
          
          // 发送通知
          await this.notifyUser(task.userId, task.id);
          
        } catch (error) {
          await redis.hset(`task:${task.id}`, {
            status: 'failed',
            error: error.message
          });
        }
      }
      
      async generateTattoo(task) {
        // 集成Stable Diffusion或DALL-E API
        const response = await stableDiffusionAPI.generate({
          prompt: `tattoo design, ${task.style} style, ${task.prompt}`,
          negative_prompt: 'blurry, low quality',
          width: 512,
          height: 512,
          steps: 50
        });
        
        return response.imageUrl;
      }
    }
    

    数据库设计

    PostgreSQL表结构:

    -- 用户表
    CREATE TABLE users (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      email VARCHAR(255) UNIQUE NOT NULL,
      password_hash VARCHAR(255),
      username VARCHAR(100),
      avatar_url VARCHAR(500),
      plan VARCHAR(50) DEFAULT 'FREE',
      credits INTEGER DEFAULT 5,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    
    -- 订单表
    CREATE TABLE orders (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      user_id UUID REFERENCES users(id),
      plan VARCHAR(50),
      amount DECIMAL(10,2),
      currency VARCHAR(3) DEFAULT 'USD',
      status VARCHAR(50),
      stripe_payment_id VARCHAR(255),
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    
    -- 生成历史表
    CREATE TABLE tattoo_generations (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      user_id UUID REFERENCES users(id),
      prompt TEXT,
      style VARCHAR(100),
      result_url VARCHAR(500),
      status VARCHAR(50),
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    

    部署架构

    容器化部署(Kubernetes):

    # API服务部署
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: tattoo-api
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: tattoo-api
      template:
        metadata:
          labels:
            app: tattoo-api
        spec:
          containers:
          - name: api
            image: tattoo-api:latest
            resources:
              requests:
                memory: "512Mi"
                cpu: "500m"
              limits:
                memory: "1Gi"
                cpu: "1000m"
    ---
    # AI Worker部署
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: ai-worker
    spec:
      replicas: 5
      selector:
        matchLabels:
          app: ai-worker
      template:
        metadata:
          labels:
            app: ai-worker
        spec:
          containers:
          - name: worker
            image: ai-worker:latest
            resources:
              requests:
                memory: "2Gi"
                cpu: "2000m"
                nvidia.com/gpu: 1  # GPU资源
    

    监控和日志

    监控体系:

    • Prometheus + Grafana:系统指标监控
    • ELK Stack:日志收集和分析
    • Sentry:错误追踪

    关键监控指标:

    // 自定义监控指标
    const metrics = {
      // API响应时间
      apiResponseTime: new Histogram({
        name: 'api_response_time',
        help: 'API response time in ms',
        labelNames: ['method', 'route', 'status']
      }),
      
      // 任务队列长度
      taskQueueLength: new Gauge({
        name: 'task_queue_length',
        help: 'Number of pending tasks in queue'
      }),
      
      // AI生成成功率
      aiGenerationSuccess: new Counter({
        name: 'ai_generation_success_total',
        help: 'Total successful AI generations'
      })
    };
    

    安全性设计

    1. API安全:

      • Rate limiting per user/IP
      • API Key管理
      • Request signing
    2. 数据安全:

      • 敏感数据加密存储
      • TLS/SSL加密传输
      • 定期安全审计
    3. 图片安全:

      • 内容审核(NSFW检测)
      • 水印添加(免费用户)
      • CDN防盗链

    这个架构设计具有良好的可扩展性,能够根据业务增长动态调整各个组件的规模。需要特别注意的是AI生图服务的成本控制和性能优化,建议根据实际负载情况调整令牌桶参数和Worker数量。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.