cloudflare-workers-performance
/cloudflare-workers-performance
Cloudflare Workers performance optimization with CPU, memory, caching, bundle size. Use for slow workers, high latency, cold starts, or encountering CPU limits, memory issues, timeout errors.
- Author
- secondsky ↗
- Repository
- claude-skills ↗
- Licence
- MIT
- Last repository change
- 26.09.2026
Assessment and security
- Files in this package
- 11
- Scripts
- 5
- HTML comments
- 0
- URLs in SKILL.md
- 5
No signals detected. Repository changed on 26.09.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
- 5 scripts in this package. Review them before installing, as Claude may execute them.
Scripts: scripts/benchmark.sh, scripts/profile-worker.sh, templates/caching-layer.ts, templates/optimized-worker.ts, templates/performance-middleware.ts
What it does and when to use it
Cloudflare Workers performance optimization with CPU, memory, caching, bundle size. Use for slow workers, high latency, cold starts, or encountering CPU limits, memory issues, timeout errors.
Original author description
Cloudflare Workers performance optimization with CPU, memory, caching, bundle size. Use for slow workers, high latency, cold starts, or encountering CPU limits, memory issues, timeout errors.
How it works
- Quick Wins
- Critical Rules
- Top 10 Performance Errors
- CPU Optimization
- Memory Optimization
- Caching Strategies
- Bundle Optimization
- When to Load References
- Templates
- Scripts
SKILL.md preview
---
name: cloudflare-workers-performance
description: Cloudflare Workers performance optimization with CPU, memory, caching, bundle size. Use for slow workers, high latency, cold starts, or encountering CPU limits, memory issues, timeout errors.
license: MIT
---
# Cloudflare Workers Performance Optimization
Techniques for maximizing Worker performance and minimizing latency.
## Quick Wins
```typescript
// 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;
```
## Critical Rules
1. **Stay under CPU limits** - 10ms (free), 30ms (paid), 50ms (unbound)
2. **Minimize cold starts** - Keep bundles < 1MB, avoid dynamic imports
3. **Use Cache API** - Cache responses at the edge
4. **Stream large payloads** - Don't buffer entire responses
5. **Batch operations** - Combine multiple KV/D1 calls
## Top 10 Performance Errors
| Error | Symptom | Fix |
|-------|---------|-----|
| CPU limit exceeded | Worker terminated | Optimize hot paths, use streaming |
| Cold start latency | First request slow | Reduce bundle size, avoid top-level await |
| Memory pressure | Slow GC, timeouts | Stream data, avoid large arrays |
| KV latency | Slow reads | Use Cache API, batch reads |
| D1 slow queries | High latency | Add indexes, optimize SQL |
| Large bundles | Slow cold starts | Tree-shake, code split |
| Blocking operations | Request timeouts | Use Promise.all, streaming |
| Unnecessary cloning | Memory spike | Only clone when needed |
| Missing cache | Repeated computation | Implement caching layer |
| Sync operations | CPU spikes | Use async alternatives |
## CPU Optimization
### Profile Hot Paths
```typescript
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);
}
```
### Optimize JSON Operations
```typescript
// 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;
}
```
## Memory Optimization
### Avoid Large Arrays
```typescript
// ❌ 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;
}
}
```
## Caching Strategies
### Multi-Layer Cache
```typescript
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
```
## Bundle Optimization
```typescript
// 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;
}
```
## When to Load References
Load specific references based on the task:
- **Optimizing CPU usage?** → Load `references/cpu-optimization.md`
- **Memory issues?** → Load `references/memory-optimization.md`
- **Implementing caching?** → Load `references/caching-strategies.md`
- **Reducing bundle size?** → Load `references/bundle-optimization.md`
- **Cold start problems?** → Load `references/cold-starts.md`
## Templates
| Template | Purpose | Use When |
|----------|---------|----------|
| `templates/performance-middleware.ts` | Performance monitoring | Adding timing/profiling |
| `templates/caching-layer.ts` | Multi-layer caching | Implementing cache |
| `templates/optimized-worker.ts` | Performance patterns | Starting optimized worker |
## Scripts
| Script | Purpose | Command |
|--------|---------|---------|
| `scripts/benchmark.sh` | Load testing | `./benchmark.sh <url>` |
| `scripts/profile-worker.sh` | CPU profiling | `./profile-worker.sh` |
## Resources
- Performance: https://developers.cloudflare.com/workers/platform/performance/
- Limits: https://developers.cloudflare.com/workers/platform/limits/
- Caching: https://developers.cloudflare.com/workers/runtime-apis/cache/
Files in this package (11)
- SKILL.md 6 KB
- references/bundle-optimization.md 9 KB
- references/caching-strategies.md 11 KB
- references/cold-starts.md 9 KB
- references/cpu-optimization.md 9 KB
- references/memory-optimization.md 10 KB
- scripts/benchmark.sh 12 KB
- scripts/profile-worker.sh 12 KB
- templates/caching-layer.ts 13 KB
- templates/optimized-worker.ts 10 KB
- templates/performance-middleware.ts 11 KB
Versions
The database has no other skills named cloudflare-workers-performance.
Database snapshot: 13.11.2026 · package version b65c41325532 (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 100cloudflare-cost-optimization
Cloudflare 成本优化:在功能不变的前提下,把部署在 Cloudflare(Workers / D1 / R2 / KV / Cache API)上的项目的费用降到最低,顺带提升性能。已上线的项目用真实用量数据找出最贵、最慢的请求和查询;还没上线的项目从代码和本地数据库提前检查。适用于:想知道账单从哪来、D1 读取量偏高、Workers 请求量或 CPU 偏高、页面慢、静态文件误走 Worker、爬虫流量大、上线前做一次检查、上线新功能后确认有没有性能问题。用户说“查一下 Cloudflare 用量/费用/性能”“D1… - 90workers-profiling
Profile or debug CPU usage and memory allocation in deployed Cloudflare Workers and Durable Objects. Then use this information to optimize your code. - 90workers-profiling
Profile or debug CPU usage and memory allocation in deployed Cloudflare Workers and Durable Objects. Then use this information to optimize your code. - 100cloudflare-kv
Cloudflare Workers KV global key-value storage. Use for namespaces, caching, TTL, or encountering KV_ERROR, 429 rate limits, consistency issues. - 100cloudflare
Cloudflare platform: Workers, Pages, KV/D1/R2, cron, Workers AI, AI Gateway, Agents SDK, MCP on Workers, REST API, wrangler. Use for any Cloudflare, Worker or binding task and Workers code review. Prefer live docs over memory. - 95cloudflare-workers-ci-cd
Complete CI/CD guide for Cloudflare Workers using GitHub Actions and GitLab CI. Use for automated testing, deployment pipelines, preview environments, secrets management, or encountering deployment failures, workflow errors, environment configuration issues.