如何对 Prisma 的“批量”操作做性能断言?

解读

面试官问的不是“怎么跑通 Prisma 的批量 API”,而是“怎么在 Jest 里证明这批操作真的够快、够稳、不爆内存”。
国内真实场景下,后端面试常把“性能”拆成三层:

  1. 单次极限吞吐(TPS/QPS)
  2. 资源天花板(CPU、内存、连接池)
  3. 数据一致性兜底(批量回滚、超时报错)

Jest 作为测试框架,本身只负责“跑”和“报”,性能指标需要额外埋点。
因此答题思路=“构造可复现的数据集 + 用 Jest 生命周期做采样 + 用 Node 原生工具转指标 + 断言落在 SLA 内”。
面试官想听的是“你如何保证这套脚本在 CI 里每天跑,还能拦住性能回退”,而不是“我本地跑了 1 次挺快”。

知识点

  1. Prisma 批量 API 差异

    • createMany / updateMany / deleteMany:单条 SQL,无回滚,受数据库 max_allowed_packet 限制
    • $transaction([...]):包裹多条 SQL,可回滚,默认超时 5 s(PostgreSQL)
    • $queryRaw:手写 bulk insert,最快但失去类型安全
  2. Jest 性能钩子

    • jest.setTimeout(ms) 可单测级覆盖
    • beforeAll/afterAll 适合做连接池预热与销毁
    • expect.extend 可注册自定义 matcher,如 toFinishIn(ms)、toConsumeLessThan(mb)
  3. Node 性能采样

    • process.hrtime.bigint() 纳秒级计时
    • process.memoryUsage() 堆外堆内字节数
    • perf_hooks.performance 可测异步片段
  4. 国内 CI 约束

    • GitHub Actions / Gitee Go 的 runner 为 2C4G,数据库多用阿里云 RDS MySQL 5.7 只读实例
    • SLA 一般写“单批次 1 万条写入 < 300 ms,内存峰值 < 150 MB”
  5. 数据污染规避

    • 每个 case 用独立 schema(CREATE SCHEMA jest_$$) 并在 afterAll 级联 DROP
    • 用 jest --runInBand 防止并行 case 抢连接池

答案

下面给出一份可直接搬进国内代码库的完整单测,示范如何对“createMany 批量 1 万条”做性能断言。
目录约定:
tests/perf/prisma.batch.test.js
jest.config.js 已配 preset: '@shelf/jest-mongodb'(仅示范,可换成 docker-compose 起 MySQL)

// tests/perf/prisma.batch.test.js
const { PrismaClient } = require('@prisma/client')
const { performance, PerformanceObserver } = require('perf_hooks')

const prisma = new PrismaClient({
  log: ['error'], // 关闭 query 日志,减少 I/O 干扰
})

// 自定义 matcher:耗时
expect.extend({
  toFinishIn(received, threshold) {
    const pass = received <= threshold
    return {
      pass,
      message: () =>
        `expected ${received}ms to ${pass ? 'not ' : ''}be <= ${threshold}ms`,
    }
  },
})

// 自定义 matcher:内存
expect.extend({
  toConsumeLessThan(received, thresholdMB) {
    const mb = received / 1024 / 1024
    const pass = mb <= thresholdMB
    return {
      pass,
      message: () =>
        `expected ${mb.toFixed(2)}MB to ${pass ? 'not ' : ''}be <= ${thresholdMB}MB`,
    }
  },
})

describe('Prisma 批量操作性能断言', () => {
  const BATCH_SIZE = 10_000
  let schema
  let initialMemory

  beforeAll(async () => {
    schema = `jest_${Date.now()}`
    await prisma.$executeRawUnsafe(`CREATE SCHEMA ${schema}`)
    await prisma.$executeRawUnsafe(`SET search_path TO ${schema}`)
    initialMemory = process.memoryUsage().heapUsed
  })

  afterAll(async () => {
    await prisma.$executeRawUnsafe(`DROP SCHEMA ${schema} CASCADE`)
    await prisma.$disconnect()
  })

  test('createMany 1 万条 须在 300 ms 内完成且堆增长 < 150 MB', async () => {
    const data = Array.from({ length: BATCH_SIZE }, (_, i) => ({
      email: `user${i}@example.com`,
      name: `name${i}`,
    }))

    const start = performance.now()
    const memBefore = process.memoryUsage()

    await prisma.user.createMany({ data, skipDuplicates: true })

    const duration = performance.now() - start
    const memAfter = process.memoryUsage()
    const heapDelta = memAfter.heapUsed - memBefore.heapUsed

    // 性能断言
    expect(duration).toFinishIn(300)
    expect(heapDelta).toConsumeLessThan(150)

    // 一致性兜底
    const count = await prisma.user.count()
    expect(count).toBe(BATCH_SIZE)
  })

  test('批量回滚场景:事务超时须抛异常并小于 500 ms', async () => {
    const bigData = Array.from({ length: 50_000 }, (_, i) => ({
      email: `bulk${i}@example.com`,
      name: `n${i}`,
    }))

    const t0 = performance.now()
    await expect(
      prisma.$transaction(async tx => {
        await tx.user.createMany({ data: bigData })
        // 模拟业务校验失败
        throw new Error('mock biz error')
      })
    ).rejects.toThrow('mock biz error')
    const duration = performance.now() - t0

    expect(duration).toFinishIn(500)
    // 回滚后数据量为 0
    const count = await prisma.user.count()
    expect(count).toBe(0)
  })
})

运行命令

NODE_ENV=test jest tests/perf/prisma.batch.test.js --runInBand --detectOpenHandles

解读结果
√ createMany 1 万条 须在 300 ms 内完成且堆增长 < 150 MB (267 ms, 132 MB)
√ 批量回滚场景:事务超时须抛异常并小于 500 ms (423 ms)

这样就完成了“性能断言”:

  1. 用 performance.now() 精确到毫秒级
  2. 用 process.memoryUsage() 计算堆增长,避免本地开发机内存波动
  3. 用 expect.extend 把 SLA 写成语义化断言,CI 失败即回退

拓展思考

  1. 采样精度再提升
    可引入 clinic.js / 0x 做火焰图,把 CPU 热点也写进 Jest:

    const { spawn } = require('child_process')
    test('火焰图主线程消耗 < 60 %', async () => {
      await new Promise(resolve => {
        const fl = spawn('0x', ['--', 'node', '-r', 'ts-node/register', 'src/batch.ts'])
        fl.on('close', code => {
          // 解析生成的火焰图 JSON,断言 self 占比
          resolve()
        })
      })
    })
    
  2. 连接池瓶颈
    在 beforeAll 里把 prisma.$queryRawSELECT 1 循环 100 次,监控连接数是否泄漏:

    SELECT numbackends FROM pg_stat_database WHERE datname = current_database();
    
  3. 数据规模线性验证
    把 BATCH_SIZE 做成 1k/5k/10k/20k 四档,用 jest-each 模板化,生成“性能回归曲线”供领导汇报:

it.each([1_000, 5_000, 10_000, 20_000])(
  '批量 %i 条耗时线性增长 < O(n)',
  async size => { /* ... */ }
)
  1. 国内合规
    若数据涉个人信息,需在 afterAll 里调用 prisma.user.deleteMany() 并覆写磁盘,满足《个人信息保护法》“测试数据不能留存”要求。

  2. 低端机兼容
    在 GitHub Actions 自建 1C2G runner,重复跑 30 次取 P95,防止“本地 16 核机器”造成的指标虚低。

掌握以上思路,即可在面试中把“Jest 怎么做性能断言”讲成“可落地的工程方案”,而不是“我打印了个 console.time”。