mcpField
C
cloudflare-workers-performance

cloudflare-workers-performance

github.com/secondsky云与 DevOps240319 次安装5 周前更新
代码仓库

关于 cloudflare-workers-performance

面向优化 Cloudflare Workers 的开发者的参考技能,涵盖 CPU、内存、延迟、缓存和包体积优化,并提供相关参考资料、模板及性能分析脚本。

主要功能

  1. 01CPU 与热点路径优化
  2. 02流式处理和内存管理
  3. 03Cache API 与批量操作
  4. 04包体积和冷启动优化指引
  5. 05模板及性能分析脚本

适用场景

  1. 01降低 Worker 的 CPU 使用和延迟
  2. 02避免缓冲方式处理大型负载
  3. 03排查内存或冷启动问题
  4. 04添加缓存或性能监控

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/claude-skills --skill cloudflare-workers-performance

安装后在 Claude Code 中输入/cloudflare-workers-performance确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
bundle-optimization.md
caching-strategies.md
cold-starts.md
cpu-optimization.md
memory-optimization.md
scripts/
benchmark.sh
profile-worker.sh
templates/
caching-layer.ts
optimized-worker.ts
performance-middleware.ts

详细介绍

Cloudflare Workers 性能优化

最大限度提升 Worker 性能并降低延迟的技巧。

快速见效

// 1. Avoid unnecessary cloning
// ❌ Bad: Clones entire request
const body = await request.clone().json();

// ✅ Good: Parse directly when not re-using body
const body = await request.json();

// 2. Use streaming instead of buffering
// ❌ Bad: Buffers entire response
const text = await response.text();
return new Response(transform(text));

// ✅ Good: Stream transformation
return new Response(response.body.pipeThrough(new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(process(chunk));
  }
})));

// 3. Cache expensive operations
const cache = caches.default;
const cached = await cache.match(request);
if (cached) return cached;

关键规则

  1. 控制在 CPU 限制以内 - 10ms(免费版)、30ms(付费版)、50ms(无绑定)
  2. 尽量减少冷启动 - 将包体积控制在 < 1MB,避免动态导入
  3. 使用 Cache API - 在边缘缓存响应
  4. 流式传输大型负载 - 不要缓冲整个响应
  5. 批量处理操作 - 合并多个 KV/D1 调用

十大性能错误

错误症状修复方法
超出 CPU 限制Worker 被终止优化热点路径,使用流式处理
冷启动延迟首个请求速度慢缩小包体积,避免顶层 await
内存压力GC 缓慢、超时流式处理数据,避免使用大型数组
KV 延迟读取缓慢使用 Cache API,批量读取
D1 查询缓慢延迟较高添加索引,优化 SQL
包体积过大冷启动缓慢使用 Tree Shaking,拆分代码
阻塞操作请求超时使用 Promise.all、流式处理
不必要的克隆内存激增仅在需要时克隆
缺少缓存重复计算实现缓存层
同步操作CPU 峰值使用异步替代方案

CPU 优化

分析热点路径
async function profiledHandler(request: Request): Promise<Response> {
  const timing: Record<string, number> = {};

  const time = async <T>(name: string, fn: () => Promise<T>): Promise<T> => {
    const start = Date.now();
    const result = await fn();
    timing[name] = Date.now() - start;
    return result;
  };

  const data = await time('fetch', () => fetchData());
  const processed = await time('process', () => processData(data));
  const response = await time('serialize', () => serialize(processed));

  console.log('Timing:', timing);
  return new Response(response);
}
优化 JSON 操作
// For large JSON, use streaming parser
import { JSONParser } from '@streamparser/json';

async function parseStreamingJSON(stream: ReadableStream): Promise<unknown[]> {
  const parser = new JSONParser();
  const results: unknown[] = [];

  parser.onValue = (value) => results.push(value);

  for await (const chunk of stream) {
    parser.write(chunk);
  }

  return results;
}

内存优化

避免使用大型数组
// ❌ Bad: Loads all into memory
const items = await db.prepare('SELECT * FROM items').all();
const processed = items.results.map(transform);

// ✅ Good: Process in batches
async function* batchProcess(db: D1Database, batchSize = 100) {
  let offset = 0;
  while (true) {
    const { results } = await db
      .prepare('SELECT * FROM items LIMIT ? OFFSET ?')
      .bind(batchSize, offset)
      .all();

    if (results.length === 0) break;

    for (const item of results) {
      yield transform(item);
    }
    offset += batchSize;
  }
}

缓存策略

多层缓存
interface CacheLayer {
  get(key: string): Promise<unknown | null>;
  set(key: string, value: unknown, ttl?: number): Promise<void>;
}

// Layer 1: In-memory (request-scoped)
const memoryCache = new Map<string, unknown>();

// Layer 2: Cache API (edge-local)
const edgeCache: CacheLayer = {
  async get(key) {
    const response = await caches.default.match(new Request(`https://cache/${key}`));
    return response ? response.json() : null;
  },
  async set(key, value, ttl = 60) {
    await caches.default.put(
      new Request(`https://cache/${key}`),
      new Response(JSON.stringify(value), {
        headers: { 'Cache-Control': `max-age=${ttl}` }
      })
    );
  }
};

// Layer 3: KV (global)
// Use env.KV.get/put

包体积优化

// 1. Tree-shake imports
// ❌ Bad
import * as lodash from 'lodash';

// ✅ Good
import { debounce } from 'lodash-es';

// 2. Lazy load heavy dependencies
let heavyLib: typeof import('heavy-lib') | undefined;

async function getHeavyLib() {
  if (!heavyLib) {
    heavyLib = await import('heavy-lib');
  }
  return heavyLib;
}

何时加载参考资料

根据任务加载特定参考资料:

  • 要优化 CPU 使用率? → 加载 references/cpu-optimization.md
  • 有内存问题? → 加载 references/memory-optimization.md
  • 要实现缓存? → 加载 references/caching-strategies.md
  • 要缩小包体积? → 加载 references/bundle-optimization.md
  • 有冷启动问题? → 加载 references/cold-starts.md

模板

模板用途使用时机
templates/performance-middleware.ts性能监控添加计时/性能分析
templates/caching-layer.ts多层缓存实现缓存
templates/optimized-worker.ts性能模式创建经过优化的 Worker

脚本

脚本用途命令
scripts/benchmark.sh负载测试./benchmark.sh <url>
scripts/profile-worker.shCPU 性能分析./profile-worker.sh

资源

评论

支持 Markdown