Skip to main content
skill CX Codex

cloudflare-workers-performance — Claude Code skill: speed up Workers

A Claude skill for Cloudflare Workers performance: CPU, memory, caching, bundle size. Useful when a worker is slow or hitting limits.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add secondsky/claude-skills --skill cloudflare-workers-performance -a claude-code
Open on GitHub

What cloudflare-workers-performance does

The skill covers Worker performance across four areas: CPU time, memory, caching and bundle size. It ships a table of common failures with symptoms and fixes — CPU limit exceeded, slow cold starts, memory pressure, KV and D1 latency, needless request cloning.

The hands-on part is TypeScript. Timing hot paths with a Date.now() wrapper, streaming a response instead of buffering it, batching D1 reads instead of pulling every row into an array, and a three-layer cache built from in-memory storage, the Cache API and KV. Bundle advice is concrete too: named imports over import * as, lazy loading heavy dependencies through dynamic import. Templates live in templates/performance-middleware.ts, templates/caching-layer.ts and templates/optimized-worker.ts; scripts in scripts/benchmark.sh and scripts/profile-worker.sh.

Keep bundles under 1MB and watch the CPU ceilings: 10ms on free, 30ms on paid, 50ms on unbound. Dynamic imports shrink the bundle but add latency on the first call, so it is worth checking what actually loads lazily. The skill suggests pulling one reference file per task: references/cpu-optimization.md, references/memory-optimization.md, references/caching-strategies.md, references/bundle-optimization.md or references/cold-starts.md.

What it helps with

  • stay under the CPU limit on free or paid plans
  • cut cold start latency
  • ease memory pressure when handling large responses
  • add a cache in front of repeated computation
  • shrink the bundle before deploy

Example prompts for the agent

  • My worker keeps dying with CPU limit exceeded — help me find the hot path
  • Responses are slow, switch this handler to streaming instead of buffering
  • The bundle got big, show me how to trim it and speed up cold starts

How to install cloudflare-workers-performance

1Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill cloudflare-workers-performance -a claude-code

2Manually: put the files in place

~/.claude/skills/cloudflare-workers-performance/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/cloudflare-workers-performance/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about cloudflare-workers-performance

How do I install cloudflare-workers-performance in Claude?

Run npx skills add secondsky/claude-skills --skill cloudflare-workers-performance -a claude-code. The skill lands at ~/.claude/skills/cloudflare-workers-performance/SKILL.md.

What does cloudflare-workers-performance do?

It walks through speeding up Cloudflare Workers: CPU optimization, memory handling, caching and bundle size. It also maps common failures like CPU limit exceeded and slow cold starts to fixes.

Which CPU limits does the skill account for?

10ms on the free plan, 30ms on paid and 50ms on unbound. Those numbers shape which optimization techniques are worth applying.

Source text

SKILL.md · MIT
---
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/

© secondsky · MIT · secondsky/claude-skills

Similar skills

All skills for Cloud: AWS, Azure, GCP →

From the same set94

maz-ui This skill teaches your agent Maz-UI v4: 50+ components, composables and directives for Vue 3 and Nuxt 3. Handy when you build forms, dialogs or data tables. CX Codex +1 369installs woocommerce-dev-cycle A skill that walks you through the WooCommerce dev cycle: run tests, fix code style, sort out linting errors. CX Codex +1 361installs woocommerce-copy-guidelines A skill that sets the rules for user-facing text in WooCommerce: button labels, field names, messages and docs. Useful when more than one person writes the storefront strings. CX Codex +1 363installs cloudflare-workers-testing A skill for writing Cloudflare Workers tests with Vitest and real D1, KV, R2 and Durable Objects bindings. Useful when tests break on mocks or can't see the environment. CX Codex +1 325installs nuxt-seo A skill covering the eight Nuxt SEO v5 modules: robots.txt, sitemaps, OG images, Schema.org and meta tags. Useful when a Nuxt app needs SEO wired up. CX Codex +1 324installs cloudflare-workers-runtime-apis A skill covering the Cloudflare Workers runtime APIs: Fetch, Streams, Crypto, Cache, WebSockets and text encoding. Handy when a worker trips over requests, streams or cache. CX Codex +1 311installs cloudflare-workers-frameworks Tells your agent how to run Hono, Remix, Next.js, Astro, SvelteKit, Qwik or Nuxt on Cloudflare Workers, and walks through the usual build errors. CX Codex +1 309installs cloudflare-workers-observability A skill for Cloudflare Workers observability: structured logging, Analytics Engine, Tail Workers, metrics and alerting. Useful when a worker fails in production and you can't see why. CX Codex +1 302installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor