sub2api icon indicating copy to clipboard operation
sub2api copied to clipboard

Sub2API 性能优化技术方案草案

Open IanShaw027 opened this issue 11 months ago • 1 comments

🎯 一、问题背景

1.1 性能现状

经过深度分析,发现以下核心性能问题:

启动性能

当前启动时间:6-25 秒
主要瓶颈:GORM AutoMigrate + 远程 PostgreSQL(~160ms RTT)

启动日志示例:
[1489ms] SELECT count(*) FROM information_schema.tables...
[1014ms] SELECT CURRENT_DATABASE()
[870ms]  SELECT c.column_name FROM information_schema.columns...

API 响应性能(以账户列表为例)

当前性能:
- 10 个账户:1.6s
- 50 个账户:2-5s
- 100 个账户:预估 8-15s

主要问题:
1. 虽然实现了批量查询,但 Handler 层仍是串行执行
2. Redis "批量查询"实际是 for 循环(50 个账户 × 160ms RTT = 8s)
3. 缺少关键的复合索引

数据库连接池

当前配置:未配置(使用 database/sql 默认值)
- MaxIdleConns: 2(只保留 2 个空闲连接)
- MaxOpenConns: 0(无限制,风险高)

影响:
- 每次新请求可能需要建立连接(TCP 握手 + 认证 = 640-800ms)
- 高并发时连接数不可控

1.2 网络环境分析

# 远程 PostgreSQL 延迟测试
ping 142.171.248.226
平均 RTT: 159.378 ms

# 对比数据
同机房: 1-5 ms
同区域: 20-40 ms
当前:   ~160 ms (可能是跨大陆连接)

延迟放大效应:

  • 单次查询慢 32 倍(5ms → 160ms)
  • 50 次串行查询慢 32 倍(250ms → 8s)
  • AutoMigrate 慢 32-300 倍(250ms → 8-75s)

1.3 近期优化回顾

✅ 已完成的优化(feature/ui-and-backend-improvements)

  • [x] 实现批量查询方法 GetBatchAccountTodayStats
  • [x] 前端引入全局订阅数据管理 useSubscriptionStore
  • [x] 解决 N+1 查询问题(101 次查询 → 3 次)

⚠️ 优化未达预期的原因

  1. Handler 层串行执行:3 个批量查询仍然是顺序执行,延迟累加
  2. Redis "伪批量":GetAccountConcurrencyBatch 内部是 for 循环 + SCAN
  3. 缺少索引优化:批量查询的 GROUP BY 性能未达到理论最优
  4. 前端轮询不合理:后台标签页也在轮询,且强制刷新绕过缓存

📊 性能对比

实现方式 查询次数 网络往返 总延迟(50 账户) 优化效果
N+1(旧版) 101 次 101 × 160ms 16.1 s 基线
批量(当前) 3 次 3 × 160ms + 扫描 2-5 s -68%
批量 + 索引 + 并行(提议) 3 次 max(3 并发) 0.16-0.3 s -98% 🎯

💡 二、优化方案详细说明

方案分层设计

根据不同规模场景,将优化方案分为三个优先级:

  • P0:必须执行(所有规模都受益,成本低)
  • P1:推荐执行(中等规模以上必须,小规模可选)
  • P2:可选执行(大规模或长期规划)

🔧 三、P0 优化方案(必须执行)

3.1 数据库连接池配置

问题分析

// 当前代码:backend/internal/infrastructure/database.go:26
db, err := gorm.Open(postgres.Open(cfg.Database.DSNWithTimezone(cfg.Timezone)), gormConfig)
// ⚠️ 完全没有配置连接池,使用 database/sql 默认值

默认值的问题:

  • MaxIdleConns: 2 - 高并发时频繁建立连接(640-800ms/次)
  • MaxOpenConns: 0 - 无限制,可能耗尽数据库连接
  • ConnMaxLifetime: 0 - 连接永不过期,可能出现僵尸连接

优化方案

// backend/internal/infrastructure/database.go:36-48(新增)
func InitDB(cfg *config.Config) (*gorm.DB, error) {
    // ... existing code ...

    // ✅ 配置连接池
    sqlDB, err := db.DB()
    if err != nil {
        return nil, err
    }

    // 根据高延迟网络优化的连接池参数
    sqlDB.SetMaxIdleConns(10)              // 保持 10 个热连接
    sqlDB.SetMaxOpenConns(50)              // 限制最大 50 个连接
    sqlDB.SetConnMaxLifetime(time.Hour)    // 1 小时后回收连接
    sqlDB.SetConnMaxIdleTime(10 * time.Minute)  // 10 分钟无活动则关闭

    return db, nil
}

参数说明

参数 推荐值 小规模调整 大规模调整 说明
MaxIdleConns 10 5 20 空闲连接数,避免频繁建立连接
MaxOpenConns 50 20 100 最大连接数,保护数据库
ConnMaxLifetime 1h 30m 2h 连接最大生命周期,防止泄漏
ConnMaxIdleTime 10m 5m 15m 空闲连接超时

适用性分析

规模 必要性 性能提升 风险 建议
小规模 (<100 用户) ⭐⭐⭐⭐⭐ +30-50% 极低 必须做
中等规模 (100-1000) ⭐⭐⭐⭐⭐ +50-70% 极低 必须做
大规模 (>1000) ⭐⭐⭐⭐⭐ +70-90% 极低 必须做

结论:无论规模大小都必须做!成本接近 0,收益巨大。


3.2 AutoMigrate 优化(方案 1:条件化 + 性能优化)

问题分析

启动时 AutoMigrate 查询 information_schema 导致:
- 6-25 秒启动延迟
- 每次启动都执行(即使 schema 未变化)
- 在 160ms RTT 网络下被放大 32-300 倍

优化方案

// backend/internal/infrastructure/database.go:20-35
func InitDB(cfg *config.Config) (*gorm.DB, error) {
    // ... existing code ...

    gormConfig := &gorm.Config{
        PrepareStmt:            true,  // ✅ 复用预编译语句,减少元数据查询
        SkipDefaultTransaction: true,  // ✅ 跳过默认事务,加速迁移
    }

    if cfg.Server.Mode == "debug" {
        gormConfig.Logger = logger.Default.LogMode(logger.Info)
    }

    db, err := gorm.Open(postgres.Open(cfg.Database.DSNWithTimezone(cfg.Timezone)), gormConfig)
    if err != nil {
        return nil, err
    }

    // ✅ 条件化 AutoMigrate
    // - 默认执行(保持便利性)
    // - 可通过环境变量跳过(紧急场景)
    if os.Getenv("SKIP_AUTO_MIGRATE") != "true" {
        if err := repository.AutoMigrate(db); err != nil {
            return nil, err
        }
    } else {
        log.Println("⚠️  AutoMigrate skipped (SKIP_AUTO_MIGRATE=true)")
    }

    // ... connection pool config ...
}

使用场景

开发环境:

# 默认执行 AutoMigrate
go run cmd/server/main.go

生产环境(正常启动):

# 默认执行 AutoMigrate(保持便利性)
./sub2api

生产环境(紧急场景/快速重启):

# 跳过 AutoMigrate(启动时间 <1s)
SKIP_AUTO_MIGRATE=true ./sub2api

适用性分析

规模 启动频率 AutoMigrate 影响 建议
小规模 低(每天 1-2 次) 20s 延迟可接受 默认开启
中等规模 中(每天 3-5 次) 20s 延迟有感知 默认开启,紧急时可跳过
大规模 高(滚动发布,频繁重启) 20s 延迟不可接受 考虑迁移工具(见附录)

预期效果

  • ✅ PrepareStmt + SkipDefaultTransaction 可减少 20-30% 的迁移时间
  • ✅ 紧急场景可跳过(启动时间从 6-25s → <1s)
  • ✅ 保持现有便利性(默认行为不变)

3.3 Redis 连接池配置

问题分析

// 当前代码:backend/internal/infrastructure/redis.go:11-15
return redis.NewClient(&redis.Options{
    Addr:     cfg.Redis.Address(),
    Password: cfg.Redis.Password,
    DB:       cfg.Redis.DB,
    // ⚠️ 完全没有配置连接池和超时参数
})

默认值的问题:

  • PoolSize: 10 - 高并发时可能不足
  • MinIdleConns: 0 - 冷启动慢
  • DialTimeout: 5s - 高延迟下可能超时
  • ReadTimeout: 3s - 高延迟下可能超时

优化方案

// backend/internal/infrastructure/redis.go:11-28
func InitRedis(cfg *config.Config) *redis.Client {
    return redis.NewClient(&redis.Options{
        Addr:     cfg.Redis.Address(),
        Password: cfg.Redis.Password,
        DB:       cfg.Redis.DB,

        // ✅ 连接池配置
        PoolSize:     50,                    // 根据并发量调整
        MinIdleConns: 10,                    // 保持最少空闲连接

        // ✅ 超时配置(针对高延迟网络)
        DialTimeout:  5 * time.Second,       // 连接超时
        ReadTimeout:  3 * time.Second,       // 读取超时
        WriteTimeout: 3 * time.Second,       // 写入超时
        PoolTimeout:  4 * time.Second,       // 等待连接池超时

        // ✅ 连接生命周期
        ConnMaxIdleTime: 10 * time.Minute,   // 空闲连接超时
        ConnMaxLifetime: time.Hour,          // 连接最大生命周期
    })
}

适用性分析

规模 推荐 PoolSize 推荐 MinIdleConns 必要性
小规模 20 5 ⭐⭐⭐⭐
中等规模 50 10 ⭐⭐⭐⭐⭐
大规模 100+ 20+ ⭐⭐⭐⭐⭐

3.4 关键复合索引

问题分析

-- ❌ 当前只有单列索引(backend/migrations/001_init.sql)
CREATE INDEX idx_usage_logs_account_id ON usage_logs(account_id);
CREATE INDEX idx_usage_logs_created_at ON usage_logs(created_at);

-- 批量查询示例(backend/internal/repository/usage_log_repo.go:435-459)
SELECT account_id, COUNT(*), SUM(tokens), SUM(cost)
FROM usage_logs
WHERE account_id IN (?, ?, ..., ?)  -- 50 个账户
  AND created_at >= ?               -- 今日 00:00
GROUP BY account_id;

-- ⚠️ 问题:数据库无法有效利用索引
-- 需要扫描所有 50 个账户的历史记录,然后过滤时间
-- 50 个账户 × 平均 10 万条记录 = 500 万行扫描

优化方案

-- ✅ 添加复合索引(INCLUDE 列避免回表)
-- PostgreSQL 11+ 支持,性能提升显著

-- 1. 账户统计专用索引
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_account_created
ON usage_logs(account_id, created_at DESC)
INCLUDE (input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, actual_cost);

-- 2. 用户统计专用索引
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_user_created
ON usage_logs(user_id, created_at DESC)
INCLUDE (actual_cost);

-- 3. API Key 统计专用索引
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_apikey_created
ON usage_logs(api_key_id, created_at DESC)
INCLUDE (actual_cost);

索引设计说明

为什么用 INCLUDE 列?

  • PostgreSQL 11+ 的 Index-Only Scan 特性
  • 索引包含所有查询需要的列,避免回表
  • 在高延迟网络下,减少一次网络往返(~160ms)

为什么用 created_at DESC?

  • 查询大多是按时间倒序(最新的数据)
  • 匹配 ORDER BY created_at DESC 的查询模式

为什么用 CONCURRENTLY?

  • 避免锁表,在线创建索引
  • 生产环境安全

执行步骤

# 1. 在生产环境执行前,先在测试环境验证
psql -h testdb -U user -d sub2api -f backend/migrations/002_add_composite_indexes.sql

# 2. 验证索引是否生效
EXPLAIN ANALYZE
SELECT account_id, COUNT(*), SUM(actual_cost)
FROM usage_logs
WHERE account_id IN (1,2,3,...,50) AND created_at >= '2025-12-27'
GROUP BY account_id;

# 3. 确认执行计划使用了新索引
-- 应该看到 "Index Only Scan using idx_usage_logs_account_created"

适用性分析

规模 数据量 索引大小估算 性能提升 必要性
小规模 <100 万条 ~50 MB +50-70% ⭐⭐⭐⭐
中等规模 100 万-1000 万 ~500 MB +70-90% ⭐⭐⭐⭐⭐
大规模 >1000 万 >1 GB +90-95% ⭐⭐⭐⭐⭐

注意:索引会占用额外的存储空间和写入成本,但对于查询密集型系统,收益远大于成本。


P0 方案总结

优化项 工作量 风险 性能提升 建议
连接池配置 30 分钟 极低 +30-70% 必须做
AutoMigrate 优化 1 小时 极低 启动 -80% 必须做
Redis 配置 30 分钟 极低 +20-40% 必须做
复合索引 1 小时 低 +50-90% 必须做
总计 3 小时 极低 +100-300% 本周内完成

🚀 四、P1 优化方案(推荐执行)

4.1 Redis 批量查询真正批量化

问题分析

// 当前代码:backend/internal/repository/concurrency_cache.go:55-61
// ⚠️ 所谓"批量查询"实际上是 for 循环
func (c *concurrencyCache) GetAccountConcurrencyBatch(ctx context.Context, accountIDs []int64) (map[int64]int, error) {
    result := make(map[int64]int)
    for _, accountID := range accountIDs {
        // 每个账号都执行一次 Lua 脚本 + SCAN
        count, err := c.GetAccountConcurrency(ctx, accountID)
        result[accountID] = count
        // 在 160ms RTT 下,50 个账号 = 8 秒延迟!
    }
    return result, nil
}

根本问题:使用 SCAN 遍历 key 的时间复杂度是 O(N × M)

  • N = 账户数量
  • M = 每个账户的平均 key 数量

优化方案:改用 Hash 结构

// backend/internal/repository/concurrency_cache.go
const accountConcurrencyHash = "account:concurrency"

// ✅ 增加并发数:O(1)
func (c *concurrencyCache) IncrAccountConcurrency(ctx context.Context, accountID int64, delta int) error {
    field := strconv.FormatInt(accountID, 10)
    return c.rdb.HIncrBy(ctx, accountConcurrencyHash, field, int64(delta)).Err()
}

// ✅ 减少并发数:O(1)
func (c *concurrencyCache) DecrAccountConcurrency(ctx context.Context, accountID int64, delta int) error {
    field := strconv.FormatInt(accountID, 10)
    return c.rdb.HIncrBy(ctx, accountConcurrencyHash, field, -int64(delta)).Err()
}

// ✅ 批量查询:O(N) → O(1)
func (c *concurrencyCache) GetAccountConcurrencyBatch(ctx context.Context, accountIDs []int64) (map[int64]int, error) {
    fields := make([]string, len(accountIDs))
    for i, id := range accountIDs {
        fields[i] = strconv.FormatInt(id, 10)
    }

    // 一次 HMGET 查询所有账户
    vals, err := c.rdb.HMGet(ctx, accountConcurrencyHash, fields...).Result()
    if err != nil {
        return nil, err
    }

    result := make(map[int64]int, len(accountIDs))
    for i, v := range vals {
        if v == nil {
            result[accountIDs[i]] = 0
            continue
        }
        count, _ := strconv.Atoi(v.(string))
        result[accountIDs[i]] = count
    }
    return result, nil
}

数据迁移方案

// backend/internal/scripts/migrate_concurrency_to_hash.go
func MigrateToHash(ctx context.Context, rdb *redis.Client) error {
    // 1. 扫描所有旧格式的 key
    iter := rdb.Scan(ctx, 0, "account:*:concurrency", 0).Iterator()

    pipeline := rdb.Pipeline()
    count := 0

    for iter.Next(ctx) {
        key := iter.Val()
        // 提取 account_id
        parts := strings.Split(key, ":")
        if len(parts) != 3 {
            continue
        }
        accountID := parts[1]

        // 获取当前值
        val, err := rdb.Get(ctx, key).Int()
        if err != nil {
            continue
        }

        // 迁移到 Hash
        pipeline.HSet(ctx, accountConcurrencyHash, accountID, val)
        pipeline.Del(ctx, key)

        count++
        if count%100 == 0 {
            pipeline.Exec(ctx)
            pipeline = rdb.Pipeline()
        }
    }

    if count%100 != 0 {
        pipeline.Exec(ctx)
    }

    return iter.Err()
}

适用性分析

规模 账户数 优化前耗时 优化后耗时 性能提升 必要性
小规模 <500 1-2s 0.16s +90% ⭐⭐⭐
中等规模 500-5000 8-15s 0.16s +98% ⭐⭐⭐⭐⭐
大规模 >5000 >30s 0.16s +99% ⭐⭐⭐⭐⭐

结论:

  • 小规模:可选(1-2s 延迟可接受)
  • 中大规模:必须做(8s+ 延迟不可接受)

4.2 Handler 层并行化 I/O

问题分析

// 当前代码:backend/internal/handler/admin/account_handler.go:129-150
// ⚠️ 虽然改成了批量查询,但三个步骤还是串行的

// 1. 查询并发数 - 等待 Redis SCAN
concurrencyCounts, err := h.concurrencyService.GetAccountConcurrencyBatch(ctx, accountIDs)

// 2. 批量查询今日统计 - 等待数据库 GROUP BY
todayStatsMap, err := h.accountUsageService.GetBatchTodayStats(ctx, accountIDs)

// 3. 批量查询使用信息 - 等待数据库查询 + 外部 API
usageInfoMap, err := h.accountUsageService.GetBatchUsageInfo(ctx, accountIDs)

// 总延迟 = delay1 + delay2 + delay3(串行累加!)

在高延迟网络下:

  • 串行:0.16s + 0.5s + 1s = 1.66s
  • 并行:max(0.16s, 0.5s, 1s) = 1s(减少 40%)

优化方案

// backend/internal/handler/admin/account_handler.go:114-180
import "golang.org/x/sync/errgroup"

func (h *AccountHandler) List(c *gin.Context) {
    page, pageSize := response.ParsePagination(c)
    platform := c.Query("platform")
    accountType := c.Query("type")
    status := c.Query("status")
    search := c.Query("search")

    accounts, total, err := h.adminService.ListAccounts(c.Request.Context(), page, pageSize, platform, accountType, status, search)
    if err != nil {
        response.ErrorFrom(c, err)
        return
    }

    // 提取账户 ID 列表
    accountIDs := make([]int64, len(accounts))
    for i, acc := range accounts {
        accountIDs[i] = acc.ID
    }

    // ✅ 并行化执行三个批量查询
    g, ctx := errgroup.WithContext(c.Request.Context())

    var concurrencyCounts map[int64]int
    var todayStatsMap map[int64]*service.WindowStats
    var usageInfoMap map[int64]*service.UsageInfo

    // Goroutine 1: 查询并发数(Redis)
    g.Go(func() error {
        var err error
        concurrencyCounts, err = h.concurrencyService.GetAccountConcurrencyBatch(ctx, accountIDs)
        if err != nil {
            // 容错:Redis 失败不影响其他查询
            concurrencyCounts = make(map[int64]int)
            log.Printf("Failed to get concurrency counts: %v", err)
        }
        return nil  // 不阻塞其他查询
    })

    // Goroutine 2: 查询今日统计(PostgreSQL)
    g.Go(func() error {
        var err error
        todayStatsMap, err = h.accountUsageService.GetBatchTodayStats(ctx, accountIDs)
        if err != nil {
            todayStatsMap = make(map[int64]*service.WindowStats)
            log.Printf("Failed to get today stats: %v", err)
        }
        return nil
    })

    // Goroutine 3: 查询使用信息(PostgreSQL + 可能的外部 API)
    // 这个可选,因为可能很慢
    // g.Go(func() error {
    //     var err error
    //     usageInfoMap, err = h.accountUsageService.GetBatchUsageInfo(ctx, accountIDs)
    //     if err != nil {
    //         usageInfoMap = make(map[int64]*service.UsageInfo)
    //     }
    //     return nil
    // })

    // 等待所有查询完成
    _ = g.Wait()

    // 组装响应
    result := make([]AccountWithConcurrency, len(accounts))
    for i := range accounts {
        accountDTO := dto.AccountFromService(&accounts[i])

        // 附加今日统计
        if stats, ok := todayStatsMap[accounts[i].ID]; ok {
            accountDTO.TodayStats = stats
        }

        // 附加使用信息(如果查询了)
        if usageInfo, ok := usageInfoMap[accounts[i].ID]; ok {
            accountDTO.UsageInfo = usageInfo
        }

        result[i] = AccountWithConcurrency{
            Account:            accountDTO,
            CurrentConcurrency: concurrencyCounts[accounts[i].ID],
        }
    }

    response.Paginated(c, result, total, page, pageSize)
}

适用性分析

规模 账户数 串行延迟 并行延迟 性能提升 必要性
小规模 <500 0.5-1s 0.3-0.5s +30-50% ⭐⭐⭐
中等规模 500-5000 1-3s 0.5-1s +50-70% ⭐⭐⭐⭐⭐
大规模 >5000 >5s 1-2s +70-80% ⭐⭐⭐⭐⭐

注意事项:

  • ✅ 使用 errgroup 统一管理 Goroutine 生命周期
  • ✅ 每个查询独立容错,避免级联失败
  • ✅ 使用 context 传递超时和取消信号

4.3 前端轮询优化

问题分析

// 当前代码:frontend/src/stores/subscriptions.ts:11-12
const CACHE_TTL_MS = 60_000  // 60 秒缓存

// frontend/src/stores/subscriptions.ts:84-91
pollerInterval = setInterval(() => {
    fetchActiveSubscriptions(true).catch(...)  // ⚠️ 强制刷新,绕过缓存!
}, 5 * 60 * 1000)  // 5 分钟轮询

// ⚠️ 问题:
// 1. force=true 每次都穿透缓存
// 2. 后台标签页也在轮询(浪费资源)
// 3. 缓存 TTL (60s) 远小于轮询间隔 (300s),缓存无效

优化方案

// frontend/src/stores/subscriptions.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import subscriptionsAPI from '@/api/subscriptions'
import type { UserSubscription } from '@/types'

// ✅ 缓存 TTL 调整为 5 分钟(匹配轮询间隔)
const CACHE_TTL_MS = 5 * 60 * 1000

let requestGeneration = 0

export const useSubscriptionStore = defineStore('subscriptions', () => {
  const activeSubscriptions = ref<UserSubscription[]>([])
  const loading = ref(false)
  const loaded = ref(false)
  const lastFetchedAt = ref<number | null>(null)

  let activePromise: Promise<UserSubscription[]> | null = null
  let pollerInterval: ReturnType<typeof setInterval> | null = null

  const hasActiveSubscriptions = computed(() => activeSubscriptions.value.length > 0)

  async function fetchActiveSubscriptions(force = false): Promise<UserSubscription[]> {
    const now = Date.now()

    if (
      !force &&
      loaded.value &&
      lastFetchedAt.value &&
      now - lastFetchedAt.value < CACHE_TTL_MS
    ) {
      return activeSubscriptions.value
    }

    if (activePromise) {
      return activePromise
    }

    const currentGeneration = ++requestGeneration

    loading.value = true
    activePromise = subscriptionsAPI
      .getActiveSubscriptions()
      .then((data) => {
        if (currentGeneration === requestGeneration) {
          activeSubscriptions.value = data
          loaded.value = true
          lastFetchedAt.value = Date.now()
        }
        return data
      })
      .catch((error) => {
        console.error('Failed to fetch active subscriptions:', error)
        throw error
      })
      .finally(() => {
        loading.value = false
        activePromise = null
      })

    return activePromise
  }

  function startPolling() {
    if (pollerInterval) return

    // ✅ 添加页面可见性监听
    document.addEventListener('visibilitychange', handleVisibilityChange)

    pollerInterval = setInterval(() => {
      // ✅ 只在页面可见时轮询
      if (document.visibilityState !== 'visible') {
        console.debug('Page hidden, skipping subscription poll')
        return
      }

      // ✅ 不要强制刷新,使用缓存策略
      fetchActiveSubscriptions(false).catch((error) => {
        console.error('Subscription polling failed:', error)
      })
    }, 5 * 60 * 1000)
  }

  function stopPolling() {
    if (pollerInterval) {
      clearInterval(pollerInterval)
      pollerInterval = null
    }
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  }

  // ✅ 页面可见性变化处理
  function handleVisibilityChange() {
    if (document.visibilityState === 'visible') {
      // 页面变为可见时立即刷新一次
      console.debug('Page visible, refreshing subscriptions')
      fetchActiveSubscriptions(true).catch(console.error)
    }
  }

  function clear() {
    requestGeneration++
    activeSubscriptions.value = []
    loaded.value = false
    lastFetchedAt.value = null
    stopPolling()
  }

  function invalidateCache() {
    lastFetchedAt.value = null
  }

  return {
    activeSubscriptions,
    loading,
    hasActiveSubscriptions,
    fetchActiveSubscriptions,
    startPolling,
    stopPolling,
    clear,
    invalidateCache
  }
})

适用性分析

规模 用户行为 优化前请求量 优化后请求量 减少幅度 必要性
小规模 多标签页 5 标签 × 12 次/小时 = 60 1 × 12 = 12 -80% ⭐⭐⭐⭐
中等规模 多标签页 + 后台 3 标签 × 12 × 100 用户 = 3600 12 × 100 = 1200 -67% ⭐⭐⭐⭐⭐
大规模 同上 3 × 12 × 1000 = 36000 12 × 1000 = 12000 -67% ⭐⭐⭐⭐⭐

P1 方案总结

优化项 工作量 风险 性能提升 建议
Redis Hash 重构 4 小时 中(需要数据迁移) +90-98% 中等规模以上必须
Handler 并行化 4 小时 低 +30-70% 中等规模以上必须
前端轮询优化 2 小时 极低 后端 -67% 负载 推荐所有规模
总计 10 小时 中-低 +50-200% 2 周内完成

📈 五、P2 优化方案(可选执行)

5.1 本地内存缓存层

问题分析

即使使用 Redis,远程调用仍有 160ms 延迟。对于高频、低变化的数据,可以引入本地缓存。

优化方案

// backend/internal/repository/cached_account_repo.go
import "github.com/patrickmn/go-cache"

type CachedAccountRepository struct {
    repo  AccountRepository
    cache *cache.Cache
}

func NewCachedAccountRepository(repo AccountRepository) *CachedAccountRepository {
    return &CachedAccountRepository{
        repo:  repo,
        cache: cache.New(5*time.Minute, 10*time.Minute),
    }
}

func (r *CachedAccountRepository) GetByID(ctx context.Context, id int64) (*Account, error) {
    key := fmt.Sprintf("account:%d", id)

    // 尝试从本地缓存读取
    if cached, found := r.cache.Get(key); found {
        return cached.(*Account), nil  // ✅ 0 网络开销
    }

    // 缓存未命中,查询数据库
    account, err := r.repo.GetByID(ctx, id)
    if err != nil {
        return nil, err
    }

    // 写入本地缓存
    r.cache.Set(key, account, cache.DefaultExpiration)
    return account, nil
}

// 更新时需要失效缓存
func (r *CachedAccountRepository) Update(ctx context.Context, account *Account) error {
    err := r.repo.Update(ctx, account)
    if err != nil {
        return err
    }

    // 失效本地缓存
    key := fmt.Sprintf("account:%d", account.ID)
    r.cache.Delete(key)

    return nil
}

适合缓存的数据

数据类型 变化频率 查询频率 缓存 TTL 是否适合
账户元数据 (name, type, platform) 低 极高 5-10 分钟 ✅ 强烈推荐
用户信息 低 高 5 分钟 ✅ 推荐
分组配置 极低 高 10-30 分钟 ✅ 推荐
API Key 元数据 低 极高 5 分钟 ✅ 强烈推荐
使用统计 高 中 不适合 ❌ 实时性要求高
账单数据 中 低 不适合 ❌ 一致性要求高

适用性分析

规模 QPS 缓存命中率 性能提升 必要性
小规模 <10 70-80% +50% ⭐⭐
中等规模 10-100 80-90% +300% ⭐⭐⭐⭐
大规模 >100 90-95% +1000% ⭐⭐⭐⭐⭐

风险:

  • ⚠️ 多实例部署时可能出现数据不一致(缓存 TTL 期间)
  • 缓解措施:TTL 设置较短(5 分钟),且更新时主动失效

5.2 数据库迁移到低延迟区域

成本效益分析

方案 RTT 延迟 启动时间 API 响应 月成本 适用场景
当前远程 DB 160ms <1s* 160-500ms 低 开发/小规模
同区域云 RDS 5-10ms <1s* 20-50ms 中 生产环境
本地 Docker <1ms <1s* 10-30ms 低 开发环境

*假设已实施 P0 优化

建议

  • 开发环境:Docker Compose 本地部署(延迟 <1ms)
  • 生产环境:迁移到同区域云 RDS(如腾讯云/阿里云/AWS RDS)
  • 远程数据库:保留作为备份/只读副本

📊 六、性能提升预估

6.1 启动时间优化

优化阶段 优化前 优化后 改善幅度
基线 6-25s - -
+ P0(连接池 + AutoMigrate 优化) 6-25s <1s -96% ✅
+ P2(本地缓存) 6-25s <0.5s -98%

6.2 账户列表接口(50 个账户)

优化阶段 优化前 优化后 改善幅度
基线(N+1 查询) 16s - -
当前(批量但串行) 16s 2-5s -68%
+ P0(连接池 + 索引) 16s 0.5-1s -93%
+ P1(Redis Hash + 并行化) 16s 0.16-0.3s -98% ✅
+ P2(本地缓存) 16s <0.1s -99% 🚀

6.3 数据库负载优化

指标 优化前 P0 后 P1 后 P2 后
每秒查询数(QPS) 50-100 20-30 10-20 5-10
慢查询比例 >30% <10% <5% <1%
连接数峰值 不可控 <50 <50 <50
CPU 使用率 60-80% 40-60% 20-40% <20%

6.4 不同规模下的推荐方案

规模 用户数 账户数 QPS 推荐方案 预期效果
小规模 <100 <500 <10 P0 启动 <1s,列表 0.5-1s
中等规模 100-1000 500-5000 10-100 P0 + P1 启动 <1s,列表 0.16-0.3s
大规模 >1000 >5000 >100 P0 + P1 + P2 启动 <0.5s,列表 <0.1s

🗓️ 七、实施时间表

第 1 周(P0 - 必须执行)

Day 1-2:基础设施优化

  • [ ] 配置数据库连接池(2 小时)
  • [ ] 配置 Redis 连接池(1 小时)
  • [ ] AutoMigrate 条件化优化(1 小时)
  • [ ] 本地测试验证(4 小时)

Day 3:数据库索引优化

  • [ ] 在测试环境添加复合索引(1 小时)
  • [ ] EXPLAIN ANALYZE 验证索引效果(1 小时)
  • [ ] 生产环境执行(CONCURRENTLY,2 小时)
  • [ ] 监控慢查询日志(持续)

Day 4-5:测试和部署

  • [ ] 压力测试(模拟 50-100 并发用户,4 小时)
  • [ ] 回归测试(功能验证,4 小时)
  • [ ] 生产环境部署(灰度发布,4 小时)
  • [ ] 监控观察(24 小时)

预期成果:

  • ✅ 启动时间从 6-25s → <1s
  • ✅ 账户列表从 2-5s → 0.5-1s
  • ✅ 数据库 QPS 降低 50%

第 2-3 周(P1 - 推荐执行)

Week 2 Day 1-2:Redis 重构

  • [ ] 实现 Hash 结构的并发数管理(4 小时)
  • [ ] 编写数据迁移脚本(2 小时)
  • [ ] 单元测试 + 集成测试(4 小时)
  • [ ] 测试环境数据迁移(2 小时)

Week 2 Day 3-4:Handler 并行化

  • [ ] 重构 account_handler.go List 方法(4 小时)
  • [ ] 重构其他批量查询接口(user, apikey)(4 小时)
  • [ ] E2E 测试(4 小时)

Week 2 Day 5:前端优化

  • [ ] 订阅轮询优化(2 小时)
  • [ ] 页面可见性检测(1 小时)
  • [ ] 前端性能测试(2 小时)

Week 3:部署和验证

  • [ ] 生产环境 Redis 数据迁移(2 小时)
  • [ ] 生产环境部署(灰度发布,4 小时)
  • [ ] 压力测试(100+ 并发,8 小时)
  • [ ] 性能监控和调优(持续)

预期成果:

  • ✅ 账户列表从 0.5-1s → 0.16-0.3s
  • ✅ Redis 负载降低 98%
  • ✅ 前端无效轮询减少 80%

第 4-6 周(P2 - 可选执行)

Week 4-5:本地缓存层

  • [ ] 选型和评估(go-cache vs ristretto,4 小时)
  • [ ] 实现 CachedAccountRepository(8 小时)
  • [ ] 实现 CachedUserRepository(4 小时)
  • [ ] 缓存失效策略(4 小时)
  • [ ] 性能测试和调优(8 小时)

Week 6:监控和长期规划

  • [ ] 部署 Prometheus + Grafana(8 小时)
  • [ ] 配置慢查询告警(4 小时)
  • [ ] 数据库迁移方案评估(4 小时)
  • [ ] 编写性能优化文档(4 小时)

预期成果:

  • ✅ 账户列表 <0.1s
  • ✅ 数据库负载降低 90%
  • ✅ 完整的性能监控体系

⚠️ 八、风险评估和应对

8.1 技术风险

风险 概率 影响 应对措施
索引创建锁表 中 高 使用 CONCURRENTLY 在线创建
连接池配置不当 低 中 在测试环境验证,逐步调整参数
Redis 数据迁移失败 低 高 编写回滚脚本,分批迁移,保留旧数据
本地缓存一致性问题 中 中 TTL 设置较短,更新时主动失效
并发查询超时 低 中 设置合理的 context timeout

8.2 业务风险

风险 概率 影响 应对措施
优化后功能异常 低 高 充分的回归测试,灰度发布
性能提升不达预期 低 中 EXPLAIN ANALYZE 验证,逐步调优
用户体验短暂下降 中 低 在低峰期部署,快速回滚机制

8.3 回滚方案

P0 优化回滚:

# 1. 回滚代码
git revert <commit-hash>

# 2. 重启服务
systemctl restart sub2api

# 3. 索引可以保留(不影响功能,只影响性能)
# 如需删除:
# DROP INDEX CONCURRENTLY idx_usage_logs_account_created;

P1 优化回滚:

# 1. Redis Hash → 旧格式迁移脚本
go run backend/internal/scripts/rollback_concurrency_hash.go

# 2. 代码回滚
git revert <commit-hash>

# 3. 重启服务

🎯 九、需要讨论的决策点

9.1 P0 方案(建议全部采纳)

  • [ ] 连接池参数:是否需要根据实际并发量调整?

    • 建议:先用推荐值,上线后根据监控调整
  • [ ] AutoMigrate 策略:是否接受默认开启(方便)vs 默认关闭(安全)?

    • 建议:默认开启,保持便利性
  • [ ] 索引创建时机:是否在业务低峰期执行?

    • 建议:测试环境验证后,在凌晨 2-4 点执行

9.2 P1 方案(建议中等规模以上采纳)

  • [ ] Redis Hash 迁移:是否需要保留旧数据一段时间?

    • 建议:保留 7 天,确保无问题后清理
  • [ ] Handler 并行化范围:是否需要优化所有列表接口?

    • 建议:优先账户列表、用户列表,其他按需
  • [ ] 前端轮询频率:5 分钟是否合适?是否需要可配置?

    • 建议:保持 5 分钟,暂不可配置

9.3 P2 方案(建议大规模采纳)

  • [ ] 本地缓存库选型:go-cache vs ristretto?

    • 建议:go-cache(简单易用),ristretto(高性能但复杂)
  • [ ] 缓存一致性策略:是否可以接受 5 分钟的数据延迟?

    • 建议:对于元数据(账户名、用户名)可以接受
  • [ ] 数据库迁移:是否考虑迁移到低延迟区域?

    • 建议:大规模时必须考虑,中等规模可先观察

📈 十、成功标准

10.1 性能指标

指标 当前 P0 目标 P1 目标 P2 目标
启动时间 6-25s <1s <1s <0.5s
账户列表(50 个) 2-5s 0.5-1s 0.16-0.3s <0.1s
P95 响应时间 >3s <1s <0.5s <0.3s
数据库 QPS 50-100 20-30 10-20 5-10
慢查询比例 >30% <10% <5% <1%

10.2 用户体验

  • [ ] 启动时间 <1s(用户无感知)
  • [ ] 页面加载时间 <0.5s(流畅)
  • [ ] 无明显的 loading 闪烁
  • [ ] 后台标签页不影响性能

10.3 系统稳定性

  • [ ] 连接数峰值 <50(可控)
  • [ ] CPU 使用率 <60%(健康)
  • [ ] 内存使用稳定(无泄漏)
  • [ ] 慢查询日志 <10 条/小时

📚 附录

A. 备选方案:使用 golang-migrate 替代 AutoMigrate

如果未来用户规模扩大,或需要更严格的变更管理,可以引入专用迁移工具。

安装

go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest

使用

# 1. 创建迁移文件
migrate create -ext sql -dir backend/migrations_versioned -seq add_user_field

# 2. 编写迁移 SQL
# backend/migrations_versioned/000001_add_user_field.up.sql
ALTER TABLE users ADD COLUMN new_field VARCHAR(255);

# backend/migrations_versioned/000001_add_user_field.down.sql
ALTER TABLE users DROP COLUMN IF EXISTS new_field;

# 3. 执行迁移
migrate -path backend/migrations_versioned \
        -database "postgres://user:pass@host/db" \
        up

# 4. 启动服务(跳过 AutoMigrate)
SKIP_AUTO_MIGRATE=true ./sub2api

优缺点

优点:

  • ✅ 可版本化管理(Git 追踪)
  • ✅ 可回滚(down.sql)
  • ✅ 启动快(不需要比对 schema)
  • ✅ 更安全(显式变更)

缺点:

  • ⚠️ 需要额外维护迁移文件
  • ⚠️ 部署流程稍微复杂

建议:

  • 小规模:保持 AutoMigrate(方便)
  • 中等规模:根据实际情况决定
  • 大规模:必须使用 migrate(安全、可控)

B. 性能监控方案

安装 Prometheus + Grafana

# docker-compose.monitoring.yml
version: '3.8'

services:
  prometheus:
    image: prom/prometheus:latest
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus
    ports:
      - "9090:9090"

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
    volumes:
      - grafana_data:/var/lib/grafana

volumes:
  prometheus_data:
  grafana_data:

集成到 Go 代码

// backend/internal/infrastructure/metrics.go
import (
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
    dbQueryDuration = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Name:    "db_query_duration_seconds",
            Help:    "Database query duration",
            Buckets: []float64{.001, .005, .01, .05, .1, .5, 1, 5},
        },
        []string{"query_type"},
    )

    redisQueryDuration = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Name:    "redis_query_duration_seconds",
            Help:    "Redis query duration",
            Buckets: []float64{.001, .005, .01, .05, .1, .5},
        },
        []string{"command"},
    )
)

func init() {
    prometheus.MustRegister(dbQueryDuration)
    prometheus.MustRegister(redisQueryDuration)
}

// 在 Gin 中暴露 metrics 端点
r.GET("/metrics", gin.WrapH(promhttp.Handler()))

使用示例

// 记录数据库查询时间
start := time.Now()
result := db.Find(&users)
dbQueryDuration.WithLabelValues("get_users").Observe(time.Since(start).Seconds())

C. 参考资料


IanShaw027 avatar Dec 27 '25 14:12 IanShaw027

改动太大,替换方案

IanShaw027 avatar Dec 29 '25 05:12 IanShaw027