Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

Complete cloudflare-queues skill - Batch 1 Finished! 🎯

Jezcf1d919971c2
diff --git a/ATOMIC-SKILLS-SUMMARY.md b/ATOMIC-SKILLS-SUMMARY.md
index a7c15e16..1e1033b5 100644
--- a/ATOMIC-SKILLS-SUMMARY.md
+++ b/ATOMIC-SKILLS-SUMMARY.md
@@ -37,20 +37,27 @@ We pivoted from **bundled composite skills** to **atomic, domain-focused skills*
## Current Status
-### βœ… Completed Skills (5)
-- `tailwind-v4-shadcn` - Tailwind v4 + shadcn/ui (6h dev, ~70% token savings)
-- `cloudflare-worker-base` - Hono + Vite + wrangler (2h dev, ~60% token savings)
-- `firecrawl-scraper` - Firecrawl v2 API for web scraping (1.5h dev, ~60% token savings)
-- `cloudflare-d1` - D1 serverless database (2.5h dev, ~58% token savings)
-- `cloudflare-r2` - R2 object storage (2.5h dev, ~60% token savings)
+### βœ… Completed Skills (9)
-### πŸ“‹ Planned Atomic Skills (8)
+**Batch 1 - Cloudflare Services (6/6 complete)** 🎯
+1. `cloudflare-worker-base` - Hono + Vite + wrangler (2h dev, ~60% token savings, 6 errors prevented)
+2. `cloudflare-d1` - D1 serverless database (2.5h dev, ~58% token savings, 6 errors prevented)
+3. `cloudflare-r2` - R2 object storage (2.5h dev, ~60% token savings, 6 errors prevented)
+4. `cloudflare-kv` - KV namespaces (3h dev, ~55% token savings, 6 errors prevented)
+5. `cloudflare-workers-ai` - Workers AI (5h dev, ~60% token savings, 6 errors prevented)
+6. `cloudflare-vectorize` - Vector search (3h dev, ~65% token savings, 8 errors prevented)
+7. `cloudflare-queues` - Async processing (3h dev, ~50% token savings, 8 errors prevented)
-**Batch 1 - Cloudflare Services (4 skills remaining)**
-1. `cloudflare-kv` - KV namespaces (caching patterns)
-2. `cloudflare-workers-ai` - Workers AI (models, streaming, embeddings)
-3. `cloudflare-vectorize` - Vector search (embeddings, RAG)
-4. `cloudflare-queues` - Async processing (batch jobs, retries)
+**Other Skills (2)**
+8. `tailwind-v4-shadcn` - Tailwind v4 + shadcn/ui (6h dev, ~70% token savings, 3 errors prevented)
+9. `firecrawl-scraper` - Firecrawl v2 API (1.5h dev, ~60% token savings, 6 errors prevented)
+
+### πŸ“‹ Planned Atomic Skills (4)
+
+**Batch 2 - Auth & Frameworks (3 skills)**
+1. `clerk-auth` - All Clerk knowledge (React, Next.js, CF Workers, JWT)
+2. `hono-routing` - Hono patterns (middleware, RPC, typed routes)
+3. `react-hook-form-zod` - Forms + validation (client + server)
**Batch 2 - Auth & Frameworks (3 skills)**
5. `clerk-auth` - All Clerk knowledge (React, Next.js, CF Workers, JWT)
@@ -58,7 +65,7 @@ We pivoted from **bundled composite skills** to **atomic, domain-focused skills*
7. `react-hook-form-zod` - Forms + validation (client + server)
**Batch 3 - Data & Utilities (1 skill)**
-8. `tanstack-query` - Server state management
+4. `tanstack-query` - Server state management
---
@@ -92,20 +99,17 @@ User: "Build a Cloudflare full-stack app with database and auth"
## Next Steps
-### Immediate (This Week):
-1. **Build cloudflare-d1** (4 hours) - Highest priority
- - Research Cloudflare Docs MCP
- - Create templates for D1 setup
- - Document migration patterns
- - Test with real project
+### βœ… Batch 1 Complete! (6/6 Cloudflare Services)
+
+All core Cloudflare Workers services are now covered with atomic skills. This provides a complete foundation for building serverless applications on Cloudflare.
-### Week 2:
-- Complete remaining Cloudflare services (R2, KV, Workers AI, Vectorize, Queues)
-- Build clerk-auth skill (critical for most apps)
+### Next Up - Batch 2 (Auth & Frameworks):
+1. **clerk-auth** - Critical for most apps with authentication
+2. **hono-routing** - Routing patterns for Cloudflare Workers
+3. **react-hook-form-zod** - Forms + validation best practices
-### Week 3:
-- Build framework skills (hono-routing, react-hook-form-zod)
-- Build utility skills (tanstack-query, drizzle-orm-d1)
+### Batch 3 (Data & Utilities):
+4. **tanstack-query** - Server state management (optional)
---
diff --git a/planning/skills-roadmap.md b/planning/skills-roadmap.md
index 8038528f..8c16fd36 100644
--- a/planning/skills-roadmap.md
+++ b/planning/skills-roadmap.md
@@ -282,23 +282,45 @@ Result: Integrated solution from atomic skills
---
#### 6. cloudflare-queues
-**Status**: Planned
+**Status**: βœ… Complete (2025-10-21)
**Priority**: Medium
**Dependencies**: cloudflare-worker-base
-**Estimated Dev Time**: 3 hours
+**Actual Dev Time**: 3 hours
**Token Savings**: ~50%
+**Errors Prevented**: 8
**What It Does**:
-- Queue setup
-- Producer/consumer patterns
-- Batch processing
-- Retry strategies
-- Dead letter queues
-- Queue monitoring
+- Queue creation and management with wrangler
+- Complete Producer API (send, sendBatch, delays)
+- Complete Consumer API (batch, message, ack/retry)
+- Batching configuration (max_batch_size, max_batch_timeout)
+- Retry strategies (implicit, explicit, exponential backoff)
+- Dead Letter Queues (DLQ) for failed messages
+- Explicit acknowledgement patterns
+- Message delays (up to 12 hours)
+- Consumer concurrency (auto-scaling up to 250)
+- Error handling and best practices
+
+**Files Created**:
+- README.md (comprehensive auto-trigger keywords)
+- SKILL.md (complete API reference, 800+ lines)
+- templates/wrangler-queues-config.jsonc
+- templates/queues-producer.ts (send, sendBatch, delays)
+- templates/queues-consumer-basic.ts (implicit ack)
+- templates/queues-consumer-explicit-ack.ts (non-idempotent ops)
+- templates/queues-dlq-pattern.ts (dead letter queue consumer)
+- templates/queues-retry-with-delay.ts (exponential backoff)
+- reference/wrangler-commands.md (complete CLI reference)
+- reference/producer-api.md (send/sendBatch deep dive)
+- reference/consumer-api.md (queue handler, batch/message operations)
+- reference/best-practices.md (patterns, concurrency, optimization)
+
+**Production Validated**: Templates tested with working examples
**Auto-Trigger Keywords**:
-- `cloudflare queues`, `queues workers`, `async processing`
-- `queue bindings`, `message queues`, `batch jobs`
+- `cloudflare queues`, `queues workers`, `message queue`, `async processing`
+- `queue bindings`, `background jobs`, `batch processing`, `dead letter queue`
+- `queue ack`, `message retry`, `consumer concurrency`
---
@@ -531,8 +553,8 @@ Calculate:
## πŸ“ˆ Progress Tracking
### Overall Progress:
-- **Completed**: 8 skills βœ…
-- **Batch 1 - Cloudflare Services**: 5/6 complete (83%)
+- **Completed**: 9 skills βœ…
+- **Batch 1 - Cloudflare Services**: 6/6 complete (100%) 🎯
- **Batch 2 - Auth & Frameworks**: 0/3 complete
- **Batch 3 - Data & Utilities**: 0/2 complete
@@ -548,14 +570,14 @@ Calculate:
| **cloudflare-kv** | **βœ… Complete** | **3h** | **~55%** | **6** | High |
| **cloudflare-workers-ai** | **βœ… Complete** | **5h** | **~60%** | **6** | High |
| **cloudflare-vectorize** | **βœ… Complete** | **3h** | **~65%** | **8** | Medium |
-| cloudflare-queues | Planned | 3h (est.) | ~50% | - | Medium |
+| **cloudflare-queues** | **βœ… Complete** | **3h** | **~50%** | **8** | Medium |
| clerk-auth | Planned | 5h (est.) | ~60% | - | Critical |
| hono-routing | Planned | 4h (est.) | ~55% | - | High |
| react-hook-form-zod | Planned | 4h (est.) | ~60% | - | High |
| tanstack-query | Planned | 4h (est.) | ~55% | - | Medium |
| drizzle-orm-d1 | Planned | 5h (est.) | ~60% | - | Low |
-**Total Skills Planned**: 13 (8 complete, 5 to build)
+**Total Skills Planned**: 13 (9 complete, 4 to build)
---
diff --git a/skills/cloudflare-kv/README.md b/skills/cloudflare-kv/README.md
new file mode 100644
index 00000000..5c2e8109
--- /dev/null
+++ b/skills/cloudflare-kv/README.md
@@ -0,0 +1,225 @@
+# Cloudflare Workers KV
+
+Complete knowledge domain for Cloudflare Workers KV - global, low-latency key-value storage on Cloudflare's edge network.
+
+---
+
+## Auto-Trigger Keywords
+
+### Primary Keywords
+- kv storage
+- cloudflare kv
+- kv namespace
+- workers kv
+- kv bindings
+- kv cache
+- kv api
+- key value storage
+- edge storage
+
+### Secondary Keywords
+- kv get
+- kv put
+- kv delete
+- kv list
+- kv ttl
+- kv expiration
+- kv metadata
+- cache ttl
+- kv pagination
+- kv prefix
+- kv wrangler
+- namespace create
+- kv operations
+- eventually consistent
+
+### Error-Based Keywords
+- KV_ERROR
+- 429 too many requests
+- kv rate limit
+- kv quota exceeded
+- kv write limit
+- concurrent writes kv
+- kv_put_failed
+- metadata too large
+- value too large
+- key too long
+- cacheTtl minimum
+
+### Framework Integration Keywords
+- kv hono
+- kv workers api
+- kv cloudflare workers
+- wrangler kv
+- kv bindings workers
+
+---
+
+## What This Skill Does
+
+This skill provides complete Workers KV knowledge including:
+
+- βœ… **KV Namespace Management** - Create, configure, and bind namespaces
+- βœ… **CRUD Operations** - get(), put(), delete(), list()
+- βœ… **Bulk Operations** - Bulk reads and REST API batch writes
+- βœ… **Metadata Storage** - Store up to 1KB metadata per key
+- βœ… **TTL & Expiration** - Automatic key expiration with TTL or absolute time
+- βœ… **CacheTtl Optimization** - Control edge caching for faster reads
+- βœ… **List Operations** - Pagination with cursor, prefix filtering
+- βœ… **Performance Patterns** - Key coalescing, caching strategies
+- βœ… **Error Handling** - Rate limit retries, eventual consistency handling
+- βœ… **Development vs Production** - Environment-specific namespaces
+
+---
+
+## Known Issues Prevented
+
+| Issue | Description | Prevention |
+|-------|-------------|------------|
+| **1 write/sec limit** | Concurrent writes to same key cause 429 errors | Document rate limits + retry logic with backoff |
+| **Eventually consistent** | Writes take up to 60s to propagate globally | Set expectations, use cacheTtl appropriately |
+| **cacheTtl minimum 60s** | Setting lower than 60s fails | Always use 60+ seconds for cacheTtl |
+| **Metadata 1024 byte limit** | Exceeding metadata size causes errors | Validate metadata size before put() |
+| **Value 25MB limit** | Large values fail to store | Check size before writing |
+| **1000 operations/invocation** | Exceeding causes Worker failure | Use bulk operations, batch reads |
+
+---
+
+## When to Use This Skill
+
+### βœ… Use this skill when:
+- Storing configuration data or feature flags
+- Caching API responses or computed values
+- Storing user preferences or session data
+- Building read-heavy applications
+- Implementing A/B testing configurations
+- Storing authentication tokens or JWT data
+- Building CDN-like caching layers
+- Storing routing tables or redirect maps
+- Managing global application state
+
+### ❌ When NOT to use:
+- You need strong consistency (use Durable Objects)
+- You need atomic operations (use Durable Objects)
+- You need relational data (use cloudflare-d1)
+- You need frequent writes to same key (>1/sec)
+- You need large file storage (use cloudflare-r2)
+- You need vector search (use cloudflare-vectorize)
+
+---
+
+## Quick Example
+
+```typescript
+import { Hono } from 'hono';
+
+type Bindings = {
+ CONFIG: KVNamespace;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// Write with expiration
+app.post('/config/:key', async (c) => {
+ const key = c.req.param('key');
+ const value = await c.req.text();
+
+ await c.env.CONFIG.put(key, value, {
+ expirationTtl: 3600, // Expire in 1 hour
+ metadata: { updatedAt: Date.now(), updatedBy: 'admin' },
+ });
+
+ return c.json({ success: true, key });
+});
+
+// Read with cache optimization
+app.get('/config/:key', async (c) => {
+ const key = c.req.param('key');
+
+ const { value, metadata } = await c.env.CONFIG.getWithMetadata(key, {
+ type: 'json',
+ cacheTtl: 300, // Cache for 5 minutes at edge
+ });
+
+ if (!value) {
+ return c.json({ error: 'Not found' }, 404);
+ }
+
+ return c.json({ value, metadata });
+});
+
+// List with prefix and pagination
+app.get('/config/list/:prefix?', async (c) => {
+ const prefix = c.req.param('prefix') || '';
+ const cursor = c.req.query('cursor');
+
+ const result = await c.env.CONFIG.list({
+ prefix,
+ limit: 100,
+ cursor: cursor || undefined,
+ });
+
+ return c.json({
+ keys: result.keys,
+ hasMore: !result.list_complete,
+ cursor: result.cursor,
+ });
+});
+
+export default app;
+```
+
+---
+
+## Token Efficiency
+
+- **Manual Setup**: 9,000-13,000 tokens
+- **With This Skill**: 3,500-5,000 tokens
+- **Savings**: ~55-60%
+
+---
+
+## Files Included
+
+- `SKILL.md` - Complete KV knowledge domain
+- `templates/wrangler-kv-config.jsonc` - KV namespace bindings
+- `templates/kv-basic-operations.ts` - CRUD operations Worker
+- `templates/kv-caching-pattern.ts` - Cache optimization patterns
+- `templates/kv-list-pagination.ts` - List with cursor pagination
+- `templates/kv-metadata-pattern.ts` - Metadata usage patterns
+- `reference/workers-api.md` - Complete Workers API reference
+- `reference/best-practices.md` - Performance & caching strategies
+
+---
+
+## Dependencies
+
+- **cloudflare-worker-base** - For Hono + Vite + Worker setup
+- **wrangler** - For KV namespace management
+
+---
+
+## Production Status
+
+βœ… **Production Ready**
+
+This skill is based on:
+- Official Cloudflare KV documentation
+- Cloudflare Workers SDK examples
+- Production-tested patterns
+- Latest package versions (verified 2025-10-21)
+
+---
+
+## Related Skills
+
+- **cloudflare-worker-base** - Base Worker setup with Hono
+- **cloudflare-d1** - Serverless SQLite database
+- **cloudflare-r2** - Object storage
+- **cloudflare-workers-ai** - AI inference on Workers
+
+---
+
+**Last Updated**: 2025-10-21
+**Status**: Production Ready βœ…
+**Maintainer**: Jeremy Dawes | [email protected]
diff --git a/skills/cloudflare-kv/SKILL.md b/skills/cloudflare-kv/SKILL.md
new file mode 100644
index 00000000..1cdbded7
--- /dev/null
+++ b/skills/cloudflare-kv/SKILL.md
@@ -0,0 +1,1049 @@
+---
+name: Cloudflare Workers KV
+description: |
+ Complete knowledge domain for Cloudflare Workers KV - global, low-latency key-value storage on Cloudflare's edge network.
+
+ Use when: creating KV namespaces, storing configuration data, caching API responses, managing user preferences,
+ implementing TTL expiration, handling KV metadata, or encountering "KV_ERROR", "429 too many requests",
+ "kv rate limit", cacheTtl errors, or eventual consistency issues.
+
+ Keywords: kv storage, cloudflare kv, workers kv, kv namespace, kv bindings, kv cache, kv ttl, kv metadata,
+ kv list, kv pagination, cache optimization, edge caching, KV_ERROR, 429 too many requests, kv rate limit,
+ eventually consistent, wrangler kv, kv operations, key value storage
+---
+
+# Cloudflare Workers KV
+
+**Status**: Production Ready βœ…
+**Last Updated**: 2025-10-21
+**Dependencies**: cloudflare-worker-base (for Worker setup)
+**Latest Versions**: [email protected], @cloudflare/[email protected]
+
+---
+
+## Quick Start (5 Minutes)
+
+### 1. Create KV Namespace
+
+```bash
+# Create a new KV namespace
+npx wrangler kv namespace create MY_NAMESPACE
+
+# Output includes namespace_id - save this!
+# βœ… Success!
+# Add the following to your wrangler.toml or wrangler.jsonc:
+#
+# [[kv_namespaces]]
+# binding = "MY_NAMESPACE"
+# id = "<UUID>"
+```
+
+**For development (preview) namespace:**
+
+```bash
+npx wrangler kv namespace create MY_NAMESPACE --preview
+
+# Output:
+# [[kv_namespaces]]
+# binding = "MY_NAMESPACE"
+# preview_id = "<UUID>"
+```
+
+### 2. Configure Bindings
+
+Add to your `wrangler.jsonc`:
+
+```jsonc
+{
+ "name": "my-worker",
+ "main": "src/index.ts",
+ "compatibility_date": "2025-10-11",
+ "kv_namespaces": [
+ {
+ "binding": "MY_NAMESPACE", // Available as env.MY_NAMESPACE
+ "id": "<production-uuid>", // Production namespace ID
+ "preview_id": "<preview-uuid>" // Local dev namespace ID (optional)
+ }
+ ]
+}
+```
+
+**Or use `wrangler.toml`:**
+
+```toml
+name = "my-worker"
+main = "src/index.ts"
+compatibility_date = "2025-10-11"
+
+[[kv_namespaces]]
+binding = "MY_NAMESPACE"
+id = "<production-uuid>"
+preview_id = "<preview-uuid>" # optional
+```
+
+**CRITICAL:**
+- `binding` is how you access the namespace in code (`env.MY_NAMESPACE`)
+- `id` is the production namespace UUID
+- `preview_id` is for local dev (optional, separate namespace)
+- **Never commit real namespace IDs to public repos** - use environment variables or secrets
+
+### 3. Write Your First Key-Value Pair
+
+```typescript
+import { Hono } from 'hono';
+
+type Bindings = {
+ MY_NAMESPACE: KVNamespace;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+app.post('/set/:key', async (c) => {
+ const key = c.req.param('key');
+ const value = await c.req.text();
+
+ // Simple write
+ await c.env.MY_NAMESPACE.put(key, value);
+
+ return c.json({ success: true, key });
+});
+
+app.get('/get/:key', async (c) => {
+ const key = c.req.param('key');
+ const value = await c.env.MY_NAMESPACE.get(key);
+
+ if (!value) {
+ return c.json({ error: 'Not found' }, 404);
+ }
+
+ return c.json({ value });
+});
+
+export default app;
+```
+
+### 4. Test Locally
+
+```bash
+# Start local development server
+npm run dev
+
+# In another terminal, test the endpoints
+curl -X POST http://localhost:8787/set/test -d "Hello KV"
+# {"success":true,"key":"test"}
+
+curl http://localhost:8787/get/test
+# {"value":"Hello KV"}
+```
+
+---
+
+## Complete Workers KV API
+
+### 1. Read Operations
+
+#### `get()` - Read Single Key
+
+```typescript
+// Get as string (default)
+const value: string | null = await env.MY_KV.get('my-key');
+
+// Get as JSON
+const data: MyType | null = await env.MY_KV.get('my-key', { type: 'json' });
+
+// Get as ArrayBuffer
+const buffer: ArrayBuffer | null = await env.MY_KV.get('my-key', { type: 'arrayBuffer' });
+
+// Get as ReadableStream
+const stream: ReadableStream | null = await env.MY_KV.get('my-key', { type: 'stream' });
+
+// Get with cache optimization
+const value = await env.MY_KV.get('my-key', {
+ type: 'text',
+ cacheTtl: 300, // Cache at edge for 5 minutes (minimum 60 seconds)
+});
+```
+
+#### `get()` - Read Multiple Keys (Bulk)
+
+```typescript
+// Read multiple keys at once (counts as 1 operation)
+const keys = ['key1', 'key2', 'key3'];
+const values: Map<string, string | null> = await env.MY_KV.get(keys);
+
+// Access values
+const value1 = values.get('key1'); // string | null
+const value2 = values.get('key2'); // string | null
+
+// Convert to object
+const obj = Object.fromEntries(values);
+```
+
+#### `getWithMetadata()` - Read with Metadata
+
+```typescript
+// Get single key with metadata
+const { value, metadata } = await env.MY_KV.getWithMetadata('my-key');
+
+// value: string | null
+// metadata: any | null
+
+// Get as JSON with metadata
+const { value, metadata } = await env.MY_KV.getWithMetadata<MyType>('my-key', {
+ type: 'json',
+ cacheTtl: 300,
+});
+
+// Get multiple keys with metadata
+const keys = ['key1', 'key2'];
+const result: Map<string, { value: string | null, metadata: any | null }> =
+ await env.MY_KV.getWithMetadata(keys);
+
+for (const [key, data] of result) {
+ console.log(key, data.value, data.metadata);
+}
+```
+
+**Type Options:**
+- `text` (default) - Returns `string`
+- `json` - Parses JSON, returns `object`
+- `arrayBuffer` - Returns `ArrayBuffer`
+- `stream` - Returns `ReadableStream`
+
+**Note:** Bulk read with `get(keys[])` only supports `text` and `json` types. For `arrayBuffer` or `stream`, use individual `get()` calls with `Promise.all()`.
+
+---
+
+### 2. Write Operations
+
+#### `put()` - Write Key-Value Pair
+
+```typescript
+// Simple write
+await env.MY_KV.put('key', 'value');
+
+// Write JSON
+await env.MY_KV.put('user:123', JSON.stringify({ name: 'John', age: 30 }));
+
+// Write with expiration (TTL)
+await env.MY_KV.put('session:abc', sessionData, {
+ expirationTtl: 3600, // Expire in 1 hour (minimum 60 seconds)
+});
+
+// Write with absolute expiration
+const expirationTime = Math.floor(Date.now() / 1000) + 86400; // 24 hours from now
+await env.MY_KV.put('token', tokenValue, {
+ expiration: expirationTime, // Seconds since epoch
+});
+
+// Write with metadata
+await env.MY_KV.put('config:theme', 'dark', {
+ metadata: {
+ updatedAt: Date.now(),
+ updatedBy: 'admin',
+ version: 2
+ },
+});
+
+// Write with everything
+await env.MY_KV.put('feature:flags', JSON.stringify(flags), {
+ expirationTtl: 600,
+ metadata: { source: 'api', timestamp: Date.now() },
+});
+```
+
+**CRITICAL Limits:**
+- **Key size**: Maximum 512 bytes
+- **Value size**: Maximum 25 MiB
+- **Metadata size**: Maximum 1024 bytes (JSON serialized)
+- **Write rate**: Maximum 1 write per second **per key**
+- **Expiration minimum**: 60 seconds (both TTL and absolute)
+
+**Rate Limit Handling:**
+
+```typescript
+async function putWithRetry(
+ kv: KVNamespace,
+ key: string,
+ value: string,
+ options?: KVPutOptions
+) {
+ let attempts = 0;
+ const maxAttempts = 5;
+ let delay = 1000; // Start with 1 second
+
+ while (attempts < maxAttempts) {
+ try {
+ await kv.put(key, value, options);
+ return; // Success
+ } catch (error) {
+ const message = (error as Error).message;
+
+ if (message.includes('429') || message.includes('Too Many Requests')) {
+ attempts++;
+ if (attempts >= maxAttempts) {
+ throw new Error('Max retry attempts reached');
+ }
+
+ console.warn(`Attempt ${attempts} failed. Retrying in ${delay}ms...`);
+ await new Promise(resolve => setTimeout(resolve, delay));
+
+ // Exponential backoff
+ delay *= 2;
+ } else {
+ throw error; // Different error, rethrow
+ }
+ }
+ }
+}
+```
+
+---
+
+### 3. List Operations
+
+#### `list()` - List Keys
+
+```typescript
+// List all keys (up to 1000)
+const result = await env.MY_KV.list();
+
+console.log(result.keys); // Array of key objects
+console.log(result.list_complete); // boolean - false if more keys exist
+console.log(result.cursor); // string - for pagination
+
+// List with prefix filter
+const result = await env.MY_KV.list({
+ prefix: 'user:', // Only keys starting with 'user:'
+});
+
+// List with limit
+const result = await env.MY_KV.list({
+ limit: 100, // Maximum 1000 (default 1000)
+});
+
+// Pagination with cursor
+let cursor: string | undefined;
+let allKeys: any[] = [];
+
+do {
+ const result = await env.MY_KV.list({ cursor });
+ allKeys = allKeys.concat(result.keys);
+ cursor = result.list_complete ? undefined : result.cursor;
+} while (cursor);
+
+// Combined: prefix + pagination
+let cursor: string | undefined;
+const userKeys: any[] = [];
+
+do {
+ const result = await env.MY_KV.list({
+ prefix: 'user:',
+ cursor,
+ });
+
+ userKeys.push(...result.keys);
+ cursor = result.list_complete ? undefined : result.cursor;
+} while (cursor);
+```
+
+**List Response Format:**
+
+```typescript
+{
+ keys: [
+ {
+ name: "user:123",
+ expiration: 1234567890, // Optional: seconds since epoch
+ metadata: { ... } // Optional: metadata object
+ },
+ // ... more keys
+ ],
+ list_complete: false, // true if no more keys
+ cursor: "6Ck1la0VxJ0djhidm1MdX2FyD" // Use for next page
+}
+```
+
+**IMPORTANT:**
+- Keys are **always** returned in lexicographically sorted order (UTF-8)
+- **Always check `list_complete`**, not `keys.length === 0`
+- Empty `keys` array doesn't mean no more data (expired/deleted keys create "tombstones")
+- When paginating with `prefix`, you **must** pass the same `prefix` with each `cursor` request
+
+---
+
+### 4. Delete Operations
+
+#### `delete()` - Delete Key
+
+```typescript
+// Delete single key
+await env.MY_KV.delete('my-key');
+
+// Delete always succeeds, even if key doesn't exist
+await env.MY_KV.delete('non-existent-key'); // No error
+
+// Bulk delete pattern (in Worker)
+const keysToDelete = ['key1', 'key2', 'key3', ...];
+
+// Delete in parallel (careful of Worker subrequest limits)
+await Promise.all(
+ keysToDelete.map(key => env.MY_KV.delete(key))
+);
+
+// For more than 1000 keys, use REST API bulk delete (via wrangler or API)
+```
+
+**Bulk Delete via REST API:**
+
+The Workers binding doesn't support bulk delete, but you can use the REST API (via `wrangler` or direct API calls):
+
+```bash
+# Using wrangler CLI
+npx wrangler kv bulk delete --namespace-id=<UUID> keys.json
+
+# keys.json format:
+# ["key1", "key2", "key3"]
+```
+
+**REST API Limit:** Up to 10,000 keys per bulk delete request.
+
+---
+
+## Advanced Patterns & Best Practices
+
+### 1. Caching Pattern with CacheTtl
+
+```typescript
+async function getCachedData(
+ kv: KVNamespace,
+ cacheKey: string,
+ fetchFn: () => Promise<any>,
+ cacheTtl: number = 300
+) {
+ // Try to get from KV cache
+ const cached = await kv.get(cacheKey, {
+ type: 'json',
+ cacheTtl, // Cache at edge for faster subsequent reads
+ });
+
+ if (cached) {
+ return cached;
+ }
+
+ // Cache miss - fetch fresh data
+ const data = await fetchFn();
+
+ // Store in KV with expiration
+ await kv.put(cacheKey, JSON.stringify(data), {
+ expirationTtl: cacheTtl * 2, // Store longer than cache
+ });
+
+ return data;
+}
+
+// Usage
+app.get('/api/data/:id', async (c) => {
+ const id = c.req.param('id');
+
+ const data = await getCachedData(
+ c.env.CACHE,
+ `data:${id}`,
+ () => fetchFromDatabase(id),
+ 300 // 5 minutes
+ );
+
+ return c.json(data);
+});
+```
+
+**CacheTtl Guidelines:**
+- **Minimum:** 60 seconds
+- **Default:** 60 seconds
+- **Maximum:** `Number.MAX_SAFE_INTEGER`
+- **Use case:** Frequently read, infrequently updated data
+- **Trade-off:** Higher cacheTtl = faster reads but slower update propagation
+
+---
+
+### 2. Metadata Optimization Pattern
+
+Store small values in metadata to avoid separate `get()` calls:
+
+```typescript
+// ❌ Bad: Two operations
+await env.MY_KV.put('user:123', 'active');
+const status = await env.MY_KV.get('user:123');
+
+// βœ… Good: Store in metadata with empty value
+await env.MY_KV.put('user:123', '', {
+ metadata: {
+ status: 'active',
+ lastSeen: Date.now(),
+ plan: 'pro'
+ },
+});
+
+// List returns metadata automatically
+const users = await env.MY_KV.list({ prefix: 'user:' });
+
+users.keys.forEach(({ name, metadata }) => {
+ console.log(name, metadata.status, metadata.plan);
+ // No additional get() calls needed!
+});
+```
+
+**When to Use:**
+- βœ… Values fit in 1024 bytes
+- βœ… You frequently use `list()` operations
+- βœ… You need to filter/process many keys
+- ❌ Don't use for large values (use regular value storage)
+
+---
+
+### 3. Key Coalescing for Performance
+
+Combine related cold keys with hot keys:
+
+```typescript
+// ❌ Bad: Many individual keys (some hot, some cold)
+await kv.put('user:123:name', 'John');
+await kv.put('user:123:email', '[email protected]');
+await kv.put('user:123:age', '30');
+
+// βœ… Good: Coalesce into single hot key
+await kv.put('user:123', JSON.stringify({
+ name: 'John',
+ email: '[email protected]',
+ age: 30,
+}));
+
+// Single read gets everything
+const user = await kv.get<User>('user:123', { type: 'json' });
+```
+
+**Advantages:**
+- Cold keys benefit from hot key caching
+- Fewer operations = better performance
+- Single cache entry instead of multiple
+
+**Disadvantages:**
+- Can't update individual fields easily (requires read-modify-write)
+- Large coalesced values may hit memory limits
+- Concurrent updates need locking mechanism
+
+---
+
+### 4. Pagination Helper
+
+```typescript
+async function* paginateKV(
+ kv: KVNamespace,
+ options: { prefix?: string; limit?: number } = {}
+) {
+ let cursor: string | undefined;
+
+ do {
+ const result = await kv.list({
+ prefix: options.prefix,
+ limit: options.limit || 1000,
+ cursor,
+ });
+
+ yield result.keys;
+
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+}
+
+// Usage
+app.get('/all-users', async (c) => {
+ const allUsers = [];
+
+ for await (const keys of paginateKV(c.env.MY_KV, { prefix: 'user:' })) {
+ // Process batch
+ allUsers.push(...keys.map(k => k.name));
+ }
+
+ return c.json({ users: allUsers, count: allUsers.length });
+});
+```
+
+---
+
+### 5. Feature Flags Pattern
+
+```typescript
+interface FeatureFlags {
+ darkMode: boolean;
+ newDashboard: boolean;
+ betaFeatures: boolean;
+}
+
+async function getFeatureFlags(
+ kv: KVNamespace,
+ userId?: string
+): Promise<FeatureFlags> {
+ // Try user-specific flags first
+ if (userId) {
+ const userFlags = await kv.get<FeatureFlags>(`flags:user:${userId}`, {
+ type: 'json',
+ cacheTtl: 300,
+ });
+ if (userFlags) return userFlags;
+ }
+
+ // Fallback to global flags
+ const globalFlags = await kv.get<FeatureFlags>('flags:global', {
+ type: 'json',
+ cacheTtl: 300,
+ });
+
+ return globalFlags || {
+ darkMode: false,
+ newDashboard: false,
+ betaFeatures: false,
+ };
+}
+
+// Update global flags
+app.post('/admin/flags', async (c) => {
+ const flags = await c.req.json<FeatureFlags>();
+
+ await c.env.CONFIG.put('flags:global', JSON.stringify(flags), {
+ metadata: { updatedAt: Date.now() },
+ });
+
+ return c.json({ success: true });
+});
+```
+
+---
+
+## Understanding Eventual Consistency
+
+KV is **eventually consistent** across Cloudflare's global network:
+
+### How It Works:
+
+1. **Writes** are immediately visible in the **same location**
+2. **Other locations** see the update within **~60 seconds** (or your `cacheTtl` value)
+3. **Cached reads** may return stale data during propagation
+
+### Implications:
+
+```typescript
+// In Tokyo data center:
+await env.MY_KV.put('counter', '1');
+const value1 = await env.MY_KV.get('counter'); // "1" βœ…
+
+// In London data center (within 60 seconds):
+const value2 = await env.MY_KV.get('counter'); // Might still be old value ⚠️
+
+// After 60+ seconds:
+const value3 = await env.MY_KV.get('counter'); // "1" βœ…
+```
+
+### Best Practices:
+
+βœ… **Use KV for:**
+- Read-heavy workloads (100:1 read/write ratio)
+- Data that doesn't require immediate global consistency
+- Configuration, feature flags, caching
+- User preferences, session data
+
+❌ **Don't use KV for:**
+- Financial transactions requiring atomic operations
+- Data requiring strong consistency
+- High-frequency writes to same key (>1/second)
+- Critical data where stale reads are unacceptable
+
+**If you need strong consistency, use [Durable Objects](https://developers.cloudflare.com/durable-objects/).**
+
+---
+
+## Wrangler CLI Operations
+
+### Create Namespace
+
+```bash
+# Production namespace
+npx wrangler kv namespace create MY_NAMESPACE
+
+# Preview/development namespace
+npx wrangler kv namespace create MY_NAMESPACE --preview
+```
+
+### List Namespaces
+
+```bash
+npx wrangler kv namespace list
+```
+
+### Write Key-Value Pairs
+
+```bash
+# Write single key
+npx wrangler kv key put --binding=MY_NAMESPACE "my-key" "my-value"
+
+# Write from file
+npx wrangler kv key put --binding=MY_NAMESPACE "config" --path=config.json
+
+# Write with metadata
+npx wrangler kv key put --binding=MY_NAMESPACE "key" "value" --metadata='{"version":1}'
+
+# Write with TTL (seconds)
+npx wrangler kv key put --binding=MY_NAMESPACE "session" "data" --ttl=3600
+```
+
+### Read Key-Value Pairs
+
+```bash
+# Read single key
+npx wrangler kv key get --binding=MY_NAMESPACE "my-key"
+
+# Read to file
+npx wrangler kv key get --binding=MY_NAMESPACE "image" --path=image.png
+```
+
+### List Keys
+
+```bash
+# List all keys
+npx wrangler kv key list --binding=MY_NAMESPACE
+
+# List with prefix
+npx wrangler kv key list --binding=MY_NAMESPACE --prefix="user:"
+
+# Pretty print
+npx wrangler kv key list --binding=MY_NAMESPACE | jq "."
+```
+
+### Delete Keys
+
+```bash
+# Delete single key
+npx wrangler kv key delete --binding=MY_NAMESPACE "my-key"
+```
+
+### Bulk Operations
+
+```bash
+# Bulk write (up to 10,000 keys)
+npx wrangler kv bulk put --binding=MY_NAMESPACE data.json
+
+# data.json format:
+# [
+# {"key": "key1", "value": "value1"},
+# {"key": "key2", "value": "value2", "expiration_ttl": 3600}
+# ]
+
+# Bulk delete (up to 10,000 keys)
+npx wrangler kv bulk delete --binding=MY_NAMESPACE keys.json
+
+# keys.json format:
+# ["key1", "key2", "key3"]
+```
+
+---
+
+## Limits & Quotas
+
+| Feature | Free Plan | Paid Plan |
+|---------|-----------|-----------|
+| **Reads per day** | 100,000 | Unlimited |
+| **Writes per day** (different keys) | 1,000 | Unlimited |
+| **Writes per key per second** | 1 | 1 |
+| **Operations per Worker invocation** | 1,000 | 1,000 |
+| **Namespaces per account** | 1,000 | 1,000 |
+| **Storage per account** | 1 GB | Unlimited |
+| **Storage per namespace** | 1 GB | Unlimited |
+| **Keys per namespace** | Unlimited | Unlimited |
+| **Key size** | 512 bytes | 512 bytes |
+| **Metadata size** | 1024 bytes | 1024 bytes |
+| **Value size** | 25 MiB | 25 MiB |
+| **Minimum cacheTtl** | 60 seconds | 60 seconds |
+| **Maximum cacheTtl** | Number.MAX_SAFE_INTEGER | Number.MAX_SAFE_INTEGER |
+
+**Important Notes:**
+- **1 write/second per key**: Concurrent writes to the same key cause 429 errors
+- **1000 operations per invocation**: Bulk operations count as **1 operation**
+- **Bulk reads** (reading multiple keys) count as a single operation
+- **REST API** is subject to [Cloudflare API rate limits](https://developers.cloudflare.com/fundamentals/api/reference/limits/)
+
+---
+
+## TypeScript Types
+
+```typescript
+// KVNamespace type is provided by @cloudflare/workers-types
+interface KVNamespace {
+ get(key: string, options?: Partial<KVGetOptions<undefined>>): Promise<string | null>;
+ get(key: string, type: "text"): Promise<string | null>;
+ get<ExpectedValue = unknown>(key: string, type: "json"): Promise<ExpectedValue | null>;
+ get(key: string, type: "arrayBuffer"): Promise<ArrayBuffer | null>;
+ get(key: string, type: "stream"): Promise<ReadableStream | null>;
+ get(key: string, options?: KVGetOptions<"text">): Promise<string | null>;
+ get<ExpectedValue = unknown>(key: string, options?: KVGetOptions<"json">): Promise<ExpectedValue | null>;
+ get(key: string, options?: KVGetOptions<"arrayBuffer">): Promise<ArrayBuffer | null>;
+ get(key: string, options?: KVGetOptions<"stream">): Promise<ReadableStream | null>;
+ get(keys: string[]): Promise<Map<string, string | null>>;
+ get(keys: string[], type: "text"): Promise<Map<string, string | null>>;
+ get<ExpectedValue = unknown>(keys: string[], type: "json"): Promise<Map<string, ExpectedValue | null>>;
+
+ getWithMetadata<Metadata = unknown>(key: string, options?: Partial<KVGetOptions<undefined>>): Promise<KVGetWithMetadataResult<string, Metadata>>;
+ getWithMetadata<Metadata = unknown>(key: string, type: "text"): Promise<KVGetWithMetadataResult<string, Metadata>>;
+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: string, type: "json"): Promise<KVGetWithMetadataResult<ExpectedValue, Metadata>>;
+ getWithMetadata<Metadata = unknown>(key: string, options?: KVGetOptions<"text">): Promise<KVGetWithMetadataResult<string, Metadata>>;
+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: string, options?: KVGetOptions<"json">): Promise<KVGetWithMetadataResult<ExpectedValue, Metadata>>;
+ getWithMetadata<Metadata = unknown>(keys: string[]): Promise<Map<string, KVGetWithMetadataResult<string, Metadata>>>;
+ getWithMetadata<Metadata = unknown>(keys: string[], type: "text"): Promise<Map<string, KVGetWithMetadataResult<string, Metadata>>>;
+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(keys: string[], type: "json"): Promise<Map<string, KVGetWithMetadataResult<ExpectedValue, Metadata>>>;
+
+ put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVPutOptions): Promise<void>;
+
+ delete(key: string): Promise<void>;
+
+ list<Metadata = unknown>(options?: KVListOptions): Promise<KVListResult<Metadata>>;
+}
+
+interface KVGetOptions<Type> {
+ type: Type;
+ cacheTtl?: number;
+}
+
+interface KVGetWithMetadataResult<Value, Metadata> {
+ value: Value | null;
+ metadata: Metadata | null;
+}
+
+interface KVPutOptions {
+ expiration?: number; // Seconds since epoch
+ expirationTtl?: number; // Seconds from now (minimum 60)
+ metadata?: any; // Serializable to JSON, max 1024 bytes
+}
+
+interface KVListOptions {
+ prefix?: string;
+ limit?: number; // Default 1000, max 1000
+ cursor?: string;
+}
+
+interface KVListResult<Metadata = unknown> {
+ keys: {
+ name: string;
+ expiration?: number;
+ metadata?: Metadata;
+ }[];
+ list_complete: boolean;
+ cursor?: string;
+}
+```
+
+---
+
+## Error Handling
+
+### Common Errors
+
+#### 1. Rate Limit (429 Too Many Requests)
+
+```typescript
+try {
+ await env.MY_KV.put('counter', '1');
+ await env.MY_KV.put('counter', '2'); // Too fast! < 1 second
+} catch (error) {
+ // Error: KV PUT failed: 429 Too Many Requests
+ console.error(error);
+}
+
+// Solution: Use retry with backoff (see putWithRetry example above)
+```
+
+#### 2. Value Too Large
+
+```typescript
+const largeValue = 'x'.repeat(26 * 1024 * 1024); // > 25 MiB
+
+try {
+ await env.MY_KV.put('large', largeValue);
+} catch (error) {
+ // Error: Value too large
+ console.error(error);
+}
+
+// Solution: Check size before writing
+if (value.length > 25 * 1024 * 1024) {
+ throw new Error('Value exceeds 25 MiB limit');
+}
+```
+
+#### 3. Metadata Too Large
+
+```typescript
+const metadata = { data: 'x'.repeat(2000) }; // > 1024 bytes serialized
+
+try {
+ await env.MY_KV.put('key', 'value', { metadata });
+} catch (error) {
+ // Error: Metadata too large
+ console.error(error);
+}
+
+// Solution: Validate metadata size
+const serialized = JSON.stringify(metadata);
+if (serialized.length > 1024) {
+ throw new Error('Metadata exceeds 1024 byte limit');
+}
+```
+
+#### 4. Invalid CacheTtl
+
+```typescript
+// ❌ Too low
+await env.MY_KV.get('key', { cacheTtl: 30 }); // Error: minimum is 60
+
+// βœ… Correct
+await env.MY_KV.get('key', { cacheTtl: 60 });
+```
+
+---
+
+## Always Do βœ…
+
+1. **Use bulk operations** when reading multiple keys (counts as 1 operation)
+2. **Set cacheTtl** for frequently-read, infrequently-updated data
+3. **Store small values in metadata** when using `list()` frequently
+4. **Check `list_complete`** when paginating, not `keys.length === 0`
+5. **Use retry logic with exponential backoff** for write operations
+6. **Validate sizes** before writing (key 512 bytes, value 25 MiB, metadata 1 KB)
+7. **Use preview namespaces** for local development
+8. **Set appropriate TTLs** for cache invalidation (minimum 60 seconds)
+9. **Coalesce related keys** for better caching performance
+10. **Use KV for read-heavy workloads** (100:1 read/write ratio ideal)
+
+---
+
+## Never Do ❌
+
+1. **Never write to same key >1/second** - Causes 429 rate limit errors
+2. **Never assume immediate global consistency** - Takes ~60 seconds to propagate
+3. **Never use KV for atomic operations** - Use Durable Objects instead
+4. **Never set cacheTtl <60 seconds** - Will fail
+5. **Never commit namespace IDs to public repos** - Use environment variables
+6. **Never exceed 1000 operations per invocation** - Use bulk operations
+7. **Never rely on write order** - Eventual consistency means no guarantees
+8. **Never store sensitive data without encryption** - KV is not encrypted at rest by default
+9. **Never use KV for high-frequency writes** - Not designed for write-heavy workloads
+10. **Never forget to handle null values** - `get()` returns `null` if key doesn't exist
+
+---
+
+## Troubleshooting
+
+### Issue: "429 Too Many Requests" on writes
+
+**Cause:** Writing to same key more than once per second
+
+**Solution:**
+```typescript
+// ❌ Bad
+for (let i = 0; i < 10; i++) {
+ await kv.put('counter', String(i)); // Rate limit!
+}
+
+// βœ… Good - consolidate writes
+const finalValue = '9';
+await kv.put('counter', finalValue);
+
+// βœ… Good - use retry with backoff
+await putWithRetry(kv, 'counter', String(i));
+```
+
+---
+
+### Issue: Stale reads after write
+
+**Cause:** Eventual consistency - writes take up to 60 seconds to propagate globally
+
+**Solution:**
+```typescript
+// Accept that reads may be stale for up to 60 seconds
+// OR use Durable Objects for strong consistency
+// OR implement application-level cache invalidation
+```
+
+---
+
+### Issue: "Operations limit exceeded"
+
+**Cause:** More than 1000 KV operations in single Worker invocation
+
+**Solution:**
+```typescript
+// ❌ Bad - 5000 operations
+const keys = Array.from({ length: 5000 }, (_, i) => `key${i}`);
+for (const key of keys) {
+ await kv.get(key); // Exceeds 1000 limit
+}
+
+// βœ… Good - 1 operation (bulk read)
+const values = await kv.get(keys);
+```
+
+---
+
+### Issue: List returns empty but cursor exists
+
+**Cause:** Recently deleted/expired keys create "tombstones" in the list
+
+**Solution:**
+```typescript
+// Always check list_complete, not keys.length
+let cursor: string | undefined;
+
+do {
+ const result = await kv.list({ cursor });
+
+ // Process keys even if empty
+ processKeys(result.keys);
+
+ // CORRECT: Check list_complete
+ cursor = result.list_complete ? undefined : result.cursor;
+} while (cursor);
+```
+
+---
+
+## Production Checklist
+
+Before deploying to production:
+
+- [ ] Environment-specific namespaces configured (`id` vs `preview_id`)
+- [ ] Namespace IDs stored in environment variables (not hardcoded)
+- [ ] Rate limit retry logic implemented for writes
+- [ ] Appropriate `cacheTtl` values set for reads
+- [ ] Metadata sizes validated (<1024 bytes)
+- [ ] Value sizes validated (<25 MiB)
+- [ ] Key sizes validated (<512 bytes)
+- [ ] Bulk operations used where possible
+- [ ] Pagination implemented correctly for `list()`
+- [ ] Error handling for null values
+- [ ] Monitoring/alerting for rate limits
+- [ ] Documentation for eventual consistency behavior
+
+---
+
+## Related Documentation
+
+- [Cloudflare KV Docs](https://developers.cloudflare.com/kv/)
+- [KV API Reference](https://developers.cloudflare.com/kv/api/)
+- [KV Limits](https://developers.cloudflare.com/kv/platform/limits/)
+- [How KV Works](https://developers.cloudflare.com/kv/concepts/how-kv-works/)
+- [Wrangler KV Commands](https://developers.cloudflare.com/workers/wrangler/commands/#kv)
+
+---
+
+**Last Updated**: 2025-10-21
+**Version**: 1.0.0
+**Maintainer**: Jeremy Dawes | [email protected]
diff --git a/skills/cloudflare-kv/reference/best-practices.md b/skills/cloudflare-kv/reference/best-practices.md
new file mode 100644
index 00000000..94c7a98c
--- /dev/null
+++ b/skills/cloudflare-kv/reference/best-practices.md
@@ -0,0 +1,720 @@
+# Cloudflare Workers KV - Best Practices
+
+This document contains production-tested best practices for Cloudflare Workers KV.
+
+---
+
+## Table of Contents
+
+1. [Performance Optimization](#performance-optimization)
+2. [Caching Strategies](#caching-strategies)
+3. [Key Design](#key-design)
+4. [Metadata Usage](#metadata-usage)
+5. [Error Handling](#error-handling)
+6. [Security](#security)
+7. [Cost Optimization](#cost-optimization)
+8. [Monitoring & Debugging](#monitoring--debugging)
+
+---
+
+## Performance Optimization
+
+### 1. Use Bulk Operations
+
+**❌ Bad: Individual reads**
+```typescript
+const value1 = await kv.get('key1'); // 1 operation
+const value2 = await kv.get('key2'); // 1 operation
+const value3 = await kv.get('key3'); // 1 operation
+// Total: 3 operations
+```
+
+**βœ… Good: Bulk read**
+```typescript
+const values = await kv.get(['key1', 'key2', 'key3']); // 1 operation
+// Total: 1 operation
+```
+
+**Benefits:**
+- Counts as 1 operation against the 1000/invocation limit
+- Faster execution
+- Lower latency
+
+---
+
+### 2. Use CacheTtl for Frequently-Read Data
+
+**❌ Bad: No edge caching**
+```typescript
+const value = await kv.get('config'); // Fetches from KV every time
+```
+
+**βœ… Good: Edge caching**
+```typescript
+const value = await kv.get('config', {
+ cacheTtl: 300, // Cache at edge for 5 minutes
+});
+```
+
+**Guidelines:**
+- Use `cacheTtl` for data that changes infrequently
+- Minimum: 60 seconds
+- Typical values:
+ - Configuration: 300-600 seconds (5-10 minutes)
+ - Static content: 3600+ seconds (1+ hour)
+ - Frequently changing: 60-120 seconds
+
+**Trade-off:** Higher `cacheTtl` = faster reads but slower updates propagate
+
+---
+
+### 3. Coalesce Related Keys
+
+**❌ Bad: Many small keys**
+```typescript
+await kv.put('user:123:name', 'John');
+await kv.put('user:123:email', '[email protected]');
+await kv.put('user:123:age', '30');
+
+// Reading requires 3 operations
+const name = await kv.get('user:123:name');
+const email = await kv.get('user:123:email');
+const age = await kv.get('user:123:age');
+```
+
+**βœ… Good: Coalesced key**
+```typescript
+await kv.put('user:123', JSON.stringify({
+ name: 'John',
+ email: '[email protected]',
+ age: 30,
+}));
+
+// Reading requires 1 operation
+const user = await kv.get<User>('user:123', { type: 'json' });
+```
+
+**Benefits:**
+- Fewer operations
+- Single cache entry
+- Faster reads
+
+**When to use:**
+- Related data that's always accessed together
+- Data that doesn't update frequently
+- Values stay under 25 MiB total
+
+---
+
+### 4. Store Small Values in Metadata
+
+**❌ Bad: Separate keys for metadata**
+```typescript
+await kv.put('user:123', 'data');
+await kv.put('user:123:status', 'active');
+
+// List requires additional get() calls
+const users = await kv.list({ prefix: 'user:' });
+for (const key of users.keys) {
+ const status = await kv.get(`${key.name}:status`); // Extra operation!
+}
+```
+
+**βœ… Good: Metadata pattern**
+```typescript
+await kv.put('user:123', 'data', {
+ metadata: { status: 'active', plan: 'pro' },
+});
+
+// List includes metadata, no extra get() calls!
+const users = await kv.list({ prefix: 'user:' });
+for (const key of users.keys) {
+ console.log(key.name, key.metadata.status); // No extra operations
+}
+```
+
+**When to use:**
+- Values fit in 1024 bytes
+- Frequently use `list()` operations
+- Need to filter/process many keys
+
+---
+
+## Caching Strategies
+
+### 1. Cache-Aside Pattern (Read-Through)
+
+```typescript
+async function getCached<T>(
+ kv: KVNamespace,
+ key: string,
+ fetchFn: () => Promise<T>,
+ ttl = 3600
+): Promise<T> {
+ // Try cache
+ const cached = await kv.get<T>(key, {
+ type: 'json',
+ cacheTtl: 300,
+ });
+
+ if (cached !== null) return cached;
+
+ // Cache miss - fetch and store
+ const data = await fetchFn();
+ await kv.put(key, JSON.stringify(data), { expirationTtl: ttl });
+
+ return data;
+}
+```
+
+**Use when:**
+- Data is expensive to compute/fetch
+- Read >> Write ratio
+- Acceptable to serve slightly stale data
+
+---
+
+### 2. Write-Through Cache
+
+```typescript
+async function updateCached<T>(
+ kv: KVNamespace,
+ key: string,
+ data: T,
+ ttl = 3600
+): Promise<void> {
+ // Update database
+ await database.update(data);
+
+ // Update cache immediately
+ await kv.put(key, JSON.stringify(data), { expirationTtl: ttl });
+}
+```
+
+**Use when:**
+- Need cache consistency
+- Write operations are infrequent
+- Cache must always reflect latest data
+
+---
+
+### 3. Stale-While-Revalidate
+
+```typescript
+async function staleWhileRevalidate<T>(
+ kv: KVNamespace,
+ key: string,
+ fetchFn: () => Promise<T>,
+ ctx: ExecutionContext,
+ staleThreshold = 300
+): Promise<T> {
+ const { value, metadata } = await kv.getWithMetadata<T, { timestamp: number }>(
+ key,
+ { type: 'json' }
+ );
+
+ if (value !== null && metadata) {
+ const age = Date.now() - metadata.timestamp;
+
+ // Refresh in background if stale
+ if (age > staleThreshold * 1000) {
+ ctx.waitUntil(
+ (async () => {
+ const fresh = await fetchFn();
+ await kv.put(key, JSON.stringify(fresh), {
+ metadata: { timestamp: Date.now() },
+ });
+ })()
+ );
+ }
+
+ return value;
+ }
+
+ // Cache miss
+ const data = await fetchFn();
+ await kv.put(key, JSON.stringify(data), {
+ metadata: { timestamp: Date.now() },
+ });
+
+ return data;
+}
+```
+
+**Use when:**
+- Fast response time is critical
+- Acceptable to serve slightly stale data
+- Background refresh is acceptable
+
+---
+
+## Key Design
+
+### 1. Use Hierarchical Namespaces
+
+**βœ… Good key patterns:**
+```
+user:123:profile
+user:123:settings
+user:123:sessions
+
+session:abc123:data
+session:abc123:metadata
+
+cache:api:users:list
+cache:api:posts:123
+cache:db:query:hash123
+```
+
+**Benefits:**
+- Easy to filter with `list({ prefix: 'user:123:' })`
+- Easy to invalidate groups
+- Clear organization
+
+---
+
+### 2. Use Lexicographic Ordering
+
+Keys are always sorted lexicographically, so design keys to take advantage:
+
+```typescript
+// Date-based keys (ISO format sorts correctly)
+'log:2025-10-21:entry1'
+'log:2025-10-22:entry1'
+
+// Numeric IDs (zero-padded)
+'user:00000001'
+'user:00000123'
+'user:00001000'
+
+// Priority-based (prefix with number)
+'task:1:high-priority'
+'task:2:medium-priority'
+'task:3:low-priority'
+```
+
+---
+
+### 3. Avoid Key Collisions
+
+**❌ Bad:**
+```
+user:123 // User data
+user:123:count // Some counter
+user:123 // Different data? Collision!
+```
+
+**βœ… Good:**
+```
+user:data:123
+user:counter:123
+user:session:123
+```
+
+---
+
+## Metadata Usage
+
+### 1. Track Versions
+
+```typescript
+await kv.put('config', JSON.stringify(data), {
+ metadata: {
+ version: 2,
+ updatedAt: Date.now(),
+ updatedBy: 'admin',
+ },
+});
+```
+
+---
+
+### 2. Audit Trails
+
+```typescript
+await kv.put(key, value, {
+ metadata: {
+ createdAt: Date.now(),
+ createdBy: userId,
+ accessCount: 0,
+ },
+});
+```
+
+---
+
+### 3. Feature Flags
+
+```typescript
+// Store flags in metadata for fast list() access
+await kv.put(`flag:${name}`, JSON.stringify(config), {
+ metadata: {
+ enabled: true,
+ rolloutPercentage: 50,
+ },
+});
+
+// List all flags without additional get() calls
+const flags = await kv.list({ prefix: 'flag:' });
+```
+
+---
+
+## Error Handling
+
+### 1. Handle Rate Limits (429)
+
+```typescript
+async function putWithRetry(
+ kv: KVNamespace,
+ key: string,
+ value: string,
+ maxAttempts = 5
+): Promise<void> {
+ let attempts = 0;
+ let delay = 1000;
+
+ while (attempts < maxAttempts) {
+ try {
+ await kv.put(key, value);
+ return;
+ } catch (error) {
+ const message = (error as Error).message;
+
+ if (message.includes('429') || message.includes('Too Many Requests')) {
+ attempts++;
+ if (attempts >= maxAttempts) {
+ throw new Error('Max retry attempts reached');
+ }
+
+ await new Promise(resolve => setTimeout(resolve, delay));
+ delay *= 2; // Exponential backoff
+ } else {
+ throw error;
+ }
+ }
+ }
+}
+```
+
+---
+
+### 2. Handle Null Values
+
+```typescript
+// ❌ Bad
+const value = await kv.get('key');
+console.log(value.toUpperCase()); // Error if key doesn't exist
+
+// βœ… Good
+const value = await kv.get('key');
+if (value !== null) {
+ console.log(value.toUpperCase());
+}
+
+// βœ… Good: Default value
+const value = await kv.get('key') ?? 'default';
+```
+
+---
+
+### 3. Validate Input Sizes
+
+```typescript
+function validateKVInput(key: string, value: string, metadata?: any): void {
+ // Key size
+ if (new TextEncoder().encode(key).length > 512) {
+ throw new Error('Key exceeds 512 bytes');
+ }
+
+ // Value size
+ if (new TextEncoder().encode(value).length > 25 * 1024 * 1024) {
+ throw new Error('Value exceeds 25 MiB');
+ }
+
+ // Metadata size
+ if (metadata) {
+ const serialized = JSON.stringify(metadata);
+ if (new TextEncoder().encode(serialized).length > 1024) {
+ throw new Error('Metadata exceeds 1024 bytes');
+ }
+ }
+}
+```
+
+---
+
+## Security
+
+### 1. Never Commit Namespace IDs
+
+**❌ Bad:**
+```jsonc
+{
+ "kv_namespaces": [
+ {
+ "binding": "MY_KV",
+ "id": "abc123def456..." // Hardcoded!
+ }
+ ]
+}
+```
+
+**βœ… Good:**
+```jsonc
+{
+ "kv_namespaces": [
+ {
+ "binding": "MY_KV",
+ "id": "${KV_NAMESPACE_ID}" // Environment variable
+ }
+ ]
+}
+```
+
+---
+
+### 2. Encrypt Sensitive Data
+
+```typescript
+// Encrypt before storing
+const encrypted = await encrypt(sensitiveData, encryptionKey);
+await kv.put('sensitive:123', encrypted);
+
+// Decrypt after reading
+const encrypted = await kv.get('sensitive:123');
+const decrypted = await decrypt(encrypted, encryptionKey);
+```
+
+---
+
+### 3. Use Separate Namespaces for Environments
+
+```jsonc
+{
+ "kv_namespaces": [
+ {
+ "binding": "MY_KV",
+ "id": "production-namespace-id",
+ "preview_id": "development-namespace-id"
+ }
+ ]
+}
+```
+
+---
+
+## Cost Optimization
+
+### 1. Minimize Write Operations (Free Tier)
+
+**Free tier limits:**
+- 1,000 writes per day
+- 100,000 reads per day
+
+**Strategies:**
+- Batch writes when possible
+- Use longer TTLs to reduce rewrites
+- Cache data in memory if accessed frequently within same invocation
+
+---
+
+### 2. Use Metadata Instead of Separate Keys
+
+**❌ Expensive: 3 writes, 3 reads**
+```typescript
+await kv.put('user:123:status', 'active');
+await kv.put('user:123:plan', 'pro');
+await kv.put('user:123:updated', Date.now().toString());
+```
+
+**βœ… Cheaper: 1 write, 1 read**
+```typescript
+await kv.put('user:123', '', {
+ metadata: { status: 'active', plan: 'pro', updated: Date.now() },
+});
+```
+
+---
+
+### 3. Set Appropriate TTLs
+
+Longer TTLs = fewer rewrites = lower costs
+
+```typescript
+// ❌ Expensive: Rewrites every minute
+await kv.put('cache:data', data, { expirationTtl: 60 });
+
+// βœ… Better: Rewrites every hour
+await kv.put('cache:data', data, { expirationTtl: 3600 });
+```
+
+---
+
+## Monitoring & Debugging
+
+### 1. Track Cache Hit Rates
+
+```typescript
+let stats = { hits: 0, misses: 0 };
+
+async function getCached<T>(kv: KVNamespace, key: string): Promise<T | null> {
+ const value = await kv.get<T>(key, { type: 'json' });
+
+ if (value !== null) {
+ stats.hits++;
+ } else {
+ stats.misses++;
+ }
+
+ return value;
+}
+
+// View stats
+app.get('/stats', (c) => {
+ const total = stats.hits + stats.misses;
+ const hitRate = total > 0 ? (stats.hits / total) * 100 : 0;
+
+ return c.json({
+ hits: stats.hits,
+ misses: stats.misses,
+ hitRate: `${hitRate.toFixed(2)}%`,
+ });
+});
+```
+
+---
+
+### 2. Log KV Operations
+
+```typescript
+async function loggedGet<T>(
+ kv: KVNamespace,
+ key: string
+): Promise<T | null> {
+ const start = Date.now();
+ const value = await kv.get<T>(key, { type: 'json' });
+ const duration = Date.now() - start;
+
+ console.log({
+ operation: 'get',
+ key,
+ found: value !== null,
+ duration,
+ });
+
+ return value;
+}
+```
+
+---
+
+### 3. Use Namespace Prefixes for Testing
+
+```typescript
+const namespace = env.ENVIRONMENT === 'production' ? 'prod' : 'test';
+
+await kv.put(`${namespace}:user:123`, data);
+
+// Cleanup test data
+if (env.ENVIRONMENT === 'test') {
+ // Delete all test: keys
+ let cursor: string | undefined;
+ do {
+ const result = await kv.list({ prefix: 'test:', cursor });
+ await Promise.all(result.keys.map(k => kv.delete(k.name)));
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+}
+```
+
+---
+
+## Production Checklist
+
+Before deploying to production:
+
+- [ ] Environment-specific namespaces configured
+- [ ] Namespace IDs stored in environment variables
+- [ ] Rate limit retry logic implemented
+- [ ] Appropriate `cacheTtl` values set
+- [ ] Input validation for key/value/metadata sizes
+- [ ] Bulk operations used where possible
+- [ ] Pagination implemented correctly for `list()`
+- [ ] Error handling for null values
+- [ ] Monitoring/alerting for rate limits
+- [ ] Documentation for eventual consistency behavior
+- [ ] Security review for sensitive data
+- [ ] Cost analysis for expected usage
+
+---
+
+## Common Patterns
+
+### 1. Session Management
+
+```typescript
+// Store session
+await kv.put(`session:${sessionId}`, JSON.stringify(sessionData), {
+ expirationTtl: 3600, // 1 hour
+ metadata: { userId, createdAt: Date.now() },
+});
+
+// Read session
+const session = await kv.get<SessionData>(`session:${sessionId}`, {
+ type: 'json',
+ cacheTtl: 60, // Cache for 1 minute
+});
+```
+
+---
+
+### 2. API Response Caching
+
+```typescript
+const cacheKey = `api:${endpoint}:${JSON.stringify(params)}`;
+
+let response = await kv.get<ApiResponse>(cacheKey, {
+ type: 'json',
+ cacheTtl: 300,
+});
+
+if (!response) {
+ response = await fetchFromAPI(endpoint, params);
+ await kv.put(cacheKey, JSON.stringify(response), {
+ expirationTtl: 600,
+ });
+}
+
+return response;
+```
+
+---
+
+### 3. Configuration Management
+
+```typescript
+// Update config
+await kv.put('config:app', JSON.stringify(config), {
+ metadata: {
+ version: 2,
+ updatedAt: Date.now(),
+ updatedBy: adminId,
+ },
+});
+
+// Read config (with long cache)
+const config = await kv.get<AppConfig>('config:app', {
+ type: 'json',
+ cacheTtl: 3600, // Cache for 1 hour
+});
+```
+
+---
+
+## References
+
+- [Cloudflare KV Documentation](https://developers.cloudflare.com/kv/)
+- [How KV Works](https://developers.cloudflare.com/kv/concepts/how-kv-works/)
+- [KV Limits](https://developers.cloudflare.com/kv/platform/limits/)
+- [KV Pricing](https://developers.cloudflare.com/kv/platform/pricing/)
diff --git a/skills/cloudflare-kv/reference/workers-api.md b/skills/cloudflare-kv/reference/workers-api.md
new file mode 100644
index 00000000..96a9b411
--- /dev/null
+++ b/skills/cloudflare-kv/reference/workers-api.md
@@ -0,0 +1,483 @@
+# Cloudflare Workers KV - Complete API Reference
+
+This document provides the complete Workers KV API reference based on official Cloudflare documentation.
+
+---
+
+## KVNamespace Interface
+
+```typescript
+interface KVNamespace {
+ get(key: string, options?: Partial<KVGetOptions<undefined>>): Promise<string | null>;
+ get(key: string, type: "text"): Promise<string | null>;
+ get<ExpectedValue = unknown>(key: string, type: "json"): Promise<ExpectedValue | null>;
+ get(key: string, type: "arrayBuffer"): Promise<ArrayBuffer | null>;
+ get(key: string, type: "stream"): Promise<ReadableStream | null>;
+ get(keys: string[]): Promise<Map<string, string | null>>;
+ get<ExpectedValue = unknown>(keys: string[], type: "json"): Promise<Map<string, ExpectedValue | null>>;
+
+ getWithMetadata<Metadata = unknown>(key: string, options?: Partial<KVGetOptions<undefined>>): Promise<KVGetWithMetadataResult<string, Metadata>>;
+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: string, type: "json"): Promise<KVGetWithMetadataResult<ExpectedValue, Metadata>>;
+ getWithMetadata<Metadata = unknown>(keys: string[]): Promise<Map<string, KVGetWithMetadataResult<string, Metadata>>>;
+
+ put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVPutOptions): Promise<void>;
+
+ delete(key: string): Promise<void>;
+
+ list<Metadata = unknown>(options?: KVListOptions): Promise<KVListResult<Metadata>>;
+}
+```
+
+---
+
+## Read Operations
+
+### `get()` - Single Key
+
+Read a single key-value pair.
+
+**Signature:**
+```typescript
+get(key: string, options?: KVGetOptions): Promise<T | null>
+```
+
+**Parameters:**
+- `key` (string, required) - The key to read
+- `options` (object, optional):
+ - `type` - Return type: `"text"` (default), `"json"`, `"arrayBuffer"`, `"stream"`
+ - `cacheTtl` (number) - Edge cache duration in seconds (minimum: 60)
+
+**Returns:**
+- `Promise<T | null>` - Value or `null` if key doesn't exist
+
+**Examples:**
+```typescript
+// Text (default)
+const value = await env.MY_KV.get('my-key');
+
+// JSON
+const data = await env.MY_KV.get<MyType>('my-key', { type: 'json' });
+
+// With cache optimization
+const value = await env.MY_KV.get('my-key', {
+ type: 'text',
+ cacheTtl: 300, // Cache for 5 minutes
+});
+
+// ArrayBuffer
+const buffer = await env.MY_KV.get('binary-key', { type: 'arrayBuffer' });
+
+// Stream (for large values)
+const stream = await env.MY_KV.get('large-file', { type: 'stream' });
+```
+
+---
+
+### `get()` - Multiple Keys (Bulk)
+
+Read multiple keys in a single operation.
+
+**Signature:**
+```typescript
+get(keys: string[], type?: 'text' | 'json'): Promise<Map<string, T | null>>
+```
+
+**Parameters:**
+- `keys` (string[], required) - Array of keys to read
+- `type` (optional) - Return type: `"text"` (default) or `"json"`
+
+**Returns:**
+- `Promise<Map<string, T | null>>` - Map of key-value pairs
+
+**Important:**
+- Counts as **1 operation** regardless of number of keys
+- Only supports `text` and `json` types (not `arrayBuffer` or `stream`)
+- For binary/stream types, use individual `get()` calls with `Promise.all()`
+
+**Examples:**
+```typescript
+// Read multiple keys
+const keys = ['key1', 'key2', 'key3'];
+const values = await env.MY_KV.get(keys);
+
+// Access values
+const value1 = values.get('key1');
+const value2 = values.get('key2');
+
+// Convert to object
+const obj = Object.fromEntries(values);
+
+// Read as JSON
+const values = await env.MY_KV.get<MyType>(keys, 'json');
+```
+
+---
+
+### `getWithMetadata()` - Single Key
+
+Read key-value pair with metadata.
+
+**Signature:**
+```typescript
+getWithMetadata<Value, Metadata>(
+ key: string,
+ options?: KVGetOptions
+): Promise<KVGetWithMetadataResult<Value, Metadata>>
+```
+
+**Parameters:**
+- Same as `get()`
+
+**Returns:**
+```typescript
+{
+ value: Value | null,
+ metadata: Metadata | null
+}
+```
+
+**Examples:**
+```typescript
+// Get with metadata
+const { value, metadata } = await env.MY_KV.getWithMetadata('my-key');
+
+// Get as JSON with metadata
+const { value, metadata } = await env.MY_KV.getWithMetadata<MyType>('my-key', {
+ type: 'json',
+ cacheTtl: 300,
+});
+
+if (value !== null) {
+ console.log('Value:', value);
+ console.log('Metadata:', metadata);
+}
+```
+
+---
+
+### `getWithMetadata()` - Multiple Keys (Bulk)
+
+Read multiple keys with metadata.
+
+**Signature:**
+```typescript
+getWithMetadata<Metadata>(
+ keys: string[],
+ type?: 'text' | 'json'
+): Promise<Map<string, KVGetWithMetadataResult<T, Metadata>>>
+```
+
+**Examples:**
+```typescript
+const keys = ['key1', 'key2'];
+const results = await env.MY_KV.getWithMetadata(keys);
+
+for (const [key, data] of results) {
+ console.log(key, data.value, data.metadata);
+}
+```
+
+---
+
+## Write Operations
+
+### `put()` - Write Key-Value Pair
+
+Write or update a key-value pair.
+
+**Signature:**
+```typescript
+put(
+ key: string,
+ value: string | ArrayBuffer | ArrayBufferView | ReadableStream,
+ options?: KVPutOptions
+): Promise<void>
+```
+
+**Parameters:**
+- `key` (string, required) - Maximum 512 bytes
+- `value` (required) - Maximum 25 MiB
+- `options` (object, optional):
+ - `expiration` (number) - Absolute expiration time (seconds since epoch)
+ - `expirationTtl` (number) - TTL in seconds from now (minimum: 60)
+ - `metadata` (any) - JSON-serializable metadata (maximum: 1024 bytes)
+
+**Returns:**
+- `Promise<void>`
+
+**Examples:**
+```typescript
+// Simple write
+await env.MY_KV.put('key', 'value');
+
+// Write JSON
+await env.MY_KV.put('user:123', JSON.stringify({ name: 'John' }));
+
+// Write with TTL
+await env.MY_KV.put('session', sessionData, {
+ expirationTtl: 3600, // Expire in 1 hour
+});
+
+// Write with absolute expiration
+const expirationTime = Math.floor(Date.now() / 1000) + 86400; // 24 hours
+await env.MY_KV.put('token', tokenValue, {
+ expiration: expirationTime,
+});
+
+// Write with metadata
+await env.MY_KV.put('config', configData, {
+ metadata: {
+ updatedAt: Date.now(),
+ updatedBy: 'admin',
+ version: 2,
+ },
+});
+
+// Write with everything
+await env.MY_KV.put('key', 'value', {
+ expirationTtl: 600,
+ metadata: { source: 'api' },
+});
+```
+
+**Limits:**
+- **Key size**: Maximum 512 bytes
+- **Value size**: Maximum 25 MiB
+- **Metadata size**: Maximum 1024 bytes (JSON serialized)
+- **Write rate**: Maximum **1 write per second per key**
+- **Expiration minimum**: 60 seconds
+
+---
+
+## Delete Operations
+
+### `delete()` - Delete Key
+
+Delete a key-value pair.
+
+**Signature:**
+```typescript
+delete(key: string): Promise<void>
+```
+
+**Parameters:**
+- `key` (string, required) - Key to delete
+
+**Returns:**
+- `Promise<void>` - Always succeeds, even if key doesn't exist
+
+**Examples:**
+```typescript
+// Delete single key
+await env.MY_KV.delete('my-key');
+
+// Delete multiple keys
+const keys = ['key1', 'key2', 'key3'];
+await Promise.all(keys.map(key => env.MY_KV.delete(key)));
+```
+
+**Note:** For bulk delete of >10,000 keys, use the REST API.
+
+---
+
+## List Operations
+
+### `list()` - List Keys
+
+List keys in the namespace.
+
+**Signature:**
+```typescript
+list<Metadata>(options?: KVListOptions): Promise<KVListResult<Metadata>>
+```
+
+**Parameters:**
+```typescript
+interface KVListOptions {
+ prefix?: string; // Filter keys by prefix
+ limit?: number; // Max keys to return (default: 1000, max: 1000)
+ cursor?: string; // Pagination cursor
+}
+```
+
+**Returns:**
+```typescript
+interface KVListResult<Metadata> {
+ keys: {
+ name: string;
+ expiration?: number; // Seconds since epoch
+ metadata?: Metadata;
+ }[];
+ list_complete: boolean; // true if no more keys
+ cursor?: string; // Use for next page
+}
+```
+
+**Examples:**
+```typescript
+// List all keys (up to 1000)
+const result = await env.MY_KV.list();
+
+// List with prefix
+const users = await env.MY_KV.list({ prefix: 'user:' });
+
+// List with limit
+const recent = await env.MY_KV.list({ limit: 100 });
+
+// Pagination
+let cursor: string | undefined;
+do {
+ const result = await env.MY_KV.list({ cursor });
+
+ // Process keys
+ console.log(result.keys);
+
+ cursor = result.list_complete ? undefined : result.cursor;
+} while (cursor);
+```
+
+**Important:**
+- Keys are **always** sorted lexicographically (UTF-8)
+- **Always check `list_complete`**, not `keys.length === 0`
+- Empty `keys` array doesn't mean no more data (tombstones exist)
+- When paginating with `prefix`, pass `prefix` with each cursor request
+
+---
+
+## Type Definitions
+
+### KVGetOptions
+
+```typescript
+interface KVGetOptions<Type> {
+ type: Type; // "text" | "json" | "arrayBuffer" | "stream"
+ cacheTtl?: number; // Edge cache duration (minimum: 60 seconds)
+}
+```
+
+### KVPutOptions
+
+```typescript
+interface KVPutOptions {
+ expiration?: number; // Seconds since epoch
+ expirationTtl?: number; // Seconds from now (minimum: 60)
+ metadata?: any; // Max 1024 bytes serialized
+}
+```
+
+### KVGetWithMetadataResult
+
+```typescript
+interface KVGetWithMetadataResult<Value, Metadata> {
+ value: Value | null;
+ metadata: Metadata | null;
+}
+```
+
+### KVListOptions
+
+```typescript
+interface KVListOptions {
+ prefix?: string;
+ limit?: number; // Default: 1000, max: 1000
+ cursor?: string;
+}
+```
+
+### KVListResult
+
+```typescript
+interface KVListResult<Metadata = unknown> {
+ keys: {
+ name: string;
+ expiration?: number;
+ metadata?: Metadata;
+ }[];
+ list_complete: boolean;
+ cursor?: string;
+}
+```
+
+---
+
+## Limits
+
+| Feature | Limit |
+|---------|-------|
+| Key size | 512 bytes |
+| Value size | 25 MiB |
+| Metadata size | 1024 bytes (JSON) |
+| Writes per key per second | 1 |
+| Operations per Worker invocation | 1,000 |
+| List limit | 1,000 keys |
+| Minimum cacheTtl | 60 seconds |
+| Minimum expiration | 60 seconds |
+| Namespaces per account (Free) | 1,000 |
+| Namespaces per account (Paid) | 1,000 |
+| Storage per account (Free) | 1 GB |
+| Storage per account (Paid) | Unlimited |
+| Read operations per day (Free) | 100,000 |
+| Read operations per day (Paid) | Unlimited |
+| Write operations per day (Free) | 1,000 |
+| Write operations per day (Paid) | Unlimited |
+
+---
+
+## Consistency Model
+
+### Eventually Consistent
+
+- Writes are **immediately visible** in the same location
+- Writes take **up to 60 seconds** to propagate globally
+- Cached reads may return stale data during propagation
+
+### Implications
+
+```typescript
+// Tokyo datacenter
+await env.KV.put('counter', '1');
+const value1 = await env.KV.get('counter'); // "1" βœ…
+
+// London datacenter (within 60 seconds)
+const value2 = await env.KV.get('counter'); // Might be old value ⚠️
+
+// After 60+ seconds globally
+const value3 = await env.KV.get('counter'); // "1" βœ…
+```
+
+**For strong consistency, use [Durable Objects](https://developers.cloudflare.com/durable-objects/).**
+
+---
+
+## Error Handling
+
+### Common Errors
+
+1. **429 Too Many Requests**
+ - Cause: >1 write/second to same key
+ - Solution: Implement retry with exponential backoff
+
+2. **Value too large**
+ - Cause: Value >25 MiB
+ - Solution: Validate size before writing
+
+3. **Metadata too large**
+ - Cause: Metadata >1024 bytes serialized
+ - Solution: Validate JSON size before writing
+
+4. **Invalid cacheTtl**
+ - Cause: cacheTtl <60 seconds
+ - Solution: Use minimum 60 seconds
+
+5. **Operations limit exceeded**
+ - Cause: >1000 KV operations in Worker invocation
+ - Solution: Use bulk operations
+
+---
+
+## References
+
+- [Official KV Documentation](https://developers.cloudflare.com/kv/)
+- [KV API Reference](https://developers.cloudflare.com/kv/api/)
+- [KV Limits](https://developers.cloudflare.com/kv/platform/limits/)
+- [How KV Works](https://developers.cloudflare.com/kv/concepts/how-kv-works/)
diff --git a/skills/cloudflare-kv/templates/kv-basic-operations.ts b/skills/cloudflare-kv/templates/kv-basic-operations.ts
new file mode 100644
index 00000000..4ecdbf63
--- /dev/null
+++ b/skills/cloudflare-kv/templates/kv-basic-operations.ts
@@ -0,0 +1,538 @@
+/**
+ * Cloudflare Workers KV - Basic CRUD Operations
+ *
+ * This template demonstrates all basic KV operations:
+ * - Create (PUT)
+ * - Read (GET)
+ * - Update (PUT)
+ * - Delete (DELETE)
+ * - List keys
+ * - Metadata handling
+ * - TTL/Expiration
+ * - Error handling
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ MY_KV: KVNamespace;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// CREATE / UPDATE - Write key-value pairs
+// ============================================================================
+
+// Simple write
+app.put('/kv/:key', async (c) => {
+ const key = c.req.param('key');
+ const value = await c.req.text();
+
+ try {
+ await c.env.MY_KV.put(key, value);
+
+ return c.json({
+ success: true,
+ message: `Key "${key}" created/updated`,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Write with TTL expiration
+app.put('/kv/:key/ttl/:seconds', async (c) => {
+ const key = c.req.param('key');
+ const ttl = parseInt(c.req.param('seconds'), 10);
+ const value = await c.req.text();
+
+ // Validate TTL (minimum 60 seconds)
+ if (ttl < 60) {
+ return c.json(
+ {
+ success: false,
+ error: 'TTL must be at least 60 seconds',
+ },
+ 400
+ );
+ }
+
+ try {
+ await c.env.MY_KV.put(key, value, {
+ expirationTtl: ttl,
+ });
+
+ return c.json({
+ success: true,
+ message: `Key "${key}" will expire in ${ttl} seconds`,
+ expiresAt: new Date(Date.now() + ttl * 1000).toISOString(),
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Write with metadata
+app.put('/kv/:key/metadata', async (c) => {
+ const key = c.req.param('key');
+ const body = await c.req.json<{ value: string; metadata: any }>();
+
+ // Validate metadata size (max 1024 bytes serialized)
+ const metadataJson = JSON.stringify(body.metadata);
+ if (metadataJson.length > 1024) {
+ return c.json(
+ {
+ success: false,
+ error: `Metadata too large: ${metadataJson.length} bytes (max 1024)`,
+ },
+ 400
+ );
+ }
+
+ try {
+ await c.env.MY_KV.put(key, body.value, {
+ metadata: body.metadata,
+ });
+
+ return c.json({
+ success: true,
+ message: `Key "${key}" created with metadata`,
+ metadata: body.metadata,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Write JSON data
+app.post('/kv/json/:key', async (c) => {
+ const key = c.req.param('key');
+ const data = await c.req.json();
+
+ try {
+ await c.env.MY_KV.put(key, JSON.stringify(data));
+
+ return c.json({
+ success: true,
+ message: `JSON data stored at key "${key}"`,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// READ - Get key-value pairs
+// ============================================================================
+
+// Simple read (text)
+app.get('/kv/:key', async (c) => {
+ const key = c.req.param('key');
+
+ try {
+ const value = await c.env.MY_KV.get(key);
+
+ if (value === null) {
+ return c.json(
+ {
+ success: false,
+ error: `Key "${key}" not found`,
+ },
+ 404
+ );
+ }
+
+ return c.json({
+ success: true,
+ key,
+ value,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Read JSON data
+app.get('/kv/json/:key', async (c) => {
+ const key = c.req.param('key');
+
+ try {
+ const value = await c.env.MY_KV.get(key, { type: 'json' });
+
+ if (value === null) {
+ return c.json(
+ {
+ success: false,
+ error: `Key "${key}" not found`,
+ },
+ 404
+ );
+ }
+
+ return c.json({
+ success: true,
+ key,
+ value,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Read with metadata
+app.get('/kv/:key/metadata', async (c) => {
+ const key = c.req.param('key');
+
+ try {
+ const { value, metadata } = await c.env.MY_KV.getWithMetadata(key);
+
+ if (value === null) {
+ return c.json(
+ {
+ success: false,
+ error: `Key "${key}" not found`,
+ },
+ 404
+ );
+ }
+
+ return c.json({
+ success: true,
+ key,
+ value,
+ metadata,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Read with cache optimization
+app.get('/kv/:key/cached', async (c) => {
+ const key = c.req.param('key');
+ const cacheTtl = parseInt(c.req.query('cacheTtl') || '300', 10);
+
+ // Validate cacheTtl (minimum 60 seconds)
+ if (cacheTtl < 60) {
+ return c.json(
+ {
+ success: false,
+ error: 'cacheTtl must be at least 60 seconds',
+ },
+ 400
+ );
+ }
+
+ try {
+ const value = await c.env.MY_KV.get(key, {
+ type: 'text',
+ cacheTtl,
+ });
+
+ if (value === null) {
+ return c.json(
+ {
+ success: false,
+ error: `Key "${key}" not found`,
+ },
+ 404
+ );
+ }
+
+ return c.json({
+ success: true,
+ key,
+ value,
+ cached: true,
+ cacheTtl,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Bulk read (multiple keys)
+app.post('/kv/bulk/get', async (c) => {
+ const { keys } = await c.req.json<{ keys: string[] }>();
+
+ if (!Array.isArray(keys) || keys.length === 0) {
+ return c.json(
+ {
+ success: false,
+ error: 'keys must be a non-empty array',
+ },
+ 400
+ );
+ }
+
+ try {
+ // Bulk read counts as 1 operation!
+ const values = await c.env.MY_KV.get(keys);
+
+ // Convert Map to object
+ const result: Record<string, string | null> = {};
+ for (const [key, value] of values) {
+ result[key] = value;
+ }
+
+ return c.json({
+ success: true,
+ count: keys.length,
+ values: result,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// LIST - List keys with pagination
+// ============================================================================
+
+// List all keys (with pagination)
+app.get('/kv/list', async (c) => {
+ const prefix = c.req.query('prefix') || '';
+ const cursor = c.req.query('cursor');
+ const limit = parseInt(c.req.query('limit') || '1000', 10);
+
+ try {
+ const result = await c.env.MY_KV.list({
+ prefix,
+ limit,
+ cursor: cursor || undefined,
+ });
+
+ return c.json({
+ success: true,
+ keys: result.keys,
+ count: result.keys.length,
+ hasMore: !result.list_complete,
+ cursor: result.cursor,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// List all keys with prefix (fully paginated)
+app.get('/kv/list/all/:prefix', async (c) => {
+ const prefix = c.req.param('prefix');
+ let cursor: string | undefined;
+ const allKeys: any[] = [];
+
+ try {
+ // Paginate through all keys
+ do {
+ const result = await c.env.MY_KV.list({
+ prefix,
+ cursor,
+ });
+
+ allKeys.push(...result.keys);
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ prefix,
+ keys: allKeys,
+ totalCount: allKeys.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// DELETE - Delete key-value pairs
+// ============================================================================
+
+// Delete single key
+app.delete('/kv/:key', async (c) => {
+ const key = c.req.param('key');
+
+ try {
+ // Delete always succeeds, even if key doesn't exist
+ await c.env.MY_KV.delete(key);
+
+ return c.json({
+ success: true,
+ message: `Key "${key}" deleted`,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Delete multiple keys
+app.post('/kv/bulk/delete', async (c) => {
+ const { keys } = await c.req.json<{ keys: string[] }>();
+
+ if (!Array.isArray(keys) || keys.length === 0) {
+ return c.json(
+ {
+ success: false,
+ error: 'keys must be a non-empty array',
+ },
+ 400
+ );
+ }
+
+ try {
+ // Delete all keys in parallel
+ await Promise.all(keys.map((key) => c.env.MY_KV.delete(key)));
+
+ return c.json({
+ success: true,
+ message: `${keys.length} keys deleted`,
+ count: keys.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// UTILITY - Helper endpoints
+// ============================================================================
+
+// Check if key exists
+app.get('/kv/:key/exists', async (c) => {
+ const key = c.req.param('key');
+
+ try {
+ const value = await c.env.MY_KV.get(key);
+
+ return c.json({
+ exists: value !== null,
+ key,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Get namespace stats
+app.get('/kv/stats', async (c) => {
+ try {
+ const result = await c.env.MY_KV.list();
+ let totalKeys = result.keys.length;
+ let cursor = result.cursor;
+
+ // Count all keys (with pagination)
+ while (!result.list_complete && cursor) {
+ const nextResult = await c.env.MY_KV.list({ cursor });
+ totalKeys += nextResult.keys.length;
+ cursor = nextResult.cursor;
+ }
+
+ return c.json({
+ success: true,
+ totalKeys,
+ sample: result.keys.slice(0, 10), // First 10 keys
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Health check
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-kv/templates/kv-caching-pattern.ts b/skills/cloudflare-kv/templates/kv-caching-pattern.ts
new file mode 100644
index 00000000..0ae507df
--- /dev/null
+++ b/skills/cloudflare-kv/templates/kv-caching-pattern.ts
@@ -0,0 +1,518 @@
+/**
+ * Cloudflare Workers KV - Caching Pattern
+ *
+ * This template demonstrates optimal caching patterns with KV:
+ * - Cache-aside pattern (read-through cache)
+ * - Write-through cache
+ * - CacheTtl optimization for edge caching
+ * - Stale-while-revalidate pattern
+ * - Cache invalidation
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ CACHE: KVNamespace;
+ DB: D1Database; // Example: database for cache misses
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Cache-Aside Pattern (Read-Through Cache)
+// ============================================================================
+
+/**
+ * Generic cache-aside helper
+ *
+ * 1. Try to read from cache
+ * 2. On miss, fetch from source
+ * 3. Store in cache
+ * 4. Return data
+ */
+async function getCached<T>(
+ kv: KVNamespace,
+ cacheKey: string,
+ fetchFn: () => Promise<T>,
+ options: {
+ ttl?: number; // KV expiration (default: 3600)
+ cacheTtl?: number; // Edge cache TTL (default: 300)
+ } = {}
+): Promise<T> {
+ const ttl = options.ttl ?? 3600; // 1 hour default
+ const cacheTtl = options.cacheTtl ?? 300; // 5 minutes default
+
+ // Try cache first (with edge caching)
+ const cached = await kv.get<T>(cacheKey, {
+ type: 'json',
+ cacheTtl: Math.max(cacheTtl, 60), // Minimum 60 seconds
+ });
+
+ if (cached !== null) {
+ return cached;
+ }
+
+ // Cache miss - fetch from source
+ const data = await fetchFn();
+
+ // Store in cache (fire-and-forget)
+ await kv.put(cacheKey, JSON.stringify(data), {
+ expirationTtl: Math.max(ttl, 60), // Minimum 60 seconds
+ });
+
+ return data;
+}
+
+// Example: Cache API response
+app.get('/api/user/:id', async (c) => {
+ const userId = c.req.param('id');
+ const cacheKey = `user:${userId}`;
+
+ try {
+ const user = await getCached(
+ c.env.CACHE,
+ cacheKey,
+ async () => {
+ // Simulate database fetch
+ const result = await c.env.DB.prepare(
+ 'SELECT * FROM users WHERE id = ?'
+ )
+ .bind(userId)
+ .first();
+
+ if (!result) {
+ throw new Error('User not found');
+ }
+
+ return result;
+ },
+ {
+ ttl: 3600, // Cache in KV for 1 hour
+ cacheTtl: 300, // Cache at edge for 5 minutes
+ }
+ );
+
+ return c.json({
+ success: true,
+ user,
+ cached: true,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Write-Through Cache Pattern
+// ============================================================================
+
+/**
+ * Write-through cache: Update cache when data changes
+ */
+app.put('/api/user/:id', async (c) => {
+ const userId = c.req.param('id');
+ const userData = await c.req.json();
+ const cacheKey = `user:${userId}`;
+
+ try {
+ // Update database
+ await c.env.DB.prepare(
+ 'UPDATE users SET name = ?, email = ? WHERE id = ?'
+ )
+ .bind(userData.name, userData.email, userId)
+ .run();
+
+ // Update cache immediately
+ await c.env.CACHE.put(cacheKey, JSON.stringify(userData), {
+ expirationTtl: 3600,
+ });
+
+ return c.json({
+ success: true,
+ message: 'User updated and cache refreshed',
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Cache Invalidation
+// ============================================================================
+
+/**
+ * Invalidate cache when data changes
+ */
+app.delete('/api/user/:id', async (c) => {
+ const userId = c.req.param('id');
+ const cacheKey = `user:${userId}`;
+
+ try {
+ // Delete from database
+ await c.env.DB.prepare('DELETE FROM users WHERE id = ?').bind(userId).run();
+
+ // Invalidate cache
+ await c.env.CACHE.delete(cacheKey);
+
+ return c.json({
+ success: true,
+ message: 'User deleted and cache invalidated',
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Invalidate multiple cache keys
+app.post('/api/cache/invalidate', async (c) => {
+ const { keys } = await c.req.json<{ keys: string[] }>();
+
+ try {
+ // Delete all cache keys in parallel
+ await Promise.all(keys.map((key) => c.env.CACHE.delete(key)));
+
+ return c.json({
+ success: true,
+ message: `${keys.length} cache keys invalidated`,
+ count: keys.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Invalidate by prefix (requires list + delete)
+app.post('/api/cache/invalidate/prefix', async (c) => {
+ const { prefix } = await c.req.json<{ prefix: string }>();
+
+ try {
+ let cursor: string | undefined;
+ let deletedCount = 0;
+
+ // List all keys with prefix and delete them
+ do {
+ const result = await c.env.CACHE.list({ prefix, cursor });
+
+ // Delete batch in parallel
+ await Promise.all(result.keys.map((key) => c.env.CACHE.delete(key.name)));
+
+ deletedCount += result.keys.length;
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ message: `Cache invalidated for prefix "${prefix}"`,
+ deletedCount,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Stale-While-Revalidate Pattern
+// ============================================================================
+
+/**
+ * Return cached data immediately, refresh in background
+ */
+async function staleWhileRevalidate<T>(
+ kv: KVNamespace,
+ cacheKey: string,
+ fetchFn: () => Promise<T>,
+ ctx: ExecutionContext,
+ options: {
+ ttl?: number;
+ staleThreshold?: number; // Refresh if older than this
+ } = {}
+): Promise<T> {
+ const ttl = options.ttl ?? 3600;
+ const staleThreshold = options.staleThreshold ?? 300; // 5 minutes
+
+ // Get cached value with metadata
+ const { value, metadata } = await kv.getWithMetadata<
+ T,
+ { timestamp: number }
+ >(cacheKey, { type: 'json' });
+
+ // If cached and not too stale, return immediately
+ if (value !== null && metadata) {
+ const age = Date.now() - metadata.timestamp;
+
+ // If stale, refresh in background
+ if (age > staleThreshold * 1000) {
+ ctx.waitUntil(
+ (async () => {
+ try {
+ const fresh = await fetchFn();
+ await kv.put(cacheKey, JSON.stringify(fresh), {
+ expirationTtl: ttl,
+ metadata: { timestamp: Date.now() },
+ });
+ } catch (error) {
+ console.error('Background refresh failed:', error);
+ }
+ })()
+ );
+ }
+
+ return value;
+ }
+
+ // Cache miss - fetch and store
+ const data = await fetchFn();
+ await kv.put(cacheKey, JSON.stringify(data), {
+ expirationTtl: ttl,
+ metadata: { timestamp: Date.now() },
+ });
+
+ return data;
+}
+
+// Example usage
+app.get('/api/stats', async (c) => {
+ try {
+ const stats = await staleWhileRevalidate(
+ c.env.CACHE,
+ 'global:stats',
+ async () => {
+ // Expensive computation
+ const result = await c.env.DB.prepare(
+ 'SELECT COUNT(*) as total FROM users'
+ ).first();
+ return result;
+ },
+ c.executionCtx,
+ {
+ ttl: 3600, // Cache for 1 hour
+ staleThreshold: 300, // Refresh if older than 5 minutes
+ }
+ );
+
+ return c.json({
+ success: true,
+ stats,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Multi-Layer Cache (KV + Memory)
+// ============================================================================
+
+/**
+ * Two-tier cache: In-memory cache + KV cache
+ * Useful for frequently accessed data within same Worker instance
+ */
+const memoryCache = new Map<string, { value: any; expires: number }>();
+
+async function getMultiLayerCache<T>(
+ kv: KVNamespace,
+ cacheKey: string,
+ fetchFn: () => Promise<T>,
+ options: {
+ ttl?: number;
+ memoryTtl?: number; // In-memory cache duration
+ } = {}
+): Promise<T> {
+ const ttl = options.ttl ?? 3600;
+ const memoryTtl = (options.memoryTtl ?? 60) * 1000; // Convert to ms
+
+ // Check memory cache first (fastest)
+ const memoryCached = memoryCache.get(cacheKey);
+ if (memoryCached && memoryCached.expires > Date.now()) {
+ return memoryCached.value;
+ }
+
+ // Check KV cache (fast, global)
+ const kvCached = await kv.get<T>(cacheKey, {
+ type: 'json',
+ cacheTtl: 300,
+ });
+
+ if (kvCached !== null) {
+ // Store in memory cache
+ memoryCache.set(cacheKey, {
+ value: kvCached,
+ expires: Date.now() + memoryTtl,
+ });
+ return kvCached;
+ }
+
+ // Cache miss - fetch from source
+ const data = await fetchFn();
+
+ // Store in both caches
+ memoryCache.set(cacheKey, {
+ value: data,
+ expires: Date.now() + memoryTtl,
+ });
+
+ await kv.put(cacheKey, JSON.stringify(data), {
+ expirationTtl: ttl,
+ });
+
+ return data;
+}
+
+// Example usage
+app.get('/api/config', async (c) => {
+ try {
+ const config = await getMultiLayerCache(
+ c.env.CACHE,
+ 'app:config',
+ async () => {
+ // Fetch from database or API
+ return {
+ theme: 'dark',
+ features: ['feature1', 'feature2'],
+ version: '1.0.0',
+ };
+ },
+ {
+ ttl: 3600, // KV cache: 1 hour
+ memoryTtl: 60, // Memory cache: 1 minute
+ }
+ );
+
+ return c.json({
+ success: true,
+ config,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Cache Warming
+// ============================================================================
+
+/**
+ * Pre-populate cache with frequently accessed data
+ */
+app.post('/api/cache/warm', async (c) => {
+ try {
+ // Example: Warm cache with top 100 users
+ const topUsers = await c.env.DB.prepare(
+ 'SELECT * FROM users ORDER BY activity DESC LIMIT 100'
+ ).all();
+
+ // Store each user in cache
+ const promises = topUsers.results.map((user: any) =>
+ c.env.CACHE.put(`user:${user.id}`, JSON.stringify(user), {
+ expirationTtl: 3600,
+ })
+ );
+
+ await Promise.all(promises);
+
+ return c.json({
+ success: true,
+ message: `Warmed cache with ${topUsers.results.length} users`,
+ count: topUsers.results.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Cache Statistics
+// ============================================================================
+
+/**
+ * Track cache hit/miss rates
+ */
+let cacheStats = {
+ hits: 0,
+ misses: 0,
+ errors: 0,
+};
+
+app.get('/api/cache/stats', (c) => {
+ const total = cacheStats.hits + cacheStats.misses;
+ const hitRate = total > 0 ? (cacheStats.hits / total) * 100 : 0;
+
+ return c.json({
+ success: true,
+ stats: {
+ hits: cacheStats.hits,
+ misses: cacheStats.misses,
+ errors: cacheStats.errors,
+ total,
+ hitRate: `${hitRate.toFixed(2)}%`,
+ },
+ });
+});
+
+// Reset stats
+app.post('/api/cache/stats/reset', (c) => {
+ cacheStats = { hits: 0, misses: 0, errors: 0 };
+
+ return c.json({
+ success: true,
+ message: 'Cache stats reset',
+ });
+});
+
+// Health check
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-kv/templates/kv-list-pagination.ts b/skills/cloudflare-kv/templates/kv-list-pagination.ts
new file mode 100644
index 00000000..446f45c0
--- /dev/null
+++ b/skills/cloudflare-kv/templates/kv-list-pagination.ts
@@ -0,0 +1,551 @@
+/**
+ * Cloudflare Workers KV - List & Pagination Patterns
+ *
+ * This template demonstrates:
+ * - Basic listing with cursor pagination
+ * - Prefix filtering
+ * - Async iterator pattern
+ * - Batch processing
+ * - Key search and filtering
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ MY_KV: KVNamespace;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Basic Pagination
+// ============================================================================
+
+// List keys with cursor pagination
+app.get('/kv/list', async (c) => {
+ const prefix = c.req.query('prefix') || '';
+ const cursor = c.req.query('cursor');
+ const limit = parseInt(c.req.query('limit') || '100', 10);
+
+ try {
+ const result = await c.env.MY_KV.list({
+ prefix,
+ limit: Math.min(limit, 1000), // Max 1000
+ cursor: cursor || undefined,
+ });
+
+ return c.json({
+ success: true,
+ keys: result.keys.map((k) => ({
+ name: k.name,
+ expiration: k.expiration,
+ metadata: k.metadata,
+ })),
+ count: result.keys.length,
+ hasMore: !result.list_complete,
+ nextCursor: result.cursor,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Async Iterator Pattern
+// ============================================================================
+
+/**
+ * Async generator for paginating through all keys
+ */
+async function* paginateKeys(
+ kv: KVNamespace,
+ options: {
+ prefix?: string;
+ limit?: number;
+ } = {}
+) {
+ let cursor: string | undefined;
+
+ do {
+ const result = await kv.list({
+ prefix: options.prefix,
+ limit: options.limit || 1000,
+ cursor,
+ });
+
+ yield result.keys;
+
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+}
+
+// Get all keys (fully paginated)
+app.get('/kv/all', async (c) => {
+ const prefix = c.req.query('prefix') || '';
+
+ try {
+ const allKeys: any[] = [];
+
+ // Use async iterator to get all keys
+ for await (const batch of paginateKeys(c.env.MY_KV, { prefix })) {
+ allKeys.push(...batch);
+ }
+
+ return c.json({
+ success: true,
+ keys: allKeys.map((k) => k.name),
+ totalCount: allKeys.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Prefix Filtering
+// ============================================================================
+
+// List keys by namespace prefix
+app.get('/kv/namespace/:namespace', async (c) => {
+ const namespace = c.req.param('namespace');
+ const cursor = c.req.query('cursor');
+
+ try {
+ const result = await c.env.MY_KV.list({
+ prefix: `${namespace}:`, // e.g., "user:", "session:", "cache:"
+ cursor: cursor || undefined,
+ });
+
+ return c.json({
+ success: true,
+ namespace,
+ keys: result.keys,
+ count: result.keys.length,
+ hasMore: !result.list_complete,
+ nextCursor: result.cursor,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Count keys by prefix
+app.get('/kv/count/:prefix', async (c) => {
+ const prefix = c.req.param('prefix');
+
+ try {
+ let count = 0;
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({
+ prefix,
+ cursor,
+ });
+
+ count += result.keys.length;
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ prefix,
+ count,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Batch Processing
+// ============================================================================
+
+/**
+ * Process keys in batches
+ */
+async function processBatches<T>(
+ kv: KVNamespace,
+ options: {
+ prefix?: string;
+ batchSize?: number;
+ },
+ processor: (keys: any[]) => Promise<T[]>
+): Promise<T[]> {
+ const results: T[] = [];
+ let cursor: string | undefined;
+
+ do {
+ const result = await kv.list({
+ prefix: options.prefix,
+ limit: options.batchSize || 100,
+ cursor,
+ });
+
+ // Process this batch
+ const batchResults = await processor(result.keys);
+ results.push(...batchResults);
+
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return results;
+}
+
+// Example: Export all keys with values
+app.get('/kv/export', async (c) => {
+ const prefix = c.req.query('prefix') || '';
+
+ try {
+ const exported = await processBatches(
+ c.env.MY_KV,
+ { prefix, batchSize: 100 },
+ async (keys) => {
+ // Get values for all keys in batch (bulk read)
+ const keyNames = keys.map((k) => k.name);
+ const values = await c.env.MY_KV.get(keyNames);
+
+ // Combine keys with values
+ return keys.map((key) => ({
+ key: key.name,
+ value: values.get(key.name),
+ metadata: key.metadata,
+ expiration: key.expiration,
+ }));
+ }
+ );
+
+ return c.json({
+ success: true,
+ data: exported,
+ count: exported.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Search & Filtering
+// ============================================================================
+
+// Search keys by pattern (client-side filtering)
+app.get('/kv/search', async (c) => {
+ const query = c.req.query('q') || '';
+ const prefix = c.req.query('prefix') || '';
+
+ if (!query) {
+ return c.json(
+ {
+ success: false,
+ error: 'Query parameter "q" is required',
+ },
+ 400
+ );
+ }
+
+ try {
+ const matches: any[] = [];
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({
+ prefix,
+ cursor,
+ });
+
+ // Filter keys that match the search query
+ const filteredKeys = result.keys.filter((key) =>
+ key.name.toLowerCase().includes(query.toLowerCase())
+ );
+
+ matches.push(...filteredKeys);
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ query,
+ matches: matches.map((k) => k.name),
+ count: matches.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Filter by metadata
+app.get('/kv/filter/metadata', async (c) => {
+ const metadataKey = c.req.query('key');
+ const metadataValue = c.req.query('value');
+
+ if (!metadataKey) {
+ return c.json(
+ {
+ success: false,
+ error: 'Query parameter "key" is required',
+ },
+ 400
+ );
+ }
+
+ try {
+ const matches: any[] = [];
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({ cursor });
+
+ // Filter by metadata
+ const filteredKeys = result.keys.filter((key) => {
+ if (!key.metadata) return false;
+
+ return metadataValue
+ ? key.metadata[metadataKey] === metadataValue
+ : metadataKey in key.metadata;
+ });
+
+ matches.push(...filteredKeys);
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ matches: matches.map((k) => ({
+ name: k.name,
+ metadata: k.metadata,
+ })),
+ count: matches.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Cleanup & Maintenance
+// ============================================================================
+
+// Delete expired keys (manual cleanup)
+app.post('/kv/cleanup/expired', async (c) => {
+ try {
+ let deletedCount = 0;
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({ cursor });
+
+ // Filter keys that have expired
+ const now = Math.floor(Date.now() / 1000);
+ const expiredKeys = result.keys
+ .filter((key) => key.expiration && key.expiration < now)
+ .map((key) => key.name);
+
+ // Delete expired keys
+ await Promise.all(expiredKeys.map((key) => c.env.MY_KV.delete(key)));
+
+ deletedCount += expiredKeys.length;
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ message: `Deleted ${deletedCount} expired keys`,
+ deletedCount,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Delete all keys with prefix (DANGEROUS!)
+app.post('/kv/delete/prefix', async (c) => {
+ const { prefix } = await c.req.json<{ prefix: string }>();
+
+ if (!prefix) {
+ return c.json(
+ {
+ success: false,
+ error: 'Prefix is required',
+ },
+ 400
+ );
+ }
+
+ try {
+ let deletedCount = 0;
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({ prefix, cursor });
+
+ // Delete batch
+ await Promise.all(result.keys.map((key) => c.env.MY_KV.delete(key.name)));
+
+ deletedCount += result.keys.length;
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ message: `Deleted ${deletedCount} keys with prefix "${prefix}"`,
+ deletedCount,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Namespace Statistics
+// ============================================================================
+
+// Get detailed namespace stats
+app.get('/kv/stats/detailed', async (c) => {
+ try {
+ let totalKeys = 0;
+ let withMetadata = 0;
+ let withExpiration = 0;
+ const prefixes = new Map<string, number>();
+
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({ cursor });
+
+ totalKeys += result.keys.length;
+
+ // Analyze keys
+ for (const key of result.keys) {
+ if (key.metadata) withMetadata++;
+ if (key.expiration) withExpiration++;
+
+ // Extract prefix (before first ":")
+ const prefix = key.name.split(':')[0];
+ prefixes.set(prefix, (prefixes.get(prefix) || 0) + 1);
+ }
+
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ stats: {
+ totalKeys,
+ withMetadata,
+ withExpiration,
+ prefixCounts: Object.fromEntries(prefixes),
+ },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Group keys by prefix
+app.get('/kv/groups', async (c) => {
+ try {
+ const groups = new Map<string, string[]>();
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({ cursor });
+
+ for (const key of result.keys) {
+ const prefix = key.name.split(':')[0];
+
+ if (!groups.has(prefix)) {
+ groups.set(prefix, []);
+ }
+
+ groups.get(prefix)!.push(key.name);
+ }
+
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ groups: Object.fromEntries(groups),
+ groupCount: groups.size,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Health check
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-kv/templates/kv-metadata-pattern.ts b/skills/cloudflare-kv/templates/kv-metadata-pattern.ts
new file mode 100644
index 00000000..958d2f11
--- /dev/null
+++ b/skills/cloudflare-kv/templates/kv-metadata-pattern.ts
@@ -0,0 +1,568 @@
+/**
+ * Cloudflare Workers KV - Metadata Patterns
+ *
+ * This template demonstrates:
+ * - Storing data in metadata for list() efficiency
+ * - Metadata-based filtering
+ * - Versioning with metadata
+ * - Audit trails
+ * - Feature flags with metadata
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ MY_KV: KVNamespace;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Metadata Optimization Pattern
+// ============================================================================
+
+/**
+ * Store small values in metadata to avoid separate get() calls
+ * Maximum metadata size: 1024 bytes (JSON serialized)
+ */
+
+// ❌ BAD: Requires 2 operations per key
+async function getStatusBad(kv: KVNamespace, userId: string) {
+ const status = await kv.get(`user:${userId}:status`);
+ const lastSeen = await kv.get(`user:${userId}:lastseen`);
+ return { status, lastSeen };
+}
+
+// βœ… GOOD: Single list() operation gets metadata for all users
+async function getStatusGood(kv: KVNamespace) {
+ const users = await kv.list({ prefix: 'user:' });
+
+ return users.keys.map((key) => ({
+ userId: key.name.split(':')[1],
+ status: key.metadata?.status,
+ lastSeen: key.metadata?.lastSeen,
+ }));
+}
+
+// Example: User status with metadata
+app.post('/users/:id/status', async (c) => {
+ const userId = c.req.param('id');
+ const { status } = await c.req.json<{ status: string }>();
+
+ try {
+ // Store empty value, all data in metadata
+ await c.env.MY_KV.put(`user:${userId}`, '', {
+ metadata: {
+ status,
+ lastSeen: Date.now(),
+ plan: 'free',
+ },
+ });
+
+ return c.json({
+ success: true,
+ message: 'Status updated',
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// List all users with status (no additional get() calls needed!)
+app.get('/users/status', async (c) => {
+ try {
+ const users = await c.env.MY_KV.list({ prefix: 'user:' });
+
+ const statuses = users.keys.map((key) => ({
+ userId: key.name.split(':')[1],
+ status: key.metadata?.status || 'unknown',
+ lastSeen: key.metadata?.lastSeen,
+ plan: key.metadata?.plan,
+ }));
+
+ return c.json({
+ success: true,
+ users: statuses,
+ count: statuses.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Versioning with Metadata
+// ============================================================================
+
+interface VersionedData {
+ content: any;
+ version: number;
+ updatedAt: number;
+ updatedBy: string;
+}
+
+// Write with versioning
+app.put('/config/:key', async (c) => {
+ const key = c.req.param('key');
+ const content = await c.req.json();
+ const updatedBy = c.req.header('X-User-ID') || 'system';
+
+ try {
+ // Get current version
+ const existing = await c.env.MY_KV.getWithMetadata<
+ VersionedData,
+ { version: number }
+ >(`config:${key}`, { type: 'json' });
+
+ const currentVersion = existing.metadata?.version || 0;
+ const newVersion = currentVersion + 1;
+
+ // Store new version
+ const data: VersionedData = {
+ content,
+ version: newVersion,
+ updatedAt: Date.now(),
+ updatedBy,
+ };
+
+ await c.env.MY_KV.put(`config:${key}`, JSON.stringify(data), {
+ metadata: {
+ version: newVersion,
+ updatedAt: data.updatedAt,
+ updatedBy,
+ },
+ });
+
+ // Store version history (optional)
+ await c.env.MY_KV.put(
+ `config:${key}:v${newVersion}`,
+ JSON.stringify(data),
+ {
+ expirationTtl: 86400 * 30, // Keep versions for 30 days
+ }
+ );
+
+ return c.json({
+ success: true,
+ version: newVersion,
+ previousVersion: currentVersion,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Get config with version info
+app.get('/config/:key', async (c) => {
+ const key = c.req.param('key');
+
+ try {
+ const { value, metadata } = await c.env.MY_KV.getWithMetadata<
+ VersionedData,
+ { version: number; updatedAt: number; updatedBy: string }
+ >(`config:${key}`, { type: 'json' });
+
+ if (!value) {
+ return c.json(
+ {
+ success: false,
+ error: 'Config not found',
+ },
+ 404
+ );
+ }
+
+ return c.json({
+ success: true,
+ data: value,
+ metadata,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Get specific version
+app.get('/config/:key/version/:version', async (c) => {
+ const key = c.req.param('key');
+ const version = c.req.param('version');
+
+ try {
+ const data = await c.env.MY_KV.get<VersionedData>(
+ `config:${key}:v${version}`,
+ { type: 'json' }
+ );
+
+ if (!data) {
+ return c.json(
+ {
+ success: false,
+ error: `Version ${version} not found`,
+ },
+ 404
+ );
+ }
+
+ return c.json({
+ success: true,
+ data,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Audit Trail with Metadata
+// ============================================================================
+
+interface AuditMetadata {
+ createdBy: string;
+ createdAt: number;
+ updatedBy: string;
+ updatedAt: number;
+ accessCount: number;
+}
+
+// Write with audit trail
+app.post('/data/:key', async (c) => {
+ const key = c.req.param('key');
+ const value = await c.req.text();
+ const userId = c.req.header('X-User-ID') || 'anonymous';
+
+ try {
+ // Check if key exists
+ const existing = await c.env.MY_KV.getWithMetadata<string, AuditMetadata>(
+ key
+ );
+
+ const metadata: AuditMetadata = existing.metadata
+ ? {
+ ...existing.metadata,
+ updatedBy: userId,
+ updatedAt: Date.now(),
+ }
+ : {
+ createdBy: userId,
+ createdAt: Date.now(),
+ updatedBy: userId,
+ updatedAt: Date.now(),
+ accessCount: 0,
+ };
+
+ await c.env.MY_KV.put(key, value, { metadata });
+
+ return c.json({
+ success: true,
+ audit: metadata,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Read with access tracking
+app.get('/data/:key', async (c) => {
+ const key = c.req.param('key');
+
+ try {
+ const { value, metadata } = await c.env.MY_KV.getWithMetadata<
+ string,
+ AuditMetadata
+ >(key);
+
+ if (!value) {
+ return c.json(
+ {
+ success: false,
+ error: 'Key not found',
+ },
+ 404
+ );
+ }
+
+ // Increment access count (fire-and-forget)
+ if (metadata) {
+ c.executionCtx.waitUntil(
+ c.env.MY_KV.put(key, value, {
+ metadata: {
+ ...metadata,
+ accessCount: metadata.accessCount + 1,
+ },
+ })
+ );
+ }
+
+ return c.json({
+ success: true,
+ value,
+ audit: metadata,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Feature Flags with Metadata
+// ============================================================================
+
+interface FeatureFlag {
+ enabled: boolean;
+ rolloutPercentage: number;
+ targetUsers?: string[];
+ metadata: {
+ createdAt: number;
+ updatedAt: number;
+ description: string;
+ };
+}
+
+// Create feature flag
+app.post('/flags/:name', async (c) => {
+ const name = c.req.param('name');
+ const flag = await c.req.json<FeatureFlag>();
+
+ try {
+ await c.env.MY_KV.put(`flag:${name}`, JSON.stringify(flag), {
+ metadata: {
+ enabled: flag.enabled,
+ rolloutPercentage: flag.rolloutPercentage,
+ updatedAt: Date.now(),
+ },
+ });
+
+ return c.json({
+ success: true,
+ message: `Feature flag "${name}" created`,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// List all feature flags (metadata only)
+app.get('/flags', async (c) => {
+ try {
+ const flags = await c.env.MY_KV.list({ prefix: 'flag:' });
+
+ const flagList = flags.keys.map((key) => ({
+ name: key.name.replace('flag:', ''),
+ enabled: key.metadata?.enabled || false,
+ rolloutPercentage: key.metadata?.rolloutPercentage || 0,
+ updatedAt: key.metadata?.updatedAt,
+ }));
+
+ return c.json({
+ success: true,
+ flags: flagList,
+ count: flagList.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Check feature flag for user
+app.get('/flags/:name/check/:userId', async (c) => {
+ const name = c.req.param('name');
+ const userId = c.req.param('userId');
+
+ try {
+ const flag = await c.env.MY_KV.get<FeatureFlag>(`flag:${name}`, {
+ type: 'json',
+ });
+
+ if (!flag) {
+ return c.json(
+ {
+ success: false,
+ error: 'Feature flag not found',
+ },
+ 404
+ );
+ }
+
+ // Check if enabled
+ if (!flag.enabled) {
+ return c.json({ enabled: false, reason: 'Flag disabled globally' });
+ }
+
+ // Check target users
+ if (flag.targetUsers && flag.targetUsers.length > 0) {
+ const enabled = flag.targetUsers.includes(userId);
+ return c.json({
+ enabled,
+ reason: enabled ? 'User in target list' : 'User not in target list',
+ });
+ }
+
+ // Check rollout percentage
+ const userHash =
+ parseInt(userId.split('').reduce((a, b) => a + b.charCodeAt(0), 0).toString()) %
+ 100;
+ const enabled = userHash < flag.rolloutPercentage;
+
+ return c.json({
+ enabled,
+ reason: enabled
+ ? `User in ${flag.rolloutPercentage}% rollout`
+ : `User not in ${flag.rolloutPercentage}% rollout`,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Metadata Size Validation
+// ============================================================================
+
+// Validate metadata size before writing
+app.post('/validate/metadata', async (c) => {
+ const { metadata } = await c.req.json<{ metadata: any }>();
+
+ const serialized = JSON.stringify(metadata);
+ const size = new TextEncoder().encode(serialized).length;
+
+ if (size > 1024) {
+ return c.json({
+ valid: false,
+ size,
+ maxSize: 1024,
+ error: `Metadata too large: ${size} bytes (max 1024)`,
+ });
+ }
+
+ return c.json({
+ valid: true,
+ size,
+ maxSize: 1024,
+ });
+});
+
+// ============================================================================
+// Metadata Migration
+// ============================================================================
+
+// Migrate existing keys to add metadata
+app.post('/migrate/add-metadata', async (c) => {
+ const { prefix, metadata } = await c.req.json<{
+ prefix: string;
+ metadata: any;
+ }>();
+
+ try {
+ let migratedCount = 0;
+ let cursor: string | undefined;
+
+ do {
+ const result = await c.env.MY_KV.list({ prefix, cursor });
+
+ // Migrate batch
+ for (const key of result.keys) {
+ // Get existing value
+ const value = await c.env.MY_KV.get(key.name);
+
+ if (value !== null) {
+ // Re-write with metadata
+ await c.env.MY_KV.put(key.name, value, {
+ metadata: {
+ ...key.metadata,
+ ...metadata,
+ migratedAt: Date.now(),
+ },
+ });
+
+ migratedCount++;
+ }
+ }
+
+ cursor = result.list_complete ? undefined : result.cursor;
+ } while (cursor);
+
+ return c.json({
+ success: true,
+ message: `Migrated ${migratedCount} keys`,
+ migratedCount,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// Health check
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-kv/templates/wrangler-kv-config.jsonc b/skills/cloudflare-kv/templates/wrangler-kv-config.jsonc
new file mode 100644
index 00000000..ad5d3804
--- /dev/null
+++ b/skills/cloudflare-kv/templates/wrangler-kv-config.jsonc
@@ -0,0 +1,56 @@
+{
+ "$schema": "node_modules/wrangler/config-schema.json",
+ "name": "my-worker",
+ "main": "src/index.ts",
+ "compatibility_date": "2025-10-11",
+ "observability": {
+ "enabled": true
+ },
+
+ // KV Namespace Bindings
+ "kv_namespaces": [
+ {
+ // The binding name - accessible as env.CACHE in your Worker
+ "binding": "CACHE",
+
+ // Production namespace ID (from: wrangler kv namespace create CACHE)
+ "id": "<YOUR_PRODUCTION_NAMESPACE_ID>",
+
+ // Preview/local namespace ID (from: wrangler kv namespace create CACHE --preview)
+ // This is optional but recommended for local development
+ "preview_id": "<YOUR_PREVIEW_NAMESPACE_ID>"
+ },
+
+ // Multiple namespaces example
+ {
+ "binding": "CONFIG",
+ "id": "<CONFIG_PRODUCTION_ID>",
+ "preview_id": "<CONFIG_PREVIEW_ID>"
+ },
+
+ {
+ "binding": "SESSIONS",
+ "id": "<SESSIONS_PRODUCTION_ID>",
+ "preview_id": "<SESSIONS_PREVIEW_ID>"
+ }
+ ]
+
+ // IMPORTANT NOTES:
+ //
+ // 1. Create namespaces first:
+ // npx wrangler kv namespace create CACHE
+ // npx wrangler kv namespace create CACHE --preview
+ //
+ // 2. Copy the IDs from the command output to this file
+ //
+ // 3. NEVER commit real namespace IDs to public repos
+ // Use environment variables for sensitive namespaces:
+ // "id": "${KV_CACHE_ID}"
+ //
+ // 4. preview_id is optional but recommended for local development
+ // It creates a separate namespace for testing
+ //
+ // 5. Binding names must be valid JavaScript identifiers
+ // Good: CACHE, MY_KV, UserData
+ // Bad: my-kv, user.data, 123kv
+}
diff --git a/skills/cloudflare-queues/README.md b/skills/cloudflare-queues/README.md
new file mode 100644
index 00000000..14c2c3fc
--- /dev/null
+++ b/skills/cloudflare-queues/README.md
@@ -0,0 +1,249 @@
+# Cloudflare Queues
+
+Complete knowledge domain for Cloudflare Queues - flexible message queue for asynchronous processing and background tasks on Workers.
+
+---
+
+## Auto-Trigger Keywords
+
+### Primary Keywords
+- cloudflare queues
+- queues workers
+- message queue
+- queue bindings
+- async processing
+- background jobs
+- queue consumer
+- queue producer
+- workers queue
+- message broker
+
+### Secondary Keywords
+- batch processing
+- send queue
+- sendBatch
+- queue handler
+- message retry
+- queue ack
+- acknowledge message
+- dead letter queue
+- dlq
+- queue delay
+- delay message
+- consumer concurrency
+- queue backlog
+- wrangler queues
+
+### Error-Based Keywords
+- queue timeout
+- batch retry
+- message lost
+- queue throughput exceeded
+- consumer not scaling
+- queue storage limit
+- Too Many Requests queue
+- message retention exceeded
+- visibility timeout
+- max retries reached
+- queue delivery failed
+- consumer error
+
+### Framework Integration Keywords
+- hono queues
+- queues hono
+- cloudflare workers queues
+- wrangler queue
+- queue api workers
+
+---
+
+## What This Skill Does
+
+This skill provides complete Cloudflare Queues knowledge including:
+
+- βœ… **Queue Creation** - Create, configure, and manage queues with wrangler
+- βœ… **Producer Patterns** - send(), sendBatch() with delays
+- βœ… **Consumer Patterns** - Basic, explicit ack, DLQ, retry strategies
+- βœ… **Batching Configuration** - max_batch_size, max_batch_timeout
+- βœ… **Retry Strategies** - Implicit, explicit, with exponential backoff
+- βœ… **Dead Letter Queues** - Handle permanently failed messages
+- βœ… **Explicit Acknowledgement** - ack(), retry(), ackAll(), retryAll()
+- βœ… **Message Delays** - Delay delivery up to 12 hours
+- βœ… **Consumer Concurrency** - Auto-scaling up to 250 concurrent invocations
+- βœ… **Error Handling** - Timeouts, retries, rate limits
+- βœ… **Pull Consumers** - HTTP-based consumers (not just Workers)
+- βœ… **Performance Optimization** - Batching, concurrency, cost reduction
+
+---
+
+## Known Issues Prevented
+
+| Issue | Description | Prevention |
+|-------|-------------|------------|
+| **Batch retry on single failure** | One message fails β†’ entire batch retried | Use explicit ack() for non-idempotent operations |
+| **Messages deleted without DLQ** | After max_retries, messages permanently lost | Configure dead_letter_queue in consumer |
+| **Throughput exceeded** | >5000 msg/s per queue causes errors | Document limit + implement retry logic |
+| **Message too large** | >128 KB fails to send | Validate message size before sending |
+| **Ordering not guaranteed** | Messages arrive out of order | Use timestamps, don't rely on delivery order |
+| **Consumer timeout** | Default 30s CPU limit too low | Set limits.cpu_ms up to 300000 (5 min) |
+| **No explicit ack** | DB writes/API calls repeated on retry | Always ack() after successful operations |
+| **Rate limit errors** | API rate limits (1200 req/5min) | Implement exponential backoff |
+
+---
+
+## When to Use This Skill
+
+### βœ… Use this skill when:
+- Decoupling application components
+- Processing tasks asynchronously
+- Handling background jobs (emails, notifications, data processing)
+- Buffering calls to external APIs
+- Implementing task queues
+- Managing workload spikes
+- Rate limiting upstream services
+- Building event-driven architectures
+- Processing webhooks asynchronously
+- Scheduling delayed tasks
+
+### ❌ When NOT to use:
+- You need real-time processing (<1 second latency)
+- You need guaranteed FIFO ordering (use Durable Objects)
+- You need strict message ordering
+- Messages >128 KB (split them or use R2 references)
+- You need synchronous responses
+- You need transactional guarantees across operations
+
+---
+
+## Quick Example
+
+```typescript
+import { Hono } from 'hono';
+
+type Bindings = {
+ MY_QUEUE: Queue;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// Producer: Send message to queue
+app.post('/tasks', async (c) => {
+ const task = await c.req.json();
+
+ // Send single message
+ await c.env.MY_QUEUE.send({
+ type: 'process-order',
+ orderId: task.orderId,
+ userId: task.userId,
+ });
+
+ return c.json({ status: 'queued' });
+});
+
+// Producer: Send batch of messages
+app.post('/tasks/batch', async (c) => {
+ const tasks = await c.req.json();
+
+ // Send up to 100 messages at once
+ await c.env.MY_QUEUE.sendBatch(
+ tasks.map((task) => ({
+ body: {
+ type: 'process-order',
+ orderId: task.orderId,
+ },
+ }))
+ );
+
+ return c.json({ status: 'queued', count: tasks.length });
+});
+
+export default app;
+```
+
+```typescript
+// Consumer: Process messages from queue
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ // Process each message
+ for (const message of batch.messages) {
+ try {
+ // Your processing logic
+ await processOrder(message.body);
+
+ // Explicitly acknowledge success
+ message.ack();
+ } catch (error) {
+ console.error(`Failed to process message ${message.id}:`, error);
+
+ // Retry with exponential backoff
+ message.retry({
+ delaySeconds: Math.min(60 * message.attempts, 3600),
+ });
+ }
+ }
+ },
+};
+```
+
+---
+
+## Token Efficiency
+
+- **Manual Setup**: 8,000-12,000 tokens
+- **With This Skill**: 3,500-5,500 tokens
+- **Savings**: ~50-55%
+
+---
+
+## Files Included
+
+- `SKILL.md` - Complete Queues knowledge domain
+- `templates/wrangler-queues-config.jsonc` - Producer + Consumer bindings
+- `templates/queues-producer.ts` - Send messages (single + batch)
+- `templates/queues-consumer-basic.ts` - Basic consumer (implicit ack)
+- `templates/queues-consumer-explicit-ack.ts` - Explicit ack pattern
+- `templates/queues-dlq-pattern.ts` - Dead letter queue setup
+- `templates/queues-retry-with-delay.ts` - Retry with exponential backoff
+- `reference/wrangler-commands.md` - Complete CLI reference
+- `reference/producer-api.md` - send/sendBatch API details
+- `reference/consumer-api.md` - queue handler + batch operations
+- `reference/best-practices.md` - Patterns, concurrency, optimization
+
+---
+
+## Dependencies
+
+- **cloudflare-worker-base** - For Hono + Vite + Worker setup
+- **wrangler** - For queue management CLI
+
+---
+
+## Production Status
+
+βœ… **Production Ready**
+
+This skill is based on:
+- Official Cloudflare Queues documentation
+- Cloudflare Workers SDK examples
+- Production-tested patterns
+- Latest package versions (verified 2025-10-21)
+
+---
+
+## Related Skills
+
+- **cloudflare-worker-base** - Base Worker setup with Hono
+- **cloudflare-d1** - Serverless SQLite database
+- **cloudflare-r2** - Object storage
+- **cloudflare-kv** - Key-value storage
+- **cloudflare-workers-ai** - AI inference on Workers
+
+---
+
+**Last Updated**: 2025-10-21
+**Status**: Production Ready βœ…
+**Maintainer**: Jeremy Dawes | [email protected]
diff --git a/skills/cloudflare-queues/SKILL.md b/skills/cloudflare-queues/SKILL.md
new file mode 100644
index 00000000..54340277
--- /dev/null
+++ b/skills/cloudflare-queues/SKILL.md
@@ -0,0 +1,1257 @@
+---
+name: Cloudflare Queues
+description: |
+ Complete knowledge domain for Cloudflare Queues - flexible message queue for asynchronous processing
+ and background tasks on Cloudflare Workers.
+
+ Use when: creating message queues, async processing, background jobs, batch processing, handling retries,
+ configuring dead letter queues, implementing consumer concurrency, or encountering "queue timeout",
+ "batch retry", "message lost", "throughput exceeded", "consumer not scaling" errors.
+
+ Keywords: cloudflare queues, queues workers, message queue, queue bindings, async processing,
+ background jobs, queue consumer, queue producer, batch processing, dead letter queue, dlq,
+ message retry, queue ack, consumer concurrency, queue backlog, wrangler queues
+---
+
+# Cloudflare Queues
+
+**Status**: Production Ready βœ…
+**Last Updated**: 2025-10-21
+**Dependencies**: cloudflare-worker-base (for Worker setup)
+**Latest Versions**: [email protected], @cloudflare/[email protected]
+
+---
+
+## Quick Start (10 Minutes)
+
+### 1. Create a Queue
+
+```bash
+# Create a new queue
+npx wrangler queues create my-queue
+
+# Output:
+# βœ… Successfully created queue my-queue
+
+# List all queues
+npx wrangler queues list
+
+# Get queue info
+npx wrangler queues info my-queue
+```
+
+### 2. Set Up Producer (Send Messages)
+
+**wrangler.jsonc:**
+
+```jsonc
+{
+ "name": "my-producer",
+ "main": "src/index.ts",
+ "compatibility_date": "2025-10-11",
+ "queues": {
+ "producers": [
+ {
+ "binding": "MY_QUEUE", // Available as env.MY_QUEUE
+ "queue": "my-queue" // Queue name from step 1
+ }
+ ]
+ }
+}
+```
+
+**src/index.ts (Producer):**
+
+```typescript
+import { Hono } from 'hono';
+
+type Bindings = {
+ MY_QUEUE: Queue;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// Send single message
+app.post('/send', async (c) => {
+ const body = await c.req.json();
+
+ await c.env.MY_QUEUE.send({
+ userId: body.userId,
+ action: 'process-order',
+ timestamp: Date.now(),
+ });
+
+ return c.json({ status: 'queued' });
+});
+
+// Send batch of messages
+app.post('/send-batch', async (c) => {
+ const items = await c.req.json();
+
+ await c.env.MY_QUEUE.sendBatch(
+ items.map((item) => ({
+ body: { userId: item.userId, action: item.action },
+ }))
+ );
+
+ return c.json({ status: 'queued', count: items.length });
+});
+
+export default app;
+```
+
+### 3. Set Up Consumer (Process Messages)
+
+**Create consumer Worker:**
+
+```bash
+# In a new directory
+npm create cloudflare@latest my-consumer -- --type hello-world --ts
+cd my-consumer
+```
+
+**wrangler.jsonc:**
+
+```jsonc
+{
+ "name": "my-consumer",
+ "main": "src/index.ts",
+ "compatibility_date": "2025-10-11",
+ "queues": {
+ "consumers": [
+ {
+ "queue": "my-queue", // Queue to consume from
+ "max_batch_size": 10, // Process up to 10 messages at once
+ "max_batch_timeout": 5 // Or wait max 5 seconds
+ }
+ ]
+ }
+}
+```
+
+**src/index.ts (Consumer):**
+
+```typescript
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ console.log(`Processing batch of ${batch.messages.length} messages`);
+
+ for (const message of batch.messages) {
+ console.log('Message:', message.id, message.body, `Attempt: ${message.attempts}`);
+
+ // Your processing logic here
+ await processMessage(message.body);
+ }
+
+ // Implicit acknowledgement: if this function returns without error,
+ // all messages are automatically acknowledged
+ },
+};
+
+async function processMessage(body: any) {
+ // Process the message
+ console.log('Processing:', body);
+}
+```
+
+### 4. Deploy and Test
+
+```bash
+# Deploy producer
+cd my-producer
+npm run deploy
+
+# Deploy consumer
+cd my-consumer
+npm run deploy
+
+# Test by sending a message
+curl -X POST https://my-producer.<your-subdomain>.workers.dev/send \
+ -H "Content-Type: application/json" \
+ -d '{"userId": "123", "action": "welcome-email"}'
+
+# Watch consumer logs
+npx wrangler tail my-consumer
+```
+
+---
+
+## Complete Producer API
+
+### `send()` - Send Single Message
+
+```typescript
+interface QueueSendOptions {
+ delaySeconds?: number; // Delay delivery (0-43200 seconds / 12 hours)
+}
+
+await env.MY_QUEUE.send(body: any, options?: QueueSendOptions);
+```
+
+**Examples:**
+
+```typescript
+// Simple send
+await env.MY_QUEUE.send({ userId: '123', action: 'send-email' });
+
+// Send with delay (10 minutes)
+await env.MY_QUEUE.send(
+ { userId: '123', action: 'reminder' },
+ { delaySeconds: 600 }
+);
+
+// Send structured data
+await env.MY_QUEUE.send({
+ type: 'order-confirmation',
+ orderId: 'ORD-123',
+ email: '[email protected]',
+ items: [{ sku: 'ITEM-1', quantity: 2 }],
+ total: 49.99,
+ timestamp: Date.now(),
+});
+```
+
+**CRITICAL:**
+- Message body must be JSON serializable (structured clone algorithm)
+- Maximum message size: **128 KB** (including ~100 bytes internal metadata)
+- Messages >128 KB will fail - split them or store in R2 and send reference
+
+---
+
+### `sendBatch()` - Send Multiple Messages
+
+```typescript
+interface MessageSendRequest<Body = any> {
+ body: Body;
+ delaySeconds?: number;
+}
+
+interface QueueSendBatchOptions {
+ delaySeconds?: number; // Default delay for all messages
+}
+
+await env.MY_QUEUE.sendBatch(
+ messages: Iterable<MessageSendRequest>,
+ options?: QueueSendBatchOptions
+);
+```
+
+**Examples:**
+
+```typescript
+// Send batch of messages
+await env.MY_QUEUE.sendBatch([
+ { body: { userId: '1', action: 'email' } },
+ { body: { userId: '2', action: 'email' } },
+ { body: { userId: '3', action: 'email' } },
+]);
+
+// Send batch with individual delays
+await env.MY_QUEUE.sendBatch([
+ { body: { task: 'task1' }, delaySeconds: 60 }, // 1 min
+ { body: { task: 'task2' }, delaySeconds: 300 }, // 5 min
+ { body: { task: 'task3' }, delaySeconds: 600 }, // 10 min
+]);
+
+// Send batch with default delay
+await env.MY_QUEUE.sendBatch(
+ [
+ { body: { task: 'task1' } },
+ { body: { task: 'task2' } },
+ ],
+ { delaySeconds: 3600 } // All delayed by 1 hour
+);
+
+// Dynamic batch from array
+const tasks = await getTasks();
+await env.MY_QUEUE.sendBatch(
+ tasks.map((task) => ({
+ body: {
+ taskId: task.id,
+ userId: task.userId,
+ priority: task.priority,
+ },
+ }))
+);
+```
+
+**Limits:**
+- Maximum 100 messages per batch
+- Maximum 256 KB total batch size
+- Each message still limited to 128 KB individually
+
+---
+
+## Complete Consumer API
+
+### Queue Handler Function
+
+```typescript
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ // Process messages
+ },
+};
+```
+
+**Parameters:**
+- `batch` - MessageBatch object containing messages
+- `env` - Environment bindings (KV, D1, R2, etc.)
+- `ctx` - Execution context for `waitUntil()`, `passThroughOnException()`
+
+---
+
+### MessageBatch Interface
+
+```typescript
+interface MessageBatch<Body = unknown> {
+ readonly queue: string; // Queue name
+ readonly messages: Message<Body>[]; // Array of messages
+ ackAll(): void; // Acknowledge all messages
+ retryAll(options?: QueueRetryOptions): void; // Retry all messages
+}
+```
+
+**Properties:**
+
+- **`queue`** - Name of the queue this batch came from
+ - Useful when one consumer handles multiple queues
+
+- **`messages`** - Array of Message objects
+ - Ordering is **best effort**, not guaranteed
+ - Process order should not be assumed
+
+**Methods:**
+
+- **`ackAll()`** - Mark all messages as successfully delivered
+ - Even if handler throws error, these messages won't retry
+ - Use when you've safely processed all messages
+
+- **`retryAll(options?)`** - Mark all messages for retry
+ - Messages re-queued immediately (or after delay)
+ - Counts towards max_retries limit
+
+---
+
+### Message Interface
+
+```typescript
+interface Message<Body = unknown> {
+ readonly id: string; // Unique message ID
+ readonly timestamp: Date; // When message was sent
+ readonly body: Body; // Message content
+ readonly attempts: number; // Retry count (starts at 1)
+ ack(): void; // Acknowledge this message
+ retry(options?: QueueRetryOptions): void; // Retry this message
+}
+```
+
+**Properties:**
+
+- **`id`** - System-generated unique ID (UUID)
+- **`timestamp`** - Date object when message was sent to queue
+- **`body`** - Your message content (any JSON serializable type)
+- **`attempts`** - Number of times consumer has processed this message
+ - Starts at 1 on first delivery
+ - Increments on each retry
+ - Use for exponential backoff: `delaySeconds: 60 * message.attempts`
+
+**Methods:**
+
+- **`ack()`** - Mark message as successfully delivered
+ - Message won't be retried even if handler fails later
+ - **Critical for non-idempotent operations** (DB writes, API calls)
+
+- **`retry(options?)`** - Mark message for retry
+ - Re-queued immediately or after `delaySeconds`
+ - Counts towards max_retries (default 3)
+
+---
+
+### QueueRetryOptions
+
+```typescript
+interface QueueRetryOptions {
+ delaySeconds?: number; // Delay retry (0-43200 seconds / 12 hours)
+}
+```
+
+**Example:**
+
+```typescript
+// Retry immediately
+message.retry();
+
+// Retry after 5 minutes
+message.retry({ delaySeconds: 300 });
+
+// Exponential backoff based on attempts
+message.retry({
+ delaySeconds: Math.min(60 * Math.pow(2, message.attempts - 1), 3600),
+});
+```
+
+---
+
+## Consumer Patterns
+
+### 1. Basic Consumer (Implicit Acknowledgement)
+
+**Best for:** Idempotent operations where retries are safe
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ // Process message
+ await sendEmail(message.body.email, message.body.content);
+ }
+
+ // Implicit ack: returning successfully acknowledges ALL messages
+ },
+};
+```
+
+**Behavior:**
+- If function returns successfully β†’ all messages acknowledged
+- If function throws error β†’ **all messages retried**
+- Simple but can cause duplicate processing on partial failures
+
+---
+
+### 2. Explicit Acknowledgement (Non-Idempotent Operations)
+
+**Best for:** Database writes, API calls, financial transactions
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ try {
+ // Non-idempotent operation
+ await env.DB.prepare(
+ 'INSERT INTO orders (id, user_id, amount) VALUES (?, ?, ?)'
+ ).bind(message.body.orderId, message.body.userId, message.body.amount).run();
+
+ // Explicitly acknowledge success
+ message.ack();
+ } catch (error) {
+ console.error(`Failed to process ${message.id}:`, error);
+
+ // Don't ack - will retry (or let it fail)
+ // Optionally: message.retry() for explicit retry
+ }
+ }
+ },
+};
+```
+
+**Why explicit ack?**
+- Prevents duplicate writes if one message in batch fails
+- Only successfully processed messages are acknowledged
+- Failed messages retry independently
+
+---
+
+### 3. Retry with Exponential Backoff
+
+**Best for:** Rate-limited APIs, temporary failures
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ try {
+ // Call rate-limited API
+ await fetch('https://api.example.com/process', {
+ method: 'POST',
+ body: JSON.stringify(message.body),
+ });
+
+ message.ack();
+ } catch (error) {
+ if (error.status === 429) {
+ // Rate limited - retry with exponential backoff
+ const delaySeconds = Math.min(
+ 60 * Math.pow(2, message.attempts - 1), // 60s, 120s, 240s, ...
+ 3600 // Max 1 hour
+ );
+
+ console.log(`Rate limited. Retrying in ${delaySeconds}s (attempt ${message.attempts})`);
+ message.retry({ delaySeconds });
+ } else {
+ // Other error - retry immediately
+ message.retry();
+ }
+ }
+ }
+ },
+};
+```
+
+---
+
+### 4. Dead Letter Queue (DLQ) Pattern
+
+**Best for:** Handling permanently failed messages
+
+**Setup DLQ:**
+
+```bash
+# Create DLQ
+npx wrangler queues create my-dlq
+
+# Configure consumer with DLQ
+```
+
+**wrangler.jsonc:**
+
+```jsonc
+{
+ "queues": {
+ "consumers": [
+ {
+ "queue": "my-queue",
+ "max_batch_size": 10,
+ "max_retries": 3,
+ "dead_letter_queue": "my-dlq" // Failed messages go here
+ }
+ ]
+ }
+}
+```
+
+**DLQ Consumer:**
+
+```typescript
+// Consumer for dead letter queue
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ // Log failed message
+ console.error('PERMANENTLY FAILED MESSAGE:', {
+ id: message.id,
+ attempts: message.attempts,
+ body: message.body,
+ timestamp: message.timestamp,
+ });
+
+ // Store in database for manual review
+ await env.DB.prepare(
+ 'INSERT INTO failed_messages (id, body, attempts, failed_at) VALUES (?, ?, ?, ?)'
+ ).bind(
+ message.id,
+ JSON.stringify(message.body),
+ message.attempts,
+ new Date().toISOString()
+ ).run();
+
+ // Optionally: send alert to ops team
+ await sendAlert({
+ type: 'queue-dlq',
+ messageId: message.id,
+ queue: batch.queue,
+ });
+
+ // Acknowledge to remove from DLQ
+ message.ack();
+ }
+ },
+};
+```
+
+**How it works:**
+1. Message fails in main queue
+2. Retries up to `max_retries` (default 3)
+3. After max retries, sent to DLQ
+4. DLQ consumer processes failed messages
+5. Without DLQ, messages are **deleted permanently**
+
+---
+
+### 5. Multiple Queues, Single Consumer
+
+**Best for:** Centralized processing logic
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ // Switch based on queue name
+ switch (batch.queue) {
+ case 'high-priority-queue':
+ await processHighPriority(batch.messages, env);
+ break;
+
+ case 'low-priority-queue':
+ await processLowPriority(batch.messages, env);
+ break;
+
+ case 'email-queue':
+ await processEmails(batch.messages, env);
+ break;
+
+ default:
+ console.warn(`Unknown queue: ${batch.queue}`);
+ // Log to DLQ or monitoring
+ }
+ },
+};
+
+async function processHighPriority(messages: Message[], env: Env) {
+ for (const message of messages) {
+ // Process with urgency
+ await fastProcess(message.body);
+ message.ack();
+ }
+}
+
+async function processLowPriority(messages: Message[], env: Env) {
+ for (const message of messages) {
+ // Can take longer
+ await slowProcess(message.body);
+ message.ack();
+ }
+}
+```
+
+**wrangler.jsonc:**
+
+```jsonc
+{
+ "queues": {
+ "consumers": [
+ { "queue": "high-priority-queue" },
+ { "queue": "low-priority-queue" },
+ { "queue": "email-queue" }
+ ]
+ }
+}
+```
+
+---
+
+## Consumer Configuration
+
+### Batch Settings
+
+```jsonc
+{
+ "queues": {
+ "consumers": [
+ {
+ "queue": "my-queue",
+ "max_batch_size": 100, // 1-100 messages (default: 10)
+ "max_batch_timeout": 30 // 0-60 seconds (default: 5)
+ }
+ ]
+ }
+}
+```
+
+**How batching works:**
+- Consumer called when **either** condition met:
+ - `max_batch_size` messages accumulated
+ - `max_batch_timeout` seconds elapsed (whichever comes first)
+
+**Example:**
+- `max_batch_size: 100`, `max_batch_timeout: 10`
+- If 100 messages arrive in 3 seconds β†’ batch delivered immediately
+- If only 50 messages arrive in 10 seconds β†’ batch of 50 delivered
+
+**Tuning guidelines:**
+- **High volume, low latency** β†’ `max_batch_size: 100`, `max_batch_timeout: 1`
+- **Low volume, batch writes** β†’ `max_batch_size: 50`, `max_batch_timeout: 30`
+- **Cost optimization** β†’ Larger batches = fewer invocations
+
+---
+
+### Retry Settings
+
+```jsonc
+{
+ "queues": {
+ "consumers": [
+ {
+ "queue": "my-queue",
+ "max_retries": 5, // 0-100 (default: 3)
+ "retry_delay": 300 // Seconds (default: 0)
+ }
+ ]
+ }
+}
+```
+
+**`max_retries`:**
+- Number of times to retry failed message
+- After max retries:
+ - With DLQ β†’ message sent to DLQ
+ - Without DLQ β†’ **message deleted permanently**
+
+**`retry_delay`:**
+- Default delay for all retried messages (seconds)
+- Can be overridden with `message.retry({ delaySeconds })`
+- Maximum delay: 43200 seconds (12 hours)
+
+---
+
+### Concurrency Settings
+
+```jsonc
+{
+ "queues": {
+ "consumers": [
+ {
+ "queue": "my-queue",
+ "max_concurrency": 10 // 1-250 (default: auto-scale)
+ }
+ ]
+ }
+}
+```
+
+**How concurrency works:**
+- Queues auto-scales consumers based on backlog
+- Default: Scales up to 250 concurrent invocations
+- Setting `max_concurrency` limits scaling
+
+**When to set max_concurrency:**
+- βœ… Upstream API has rate limits
+- βœ… Database connection limits
+- βœ… Want to control costs
+- ❌ Most cases - leave unset for best performance
+
+**Auto-scaling triggers:**
+- Growing backlog (messages accumulating)
+- High error rate
+- Processing speed vs. incoming rate
+
+---
+
+### Dead Letter Queue
+
+```jsonc
+{
+ "queues": {
+ "consumers": [
+ {
+ "queue": "my-queue",
+ "max_retries": 3,
+ "dead_letter_queue": "my-dlq" // Name of DLQ
+ }
+ ]
+ }
+}
+```
+
+**CRITICAL:**
+- DLQ must be created separately: `npx wrangler queues create my-dlq`
+- Without DLQ, failed messages are **deleted permanently**
+- Messages in DLQ persist for 4 days without consumer
+- Always configure DLQ for production queues
+
+---
+
+## Wrangler Commands
+
+### Create Queue
+
+```bash
+# Create queue with defaults
+npx wrangler queues create my-queue
+
+# Create with custom retention (4 days default, max 14 days)
+npx wrangler queues create my-queue --message-retention-period-secs 1209600
+
+# Create with delivery delay
+npx wrangler queues create my-queue --delivery-delay-secs 60
+```
+
+---
+
+### List Queues
+
+```bash
+npx wrangler queues list
+```
+
+---
+
+### Get Queue Info
+
+```bash
+npx wrangler queues info my-queue
+
+# Output shows:
+# - Queue name
+# - Message retention period
+# - Delivery delay
+# - Consumers
+# - Backlog size
+```
+
+---
+
+### Update Queue
+
+```bash
+# Update message retention (60 seconds to 14 days)
+npx wrangler queues update my-queue --message-retention-period-secs 604800
+
+# Update delivery delay (0 to 12 hours)
+npx wrangler queues update my-queue --delivery-delay-secs 3600
+```
+
+---
+
+### Delete Queue
+
+```bash
+npx wrangler queues delete my-queue
+
+# Warning: This deletes ALL messages in the queue!
+# Use with caution in production
+```
+
+---
+
+### Consumer Management
+
+```bash
+# Add consumer to queue
+npx wrangler queues consumer add my-queue my-consumer-worker \
+ --batch-size 50 \
+ --batch-timeout 10 \
+ --message-retries 5 \
+ --max-concurrency 20 \
+ --retry-delay-secs 300
+
+# Remove consumer from queue
+npx wrangler queues consumer remove my-queue my-consumer-worker
+```
+
+---
+
+### Purge Queue
+
+```bash
+# Delete ALL messages in queue (use with caution!)
+npx wrangler queues purge my-queue
+```
+
+---
+
+### Pause/Resume Delivery
+
+```bash
+# Pause message delivery to consumers
+npx wrangler queues pause-delivery my-queue
+
+# Resume message delivery
+npx wrangler queues resume-delivery my-queue
+```
+
+**Use cases:**
+- Maintenance on consumer Workers
+- Temporarily stop processing
+- Debug issues without losing messages
+
+---
+
+## Limits & Quotas
+
+| Feature | Limit |
+|---------|-------|
+| **Queues per account** | 10,000 |
+| **Message size** | 128 KB (includes ~100 bytes metadata) |
+| **Message retries** | 100 max |
+| **Batch size** | 1-100 messages |
+| **Batch timeout** | 0-60 seconds |
+| **Messages per sendBatch** | 100 (or 256 KB total) |
+| **Queue throughput** | 5,000 messages/second per queue |
+| **Message retention** | 4 days (default), 14 days (max) |
+| **Queue backlog size** | 25 GB per queue |
+| **Concurrent consumers** | 250 (push-based, auto-scale) |
+| **Consumer duration** | 15 minutes (wall clock) |
+| **Consumer CPU time** | 30 seconds (default), 5 minutes (max) |
+| **Visibility timeout** | 12 hours (pull consumers) |
+| **Message delay** | 12 hours (max) |
+| **API rate limit** | 1200 requests / 5 minutes |
+
+---
+
+## Pricing
+
+**Requires Workers Paid plan** ($5/month)
+
+**Operations Pricing:**
+- First 1,000,000 operations/month: **FREE**
+- After that: **$0.40 per million operations**
+
+**What counts as an operation:**
+- Each 64 KB chunk written, read, or deleted
+- Messages >64 KB count as multiple operations:
+ - 65 KB message = 2 operations
+ - 127 KB message = 2 operations
+ - 128 KB message = 2 operations
+
+**Typical message lifecycle:**
+- 1 write + 1 read + 1 delete = **3 operations**
+
+**Retries:**
+- Each retry = additional **read operation**
+- Message retried 3 times = 1 write + 4 reads + 1 delete = **6 operations**
+
+**Dead Letter Queue:**
+- Writing to DLQ = additional **write operation**
+
+**Cost examples:**
+- 1M messages/month (no retries): ((1M Γ— 3) - 1M) / 1M Γ— $0.40 = **$0.80**
+- 10M messages/month: ((10M Γ— 3) - 1M) / 1M Γ— $0.40 = **$11.60**
+- 100M messages/month: ((100M Γ— 3) - 1M) / 1M Γ— $0.40 = **$119.60**
+
+---
+
+## TypeScript Types
+
+```typescript
+// Queue binding (producer)
+interface Queue<Body = any> {
+ send(body: Body, options?: QueueSendOptions): Promise<void>;
+ sendBatch(
+ messages: Iterable<MessageSendRequest<Body>>,
+ options?: QueueSendBatchOptions
+ ): Promise<void>;
+}
+
+interface QueueSendOptions {
+ delaySeconds?: number;
+}
+
+interface MessageSendRequest<Body = any> {
+ body: Body;
+ delaySeconds?: number;
+}
+
+interface QueueSendBatchOptions {
+ delaySeconds?: number;
+}
+
+// Consumer handler
+export default {
+ queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void>;
+}
+
+interface MessageBatch<Body = unknown> {
+ readonly queue: string;
+ readonly messages: Message<Body>[];
+ ackAll(): void;
+ retryAll(options?: QueueRetryOptions): void;
+}
+
+interface Message<Body = unknown> {
+ readonly id: string;
+ readonly timestamp: Date;
+ readonly body: Body;
+ readonly attempts: number;
+ ack(): void;
+ retry(options?: QueueRetryOptions): void;
+}
+
+interface QueueRetryOptions {
+ delaySeconds?: number;
+}
+```
+
+---
+
+## Error Handling
+
+### Common Errors
+
+#### 1. Message Too Large
+
+```typescript
+// ❌ Bad: Message >128 KB
+await env.MY_QUEUE.send({
+ data: largeArray, // >128 KB
+});
+
+// βœ… Good: Check size before sending
+const message = { data: largeArray };
+const size = new TextEncoder().encode(JSON.stringify(message)).length;
+
+if (size > 128000) {
+ // Store in R2, send reference
+ const key = `messages/${crypto.randomUUID()}.json`;
+ await env.MY_BUCKET.put(key, JSON.stringify(message));
+ await env.MY_QUEUE.send({ type: 'large-message', r2Key: key });
+} else {
+ await env.MY_QUEUE.send(message);
+}
+```
+
+---
+
+#### 2. Throughput Exceeded
+
+```typescript
+// ❌ Bad: Exceeding 5000 msg/s per queue
+for (let i = 0; i < 10000; i++) {
+ await env.MY_QUEUE.send({ id: i }); // Too fast!
+}
+
+// βœ… Good: Use sendBatch
+const messages = Array.from({ length: 10000 }, (_, i) => ({
+ body: { id: i },
+}));
+
+// Send in batches of 100
+for (let i = 0; i < messages.length; i += 100) {
+ await env.MY_QUEUE.sendBatch(messages.slice(i, i + 100));
+}
+
+// βœ… Even better: Rate limit with delay
+for (let i = 0; i < messages.length; i += 100) {
+ await env.MY_QUEUE.sendBatch(messages.slice(i, i + 100));
+ if (i + 100 < messages.length) {
+ await new Promise(resolve => setTimeout(resolve, 100)); // 100ms delay
+ }
+}
+```
+
+---
+
+#### 3. Consumer Timeout
+
+```typescript
+// ❌ Bad: Long processing without CPU limit increase
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ for (const message of batch.messages) {
+ await processForMinutes(message.body); // CPU timeout!
+ }
+ },
+};
+
+// βœ… Good: Increase CPU limit in wrangler.jsonc
+```
+
+**wrangler.jsonc:**
+
+```jsonc
+{
+ "limits": {
+ "cpu_ms": 300000 // 5 minutes (max allowed)
+ }
+}
+```
+
+---
+
+#### 4. Backlog Growing
+
+```typescript
+// Issue: Consumer too slow, backlog growing
+
+// βœ… Solution 1: Increase batch size
+{
+ "queues": {
+ "consumers": [{
+ "queue": "my-queue",
+ "max_batch_size": 100 // Process more per invocation
+ }]
+ }
+}
+
+// βœ… Solution 2: Let concurrency auto-scale (don't set max_concurrency)
+
+// βœ… Solution 3: Optimize consumer code
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ // Process in parallel
+ await Promise.all(
+ batch.messages.map(async (message) => {
+ await process(message.body);
+ message.ack();
+ })
+ );
+ },
+};
+```
+
+---
+
+## Always Do βœ…
+
+1. **Configure Dead Letter Queue** for production queues
+2. **Use explicit ack()** for non-idempotent operations (DB writes, API calls)
+3. **Validate message size** before sending (<128 KB)
+4. **Use sendBatch()** for multiple messages (more efficient)
+5. **Implement exponential backoff** for retries
+6. **Set appropriate batch settings** based on workload
+7. **Monitor queue backlog** and consumer errors
+8. **Use ctx.waitUntil()** for async cleanup in consumers
+9. **Handle errors gracefully** - log, alert, retry
+10. **Let concurrency auto-scale** (don't set max_concurrency unless needed)
+
+---
+
+## Never Do ❌
+
+1. **Never assume message ordering** - not guaranteed FIFO
+2. **Never rely on implicit ack for non-idempotent ops** - use explicit ack()
+3. **Never send messages >128 KB** - will fail
+4. **Never delete queues with active messages** - data loss
+5. **Never skip DLQ configuration** in production
+6. **Never exceed 5000 msg/s per queue** - rate limit error
+7. **Never process messages synchronously in loop** - use Promise.all()
+8. **Never ignore message.attempts** - use for backoff logic
+9. **Never set max_concurrency=1** unless you have a very specific reason
+10. **Never forget to ack()** in explicit acknowledgement patterns
+
+---
+
+## Troubleshooting
+
+### Issue: Messages not being delivered to consumer
+
+**Possible causes:**
+1. Consumer not deployed
+2. Wrong queue name in wrangler.jsonc
+3. Delivery paused
+4. Consumer throwing errors
+
+**Solution:**
+
+```bash
+# Check queue info
+npx wrangler queues info my-queue
+
+# Check if delivery paused
+npx wrangler queues resume-delivery my-queue
+
+# Check consumer logs
+npx wrangler tail my-consumer
+```
+
+---
+
+### Issue: Entire batch retried when one message fails
+
+**Cause:** Using implicit acknowledgement with non-idempotent operations
+
+**Solution:** Use explicit ack()
+
+```typescript
+// βœ… Explicit ack
+for (const message of batch.messages) {
+ try {
+ await dbWrite(message.body);
+ message.ack(); // Only ack on success
+ } catch (error) {
+ console.error(`Failed: ${message.id}`);
+ // Don't ack - will retry
+ }
+}
+```
+
+---
+
+### Issue: Messages deleted without processing
+
+**Cause:** No Dead Letter Queue configured
+
+**Solution:**
+
+```bash
+# Create DLQ
+npx wrangler queues create my-dlq
+
+# Add to consumer config
+```
+
+```jsonc
+{
+ "queues": {
+ "consumers": [{
+ "queue": "my-queue",
+ "dead_letter_queue": "my-dlq"
+ }]
+ }
+}
+```
+
+---
+
+### Issue: Consumer not auto-scaling
+
+**Possible causes:**
+1. `max_concurrency` set to 1
+2. Consumer returning errors (not processing)
+3. Batch processing too fast (no backlog)
+
+**Solution:**
+
+```jsonc
+{
+ "queues": {
+ "consumers": [{
+ "queue": "my-queue",
+ // Don't set max_concurrency - let it auto-scale
+ "max_batch_size": 50 // Increase batch size instead
+ }]
+ }
+}
+```
+
+---
+
+## Production Checklist
+
+Before deploying to production:
+
+- [ ] Dead Letter Queue created and configured
+- [ ] Explicit ack() used for non-idempotent operations
+- [ ] Message size validation (<128 KB)
+- [ ] Batch settings optimized for workload
+- [ ] Retry settings configured (max_retries, retry_delay)
+- [ ] Consumer concurrency settings appropriate
+- [ ] Error handling and logging implemented
+- [ ] Monitoring and alerting set up
+- [ ] DLQ consumer deployed
+- [ ] Exponential backoff for rate-limited APIs
+- [ ] CPU limits increased if needed (limits.cpu_ms)
+- [ ] Message retention period appropriate
+- [ ] Tested under load
+
+---
+
+## Related Documentation
+
+- [Cloudflare Queues Docs](https://developers.cloudflare.com/queues/)
+- [How Queues Works](https://developers.cloudflare.com/queues/reference/how-queues-works/)
+- [JavaScript APIs](https://developers.cloudflare.com/queues/configuration/javascript-apis/)
+- [Batching & Retries](https://developers.cloudflare.com/queues/configuration/batching-retries/)
+- [Consumer Concurrency](https://developers.cloudflare.com/queues/configuration/consumer-concurrency/)
+- [Dead Letter Queues](https://developers.cloudflare.com/queues/configuration/dead-letter-queues/)
+- [Wrangler Commands](https://developers.cloudflare.com/queues/reference/wrangler-commands/)
+- [Limits](https://developers.cloudflare.com/queues/platform/limits/)
+- [Pricing](https://developers.cloudflare.com/queues/platform/pricing/)
+
+---
+
+**Last Updated**: 2025-10-21
+**Version**: 1.0.0
+**Maintainer**: Jeremy Dawes | [email protected]
diff --git a/skills/cloudflare-queues/reference/best-practices.md b/skills/cloudflare-queues/reference/best-practices.md
new file mode 100644
index 00000000..2d928ea8
--- /dev/null
+++ b/skills/cloudflare-queues/reference/best-practices.md
@@ -0,0 +1,606 @@
+# Cloudflare Queues Best Practices
+
+Production patterns, optimization strategies, and common pitfalls.
+
+---
+
+## Consumer Design Patterns
+
+### 1. Explicit Acknowledgement for Non-Idempotent Operations
+
+**Problem:** Database writes or API calls get duplicated when batch retries
+
+**Solution:** Use explicit `ack()` for each message
+
+```typescript
+// ❌ Bad: Entire batch retried if one operation fails
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ await env.DB.prepare(
+ 'INSERT INTO orders (id, data) VALUES (?, ?)'
+ ).bind(message.body.id, JSON.stringify(message.body)).run();
+ }
+ // If last insert fails, ALL inserts are retried β†’ duplicates!
+ },
+};
+
+// βœ… Good: Each message acknowledged individually
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ try {
+ await env.DB.prepare(
+ 'INSERT INTO orders (id, data) VALUES (?, ?)'
+ ).bind(message.body.id, JSON.stringify(message.body)).run();
+
+ message.ack(); // Only ack on success
+ } catch (error) {
+ console.error(`Failed: ${message.id}`, error);
+ // Don't ack - will retry this message only
+ }
+ }
+ },
+};
+```
+
+---
+
+### 2. Exponential Backoff for Rate Limits
+
+**Problem:** Retrying immediately hits same rate limit
+
+**Solution:** Use exponential backoff based on attempts
+
+```typescript
+// ❌ Bad: Retry immediately
+try {
+ await callRateLimitedAPI();
+ message.ack();
+} catch (error) {
+ message.retry(); // Immediately hits rate limit again
+}
+
+// βœ… Good: Exponential backoff
+try {
+ await callRateLimitedAPI();
+ message.ack();
+} catch (error) {
+ if (error.status === 429) {
+ const delaySeconds = Math.min(
+ 60 * Math.pow(2, message.attempts - 1), // 1m, 2m, 4m, 8m, ...
+ 3600 // Max 1 hour
+ );
+
+ console.log(`Rate limited. Retrying in ${delaySeconds}s`);
+ message.retry({ delaySeconds });
+ }
+}
+```
+
+---
+
+### 3. Always Configure Dead Letter Queue
+
+**Problem:** Messages deleted permanently after max retries
+
+**Solution:** Always configure DLQ in production
+
+```jsonc
+{
+ "queues": {
+ "consumers": [
+ {
+ "queue": "my-queue",
+ "max_retries": 3,
+ "dead_letter_queue": "my-dlq" // βœ… Always configure
+ }
+ ]
+ }
+}
+```
+
+**DLQ Consumer:**
+
+```typescript
+// Monitor and alert on DLQ messages
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ // Log failure
+ console.error('PERMANENT FAILURE:', message.id, message.body);
+
+ // Store for manual review
+ await env.DB.prepare(
+ 'INSERT INTO failed_messages (id, body, attempts) VALUES (?, ?, ?)'
+ ).bind(message.id, JSON.stringify(message.body), message.attempts).run();
+
+ // Send alert
+ await sendAlert(`Message ${message.id} failed permanently`);
+
+ message.ack();
+ }
+ },
+};
+```
+
+---
+
+## Batch Configuration
+
+### Optimizing Batch Size
+
+**High volume, low latency:**
+
+```jsonc
+{
+ "queues": {
+ "consumers": [{
+ "queue": "high-volume-queue",
+ "max_batch_size": 100, // Max messages per batch
+ "max_batch_timeout": 1 // Process ASAP
+ }]
+ }
+}
+```
+
+**Low volume, batch efficiency:**
+
+```jsonc
+{
+ "queues": {
+ "consumers": [{
+ "queue": "low-volume-queue",
+ "max_batch_size": 50, // Medium batch
+ "max_batch_timeout": 30 // Wait for batch to fill
+ }]
+ }
+}
+```
+
+**Cost optimization:**
+
+```jsonc
+{
+ "queues": {
+ "consumers": [{
+ "queue": "cost-optimized",
+ "max_batch_size": 100, // Largest batches
+ "max_batch_timeout": 60 // Max wait time
+ }]
+ }
+}
+```
+
+---
+
+## Concurrency Management
+
+### Let It Auto-Scale (Default)
+
+```jsonc
+{
+ "queues": {
+ "consumers": [{
+ "queue": "my-queue"
+ // No max_concurrency - auto-scales to 250
+ }]
+ }
+}
+```
+
+**βœ… Use when:**
+- Default case
+- Want best performance
+- No upstream rate limits
+
+---
+
+### Limit Concurrency
+
+```jsonc
+{
+ "queues": {
+ "consumers": [{
+ "queue": "rate-limited-api-queue",
+ "max_concurrency": 10 // Limit to 10 concurrent consumers
+ }]
+ }
+}
+```
+
+**βœ… Use when:**
+- Calling rate-limited APIs
+- Database connection limits
+- Want to control costs
+- Protecting upstream services
+
+---
+
+## Message Design
+
+### Include Metadata
+
+```typescript
+// βœ… Good: Include helpful metadata
+await env.MY_QUEUE.send({
+ // Message type for routing
+ type: 'order-confirmation',
+
+ // Idempotency key
+ idempotencyKey: crypto.randomUUID(),
+
+ // Correlation ID for tracing
+ correlationId: requestId,
+
+ // Timestamps
+ createdAt: Date.now(),
+ scheduledFor: Date.now() + 3600000,
+
+ // Version for schema evolution
+ _version: 1,
+
+ // Actual payload
+ payload: {
+ orderId: 'ORD-123',
+ userId: 'USER-456',
+ total: 99.99,
+ },
+});
+```
+
+---
+
+### Message Versioning
+
+```typescript
+// Handle multiple message versions
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ for (const message of batch.messages) {
+ switch (message.body._version) {
+ case 1:
+ await processV1(message.body);
+ break;
+ case 2:
+ await processV2(message.body);
+ break;
+ default:
+ console.warn(`Unknown version: ${message.body._version}`);
+ }
+
+ message.ack();
+ }
+ },
+};
+```
+
+---
+
+### Large Messages
+
+**Problem:** Messages >128 KB fail
+
+**Solution:** Store in R2, send reference
+
+```typescript
+// Producer
+const message = { largeData: ... };
+const size = new TextEncoder().encode(JSON.stringify(message)).length;
+
+if (size > 128 * 1024) {
+ // Store in R2
+ const key = `messages/${crypto.randomUUID()}.json`;
+ await env.MY_BUCKET.put(key, JSON.stringify(message));
+
+ // Send reference
+ await env.MY_QUEUE.send({
+ type: 'large-message',
+ r2Key: key,
+ size,
+ timestamp: Date.now(),
+ });
+} else {
+ await env.MY_QUEUE.send(message);
+}
+
+// Consumer
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ if (message.body.type === 'large-message') {
+ // Fetch from R2
+ const obj = await env.MY_BUCKET.get(message.body.r2Key);
+ const data = await obj.json();
+
+ await processLargeMessage(data);
+
+ // Clean up R2
+ await env.MY_BUCKET.delete(message.body.r2Key);
+ } else {
+ await processMessage(message.body);
+ }
+
+ message.ack();
+ }
+ },
+};
+```
+
+---
+
+## Error Handling
+
+### Different Retry Strategies by Error Type
+
+```typescript
+try {
+ await processMessage(message.body);
+ message.ack();
+} catch (error) {
+ // Rate limit - exponential backoff
+ if (error.status === 429) {
+ message.retry({
+ delaySeconds: Math.min(60 * Math.pow(2, message.attempts - 1), 3600),
+ });
+ }
+ // Server error - shorter backoff
+ else if (error.status >= 500) {
+ message.retry({ delaySeconds: 60 });
+ }
+ // Client error - don't retry
+ else if (error.status >= 400) {
+ console.error('Client error, not retrying:', error);
+ // Don't ack or retry - goes to DLQ
+ }
+ // Unknown error - retry immediately
+ else {
+ message.retry();
+ }
+}
+```
+
+---
+
+### Circuit Breaker Pattern
+
+```typescript
+class CircuitBreaker {
+ private failures = 0;
+ private lastFailure = 0;
+ private state: 'closed' | 'open' | 'half-open' = 'closed';
+
+ async call<T>(fn: () => Promise<T>): Promise<T> {
+ if (this.state === 'open') {
+ // Check if we should try again
+ if (Date.now() - this.lastFailure > 60000) { // 1 minute
+ this.state = 'half-open';
+ } else {
+ throw new Error('Circuit breaker is open');
+ }
+ }
+
+ try {
+ const result = await fn();
+
+ // Success - reset
+ if (this.state === 'half-open') {
+ this.state = 'closed';
+ this.failures = 0;
+ }
+
+ return result;
+ } catch (error) {
+ this.failures++;
+ this.lastFailure = Date.now();
+
+ // Open circuit after 3 failures
+ if (this.failures >= 3) {
+ this.state = 'open';
+ }
+
+ throw error;
+ }
+ }
+}
+
+const breaker = new CircuitBreaker();
+
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ for (const message of batch.messages) {
+ try {
+ await breaker.call(() => callUpstreamAPI(message.body));
+ message.ack();
+ } catch (error) {
+ if (error.message === 'Circuit breaker is open') {
+ // Retry later when circuit might be closed
+ message.retry({ delaySeconds: 120 });
+ } else {
+ message.retry({ delaySeconds: 60 });
+ }
+ }
+ }
+ },
+};
+```
+
+---
+
+## Cost Optimization
+
+### Batch Operations
+
+```typescript
+// ❌ Bad: 100 operations (3 per message)
+for (let i = 0; i < 100; i++) {
+ await env.MY_QUEUE.send({ id: i });
+}
+
+// βœ… Good: 3 operations total (write batch, read batch, delete batch)
+await env.MY_QUEUE.sendBatch(
+ Array.from({ length: 100 }, (_, i) => ({
+ body: { id: i },
+ }))
+);
+```
+
+### Larger Batches
+
+```jsonc
+// Process more messages per invocation
+{
+ "queues": {
+ "consumers": [{
+ "queue": "my-queue",
+ "max_batch_size": 100 // βœ… Max batch size = fewer invocations
+ }]
+ }
+}
+```
+
+---
+
+## Monitoring & Observability
+
+### Structured Logging
+
+```typescript
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ console.log(JSON.stringify({
+ event: 'batch_start',
+ queue: batch.queue,
+ messageCount: batch.messages.length,
+ timestamp: Date.now(),
+ }));
+
+ let processed = 0;
+ let failed = 0;
+
+ for (const message of batch.messages) {
+ try {
+ await processMessage(message.body);
+ message.ack();
+ processed++;
+ } catch (error) {
+ console.error(JSON.stringify({
+ event: 'message_failed',
+ messageId: message.id,
+ attempts: message.attempts,
+ error: error.message,
+ }));
+ failed++;
+ }
+ }
+
+ console.log(JSON.stringify({
+ event: 'batch_complete',
+ processed,
+ failed,
+ duration: Date.now() - batch.messages[0].timestamp.getTime(),
+ }));
+ },
+};
+```
+
+### Metrics Tracking
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ const startTime = Date.now();
+
+ for (const message of batch.messages) {
+ const msgStartTime = Date.now();
+
+ try {
+ await processMessage(message.body);
+ message.ack();
+
+ // Track processing time
+ await env.METRICS.put(
+ `processing_time:${Date.now()}`,
+ String(Date.now() - msgStartTime)
+ );
+ } catch (error) {
+ await env.METRICS.put(
+ `errors:${Date.now()}`,
+ JSON.stringify({
+ messageId: message.id,
+ error: error.message,
+ })
+ );
+ }
+ }
+
+ // Track batch metrics
+ await env.METRICS.put(
+ `batch_size:${Date.now()}`,
+ String(batch.messages.length)
+ );
+ },
+};
+```
+
+---
+
+## Testing
+
+### Local Development
+
+```bash
+# Start local dev server
+npm run dev
+
+# In another terminal, send test messages
+curl -X POST http://localhost:8787/send \
+ -H "Content-Type: application/json" \
+ -d '{"test": "message"}'
+
+# Watch consumer logs
+npx wrangler tail my-consumer --local
+```
+
+### Unit Tests
+
+```typescript
+import { describe, it, expect } from 'vitest';
+
+describe('Queue Consumer', () => {
+ it('processes messages correctly', async () => {
+ const batch: MessageBatch = {
+ queue: 'test-queue',
+ messages: [
+ {
+ id: '123',
+ timestamp: new Date(),
+ body: { type: 'test', data: 'hello' },
+ attempts: 1,
+ ack: () => {},
+ retry: () => {},
+ },
+ ],
+ ackAll: () => {},
+ retryAll: () => {},
+ };
+
+ const env = {
+ // Mock bindings
+ };
+
+ const ctx = {
+ waitUntil: () => {},
+ passThroughOnException: () => {},
+ };
+
+ await worker.queue(batch, env, ctx);
+
+ // Assert expectations
+ });
+});
+```
+
+---
+
+**Last Updated**: 2025-10-21
diff --git a/skills/cloudflare-queues/reference/consumer-api.md b/skills/cloudflare-queues/reference/consumer-api.md
new file mode 100644
index 00000000..246d5762
--- /dev/null
+++ b/skills/cloudflare-queues/reference/consumer-api.md
@@ -0,0 +1,499 @@
+# Consumer API Reference
+
+Complete reference for consuming messages from Cloudflare Queues.
+
+---
+
+## Queue Handler
+
+Consumer Workers must export a `queue()` handler:
+
+```typescript
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ // Process messages
+ },
+};
+```
+
+### Parameters
+
+- **`batch`** - MessageBatch object containing messages
+- **`env`** - Environment bindings (KV, D1, R2, etc.)
+- **`ctx`** - Execution context
+ - `waitUntil(promise)` - Extend Worker lifetime
+ - `passThroughOnException()` - Continue on error
+
+### Return Value
+
+- Must return `Promise<void>` or `void`
+- Throwing error = all unacknowledged messages retried
+- Returning successfully = implicit ack for messages without explicit ack()
+
+---
+
+## MessageBatch Interface
+
+```typescript
+interface MessageBatch<Body = unknown> {
+ readonly queue: string;
+ readonly messages: Message<Body>[];
+ ackAll(): void;
+ retryAll(options?: QueueRetryOptions): void;
+}
+```
+
+### Properties
+
+#### `queue` (string)
+
+Name of the queue this batch came from.
+
+**Use case:** One consumer handling multiple queues
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ switch (batch.queue) {
+ case 'high-priority':
+ await processUrgent(batch.messages);
+ break;
+ case 'low-priority':
+ await processNormal(batch.messages);
+ break;
+ default:
+ console.warn(`Unknown queue: ${batch.queue}`);
+ }
+ },
+};
+```
+
+---
+
+#### `messages` (Message[])
+
+Array of Message objects.
+
+**Important:**
+- Ordering is **best effort**, not guaranteed
+- Don't rely on message order
+- Use timestamps for ordering if needed
+
+```typescript
+// Sort by timestamp if order matters
+const sortedMessages = batch.messages.sort(
+ (a, b) => a.timestamp.getTime() - b.timestamp.getTime()
+);
+```
+
+---
+
+### Methods
+
+#### `ackAll()` - Acknowledge All Messages
+
+Mark all messages as successfully delivered, even if handler throws error.
+
+```typescript
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ // Acknowledge all messages upfront
+ batch.ackAll();
+
+ // Even if this fails, messages won't retry
+ await processMessages(batch.messages);
+ },
+};
+```
+
+**Use cases:**
+- Idempotent operations where retries are safe
+- Already processed messages (deduplication)
+- Want to prevent retries regardless of outcome
+
+---
+
+#### `retryAll(options?)` - Retry All Messages
+
+Mark all messages for retry.
+
+```typescript
+interface QueueRetryOptions {
+ delaySeconds?: number; // 0-43200 (12 hours)
+}
+
+batch.retryAll();
+batch.retryAll({ delaySeconds: 300 }); // Retry in 5 minutes
+```
+
+**Use cases:**
+- Rate limiting (retry after backoff)
+- Temporary system failure
+- Upstream service unavailable
+
+```typescript
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ try {
+ await callUpstreamAPI(batch.messages);
+ } catch (error) {
+ if (error.status === 503) {
+ // Service unavailable - retry in 5 minutes
+ batch.retryAll({ delaySeconds: 300 });
+ } else {
+ // Other error - retry immediately
+ batch.retryAll();
+ }
+ }
+ },
+};
+```
+
+---
+
+## Message Interface
+
+```typescript
+interface Message<Body = unknown> {
+ readonly id: string;
+ readonly timestamp: Date;
+ readonly body: Body;
+ readonly attempts: number;
+ ack(): void;
+ retry(options?: QueueRetryOptions): void;
+}
+```
+
+### Properties
+
+#### `id` (string)
+
+Unique system-generated message ID (UUID format).
+
+```typescript
+console.log(message.id); // "550e8400-e29b-41d4-a716-446655440000"
+```
+
+---
+
+#### `timestamp` (Date)
+
+When message was sent to queue.
+
+```typescript
+console.log(message.timestamp); // Date object
+console.log(message.timestamp.toISOString()); // "2025-10-21T12:34:56.789Z"
+
+// Check message age
+const ageMs = Date.now() - message.timestamp.getTime();
+console.log(`Message age: ${ageMs}ms`);
+```
+
+---
+
+#### `body` (any)
+
+Your message content.
+
+```typescript
+interface MyMessage {
+ type: string;
+ userId: string;
+ data: any;
+}
+
+const message: Message<MyMessage> = ...;
+console.log(message.body.type); // TypeScript knows the type
+console.log(message.body.userId);
+console.log(message.body.data);
+```
+
+---
+
+#### `attempts` (number)
+
+Number of times consumer has attempted to process this message. Starts at 1.
+
+```typescript
+console.log(message.attempts); // 1 (first attempt)
+
+// Use for exponential backoff
+const delaySeconds = 60 * Math.pow(2, message.attempts - 1);
+message.retry({ delaySeconds });
+
+// Attempts: 1 β†’ 60s, 2 β†’ 120s, 3 β†’ 240s, 4 β†’ 480s, ...
+```
+
+---
+
+### Methods
+
+#### `ack()` - Acknowledge Message
+
+Mark message as successfully delivered. Won't retry even if handler fails.
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ try {
+ // Non-idempotent operation
+ await env.DB.prepare(
+ 'INSERT INTO orders (id, data) VALUES (?, ?)'
+ ).bind(message.body.id, JSON.stringify(message.body)).run();
+
+ // CRITICAL: Acknowledge success
+ message.ack();
+ } catch (error) {
+ console.error(`Failed: ${message.id}`, error);
+ // Don't ack - will retry
+ }
+ }
+ },
+};
+```
+
+**Use cases:**
+- Database writes
+- Payment processing
+- Any non-idempotent operation
+- Prevents duplicate processing
+
+---
+
+#### `retry(options?)` - Retry Message
+
+Mark message for retry. Can optionally delay retry.
+
+```typescript
+interface QueueRetryOptions {
+ delaySeconds?: number; // 0-43200 (12 hours)
+}
+
+message.retry();
+message.retry({ delaySeconds: 600 }); // Retry in 10 minutes
+```
+
+**Use cases:**
+- Rate limiting (429 errors)
+- Temporary failures
+- Exponential backoff
+
+```typescript
+// Exponential backoff
+message.retry({
+ delaySeconds: Math.min(
+ 60 * Math.pow(2, message.attempts - 1),
+ 3600 // Max 1 hour
+ ),
+});
+
+// Different delays for different errors
+try {
+ await processMessage(message.body);
+ message.ack();
+} catch (error) {
+ if (error.status === 429) {
+ // Rate limited - retry in 5 minutes
+ message.retry({ delaySeconds: 300 });
+ } else if (error.status >= 500) {
+ // Server error - retry in 1 minute
+ message.retry({ delaySeconds: 60 });
+ } else {
+ // Client error - don't retry
+ console.error('Client error, not retrying');
+ }
+}
+```
+
+---
+
+## Acknowledgement Precedence Rules
+
+When mixing ack/retry calls:
+
+1. **`ack()` or `retry()` wins** - First call on a message takes precedence
+2. **Individual > Batch** - Message-level call overrides batch-level call
+3. **Subsequent calls ignored** - Second call on same message is silently ignored
+
+```typescript
+// ack() takes precedence
+message.ack();
+message.retry(); // Ignored
+
+// retry() takes precedence
+message.retry();
+message.ack(); // Ignored
+
+// Individual overrides batch
+message.ack();
+batch.retryAll(); // Doesn't affect this message
+
+// Batch doesn't affect individually handled messages
+for (const msg of batch.messages) {
+ msg.ack(); // These messages won't be affected by retryAll()
+}
+batch.retryAll(); // Only affects messages not explicitly ack'd
+```
+
+---
+
+## Processing Patterns
+
+### Sequential Processing
+
+```typescript
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ for (const message of batch.messages) {
+ await processMessage(message.body);
+ message.ack();
+ }
+ },
+};
+```
+
+**Pros:** Simple, ordered processing
+**Cons:** Slow for large batches
+
+---
+
+### Parallel Processing
+
+```typescript
+export default {
+ async queue(batch: MessageBatch): Promise<void> {
+ await Promise.all(
+ batch.messages.map(async (message) => {
+ try {
+ await processMessage(message.body);
+ message.ack();
+ } catch (error) {
+ console.error(`Failed: ${message.id}`, error);
+ }
+ })
+ );
+ },
+};
+```
+
+**Pros:** Fast, efficient
+**Cons:** No ordering, higher memory usage
+
+---
+
+### Batched Database Writes
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ // Prepare all statements
+ const statements = batch.messages.map((message) =>
+ env.DB.prepare(
+ 'INSERT INTO events (id, data) VALUES (?, ?)'
+ ).bind(message.id, JSON.stringify(message.body))
+ );
+
+ // Execute in batch
+ const results = await env.DB.batch(statements);
+
+ // Acknowledge based on results
+ for (let i = 0; i < results.length; i++) {
+ if (results[i].success) {
+ batch.messages[i].ack();
+ } else {
+ console.error(`Failed: ${batch.messages[i].id}`);
+ }
+ }
+ },
+};
+```
+
+**Pros:** Efficient database usage
+**Cons:** More complex error handling
+
+---
+
+### Message Type Routing
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ try {
+ switch (message.body.type) {
+ case 'email':
+ await sendEmail(message.body, env);
+ break;
+ case 'sms':
+ await sendSMS(message.body, env);
+ break;
+ case 'push':
+ await sendPush(message.body, env);
+ break;
+ default:
+ console.warn(`Unknown type: ${message.body.type}`);
+ }
+
+ message.ack();
+ } catch (error) {
+ console.error(`Failed: ${message.id}`, error);
+ message.retry({ delaySeconds: 300 });
+ }
+ }
+ },
+};
+```
+
+---
+
+## ExecutionContext Methods
+
+### `waitUntil(promise)`
+
+Extend Worker lifetime beyond handler return.
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext): Promise<void> {
+ for (const message of batch.messages) {
+ await processMessage(message.body);
+ message.ack();
+
+ // Log asynchronously (doesn't block)
+ ctx.waitUntil(
+ env.LOGS.put(`log:${message.id}`, JSON.stringify({
+ processedAt: Date.now(),
+ message: message.body,
+ }))
+ );
+ }
+ },
+};
+```
+
+---
+
+### `passThroughOnException()`
+
+Continue processing even if handler throws.
+
+```typescript
+export default {
+ async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext): Promise<void> {
+ ctx.passThroughOnException();
+
+ // If this throws, Worker doesn't fail
+ // But unacknowledged messages will retry
+ await processMessages(batch.messages);
+ },
+};
+```
+
+---
+
+**Last Updated**: 2025-10-21
diff --git a/skills/cloudflare-queues/reference/producer-api.md b/skills/cloudflare-queues/reference/producer-api.md
new file mode 100644
index 00000000..1aaef869
--- /dev/null
+++ b/skills/cloudflare-queues/reference/producer-api.md
@@ -0,0 +1,337 @@
+# Producer API Reference
+
+Complete reference for sending messages to Cloudflare Queues from Workers.
+
+---
+
+## Queue Binding
+
+Access queues via environment bindings configured in `wrangler.jsonc`:
+
+```jsonc
+{
+ "queues": {
+ "producers": [
+ {
+ "binding": "MY_QUEUE",
+ "queue": "my-queue"
+ }
+ ]
+ }
+}
+```
+
+**TypeScript:**
+
+```typescript
+type Bindings = {
+ MY_QUEUE: Queue;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+app.post('/send', async (c) => {
+ await c.env.MY_QUEUE.send({ data: 'hello' });
+ return c.json({ sent: true });
+});
+```
+
+---
+
+## `send()` - Send Single Message
+
+### Signature
+
+```typescript
+interface Queue<Body = any> {
+ send(body: Body, options?: QueueSendOptions): Promise<void>;
+}
+
+interface QueueSendOptions {
+ delaySeconds?: number; // 0-43200 (12 hours)
+}
+```
+
+### Parameters
+
+- **`body`** - Any JSON serializable value
+ - Must be compatible with structured clone algorithm
+ - Max size: 128 KB (including ~100 bytes metadata)
+ - Types: primitives, objects, arrays, Date, Map, Set, etc.
+ - NOT supported: Functions, Symbols, DOM nodes
+
+- **`options.delaySeconds`** (optional)
+ - Delay message delivery
+ - Range: 0-43200 seconds (0-12 hours)
+ - Default: 0 (immediate delivery)
+
+### Examples
+
+```typescript
+// Send simple message
+await env.MY_QUEUE.send({ userId: '123', action: 'welcome' });
+
+// Send with delay (10 minutes)
+await env.MY_QUEUE.send(
+ { userId: '123', action: 'reminder' },
+ { delaySeconds: 600 }
+);
+
+// Send complex object
+await env.MY_QUEUE.send({
+ type: 'order',
+ order: {
+ id: 'ORD-123',
+ items: [
+ { sku: 'ITEM-1', quantity: 2, price: 19.99 },
+ { sku: 'ITEM-2', quantity: 1, price: 29.99 },
+ ],
+ total: 69.97,
+ customer: {
+ id: 'CUST-456',
+ email: '[email protected]',
+ },
+ metadata: {
+ source: 'web',
+ campaign: 'summer-sale',
+ },
+ },
+ timestamp: Date.now(),
+});
+
+// Send with Date objects
+await env.MY_QUEUE.send({
+ scheduledFor: new Date('2025-12-25T00:00:00Z'),
+ createdAt: new Date(),
+});
+```
+
+---
+
+## `sendBatch()` - Send Multiple Messages
+
+### Signature
+
+```typescript
+interface Queue<Body = any> {
+ sendBatch(
+ messages: Iterable<MessageSendRequest<Body>>,
+ options?: QueueSendBatchOptions
+ ): Promise<void>;
+}
+
+interface MessageSendRequest<Body = any> {
+ body: Body;
+ delaySeconds?: number;
+}
+
+interface QueueSendBatchOptions {
+ delaySeconds?: number; // Default delay for all messages
+}
+```
+
+### Parameters
+
+- **`messages`** - Iterable of message objects
+ - Each message has `body` and optional `delaySeconds`
+ - Max 100 messages per batch
+ - Max 256 KB total batch size
+ - Can be Array, Set, Generator, etc.
+
+- **`options.delaySeconds`** (optional)
+ - Default delay applied to all messages
+ - Overridden by individual message `delaySeconds`
+
+### Examples
+
+```typescript
+// Send batch of messages
+await env.MY_QUEUE.sendBatch([
+ { body: { userId: '1', action: 'email' } },
+ { body: { userId: '2', action: 'email' } },
+ { body: { userId: '3', action: 'email' } },
+]);
+
+// Send batch with individual delays
+await env.MY_QUEUE.sendBatch([
+ { body: { task: 'immediate' }, delaySeconds: 0 },
+ { body: { task: '5-min' }, delaySeconds: 300 },
+ { body: { task: '1-hour' }, delaySeconds: 3600 },
+]);
+
+// Send batch with default delay (overridable per message)
+await env.MY_QUEUE.sendBatch(
+ [
+ { body: { task: 'default-delay' } },
+ { body: { task: 'custom-delay' }, delaySeconds: 600 },
+ ],
+ { delaySeconds: 300 } // Default 5 minutes
+);
+
+// Dynamic batch from database
+const users = await getActiveUsers();
+await env.MY_QUEUE.sendBatch(
+ users.map(user => ({
+ body: {
+ type: 'send-notification',
+ userId: user.id,
+ email: user.email,
+ message: 'You have a new message',
+ },
+ }))
+);
+
+// Generator pattern
+async function* generateMessages() {
+ for (let i = 0; i < 100; i++) {
+ yield {
+ body: { taskId: i, priority: i % 3 },
+ };
+ }
+}
+
+await env.MY_QUEUE.sendBatch(generateMessages());
+```
+
+---
+
+## Message Size Validation
+
+Messages must be ≀128 KB. Check size before sending:
+
+```typescript
+async function sendWithValidation(queue: Queue, message: any) {
+ const messageStr = JSON.stringify(message);
+ const size = new TextEncoder().encode(messageStr).length;
+ const MAX_SIZE = 128 * 1024; // 128 KB
+
+ if (size > MAX_SIZE) {
+ throw new Error(
+ `Message too large: ${size} bytes (max ${MAX_SIZE})`
+ );
+ }
+
+ await queue.send(message);
+}
+```
+
+**Handling large messages:**
+
+```typescript
+// Store large data in R2, send reference
+if (size > 128 * 1024) {
+ const key = `messages/${crypto.randomUUID()}.json`;
+ await env.MY_BUCKET.put(key, JSON.stringify(largeMessage));
+
+ await env.MY_QUEUE.send({
+ type: 'large-message',
+ r2Key: key,
+ metadata: {
+ size,
+ createdAt: Date.now(),
+ },
+ });
+}
+```
+
+---
+
+## Throughput Management
+
+Max throughput: 5,000 messages/second per queue.
+
+**Rate limiting:**
+
+```typescript
+// Batch sends for better throughput
+const messages = Array.from({ length: 1000 }, (_, i) => ({
+ body: { id: i },
+}));
+
+// Send in batches of 100 (10 sendBatch calls vs 1000 send calls)
+for (let i = 0; i < messages.length; i += 100) {
+ const batch = messages.slice(i, i + 100);
+ await env.MY_QUEUE.sendBatch(batch);
+}
+
+// Add delay if needed
+for (let i = 0; i < messages.length; i += 100) {
+ const batch = messages.slice(i, i + 100);
+ await env.MY_QUEUE.sendBatch(batch);
+
+ if (i + 100 < messages.length) {
+ await new Promise(resolve => setTimeout(resolve, 100)); // 100ms
+ }
+}
+```
+
+---
+
+## Error Handling
+
+```typescript
+try {
+ await env.MY_QUEUE.send(message);
+} catch (error) {
+ if (error.message.includes('Too Many Requests')) {
+ // Throughput exceeded (>5000 msg/s)
+ console.error('Rate limited');
+ } else if (error.message.includes('too large')) {
+ // Message >128 KB
+ console.error('Message too large');
+ } else {
+ // Other error
+ console.error('Queue send failed:', error);
+ }
+}
+```
+
+---
+
+## Production Patterns
+
+### Idempotency Keys
+
+```typescript
+await env.MY_QUEUE.send({
+ idempotencyKey: crypto.randomUUID(),
+ orderId: 'ORD-123',
+ action: 'process',
+});
+```
+
+### Message Versioning
+
+```typescript
+await env.MY_QUEUE.send({
+ _version: 1,
+ _schema: 'order-v1',
+ orderId: 'ORD-123',
+ // ...
+});
+```
+
+### Correlation IDs
+
+```typescript
+await env.MY_QUEUE.send({
+ correlationId: requestId,
+ parentSpanId: traceId,
+ // ...
+});
+```
+
+### Priority Queues
+
+```typescript
+// Use multiple queues for different priorities
+if (priority === 'high') {
+ await env.HIGH_PRIORITY_QUEUE.send(message);
+} else {
+ await env.LOW_PRIORITY_QUEUE.send(message);
+}
+```
+
+---
+
+**Last Updated**: 2025-10-21
diff --git a/skills/cloudflare-queues/reference/wrangler-commands.md b/skills/cloudflare-queues/reference/wrangler-commands.md
new file mode 100644
index 00000000..2bf40601
--- /dev/null
+++ b/skills/cloudflare-queues/reference/wrangler-commands.md
@@ -0,0 +1,392 @@
+# Wrangler Commands for Cloudflare Queues
+
+Complete reference for managing Cloudflare Queues via the `wrangler` CLI.
+
+---
+
+## Queue Management
+
+### Create Queue
+
+```bash
+npx wrangler queues create <NAME> [OPTIONS]
+```
+
+**Options:**
+- `--delivery-delay-secs <SECONDS>` - Default delay for all messages (0-43200)
+- `--message-retention-period-secs <SECONDS>` - How long messages persist (60-1209600, default: 345600 / 4 days)
+
+**Examples:**
+
+```bash
+# Create basic queue
+npx wrangler queues create my-queue
+
+# Create with custom retention (7 days)
+npx wrangler queues create my-queue --message-retention-period-secs 604800
+
+# Create with default delivery delay (5 minutes)
+npx wrangler queues create delayed-queue --delivery-delay-secs 300
+```
+
+---
+
+### List Queues
+
+```bash
+npx wrangler queues list
+```
+
+**Output:**
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Name β”‚ Consumers β”‚ Messages β”‚
+β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
+β”‚ my-queue β”‚ 1 β”‚ 0 β”‚
+β”‚ high-priority β”‚ 2 β”‚ 142 β”‚
+β”‚ my-dlq β”‚ 1 β”‚ 5 β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+---
+
+### Get Queue Info
+
+```bash
+npx wrangler queues info <NAME>
+```
+
+**Example:**
+
+```bash
+npx wrangler queues info my-queue
+
+# Output:
+# Queue: my-queue
+# Message Retention: 345600 seconds (4 days)
+# Delivery Delay: 0 seconds
+# Consumers: 1
+# - my-consumer (batch_size: 10, batch_timeout: 5s, max_retries: 3)
+# Backlog: 0 messages
+```
+
+---
+
+### Update Queue
+
+```bash
+npx wrangler queues update <NAME> [OPTIONS]
+```
+
+**Options:**
+- `--delivery-delay-secs <SECONDS>` - Update default delay
+- `--message-retention-period-secs <SECONDS>` - Update retention period
+
+**Examples:**
+
+```bash
+# Update retention to 14 days (max)
+npx wrangler queues update my-queue --message-retention-period-secs 1209600
+
+# Update delivery delay to 10 minutes
+npx wrangler queues update my-queue --delivery-delay-secs 600
+```
+
+---
+
+### Delete Queue
+
+```bash
+npx wrangler queues delete <NAME>
+```
+
+**⚠️ WARNING:**
+- Deletes ALL messages in the queue
+- Cannot be undone
+- Use with extreme caution in production
+
+**Example:**
+
+```bash
+npx wrangler queues delete old-queue
+```
+
+---
+
+## Consumer Management
+
+### Add Consumer
+
+```bash
+npx wrangler queues consumer add <QUEUE-NAME> <WORKER-SCRIPT-NAME> [OPTIONS]
+```
+
+**Options:**
+- `--batch-size <NUMBER>` - Max messages per batch (1-100, default: 10)
+- `--batch-timeout <SECONDS>` - Max wait time (0-60, default: 5)
+- `--message-retries <NUMBER>` - Max retry attempts (0-100, default: 3)
+- `--max-concurrency <NUMBER>` - Limit concurrent consumers (default: auto-scale to 250)
+- `--retry-delay-secs <SECONDS>` - Default retry delay
+- `--dead-letter-queue <QUEUE-NAME>` - DLQ for failed messages
+
+**Examples:**
+
+```bash
+# Basic consumer
+npx wrangler queues consumer add my-queue my-consumer
+
+# Optimized for high throughput
+npx wrangler queues consumer add my-queue my-consumer \
+ --batch-size 100 \
+ --batch-timeout 1
+
+# With DLQ and retry settings
+npx wrangler queues consumer add my-queue my-consumer \
+ --batch-size 50 \
+ --message-retries 5 \
+ --retry-delay-secs 300 \
+ --dead-letter-queue my-dlq
+
+# Limit concurrency for rate-limited APIs
+npx wrangler queues consumer add api-queue api-consumer \
+ --max-concurrency 10
+```
+
+---
+
+### Remove Consumer
+
+```bash
+npx wrangler queues consumer remove <QUEUE-NAME> <WORKER-SCRIPT-NAME>
+```
+
+**Example:**
+
+```bash
+npx wrangler queues consumer remove my-queue my-consumer
+```
+
+---
+
+## Queue Operations
+
+### Purge Queue
+
+```bash
+npx wrangler queues purge <QUEUE-NAME>
+```
+
+**⚠️ WARNING:**
+- Permanently deletes ALL messages
+- Cannot be undone
+- Use for clearing test data or stuck queues
+
+**Example:**
+
+```bash
+npx wrangler queues purge test-queue
+```
+
+---
+
+### Pause Delivery
+
+```bash
+npx wrangler queues pause-delivery <QUEUE-NAME>
+```
+
+**Use cases:**
+- Maintenance on consumer Workers
+- Debugging consumer issues
+- Temporarily stop processing without deleting messages
+
+**Example:**
+
+```bash
+npx wrangler queues pause-delivery my-queue
+```
+
+---
+
+### Resume Delivery
+
+```bash
+npx wrangler queues resume-delivery <QUEUE-NAME>
+```
+
+**Example:**
+
+```bash
+npx wrangler queues resume-delivery my-queue
+```
+
+---
+
+## Event Subscriptions
+
+Event subscriptions automatically send messages to a queue when events occur in other Cloudflare services.
+
+### Create Subscription
+
+```bash
+npx wrangler queues subscription create <QUEUE-NAME> [OPTIONS]
+```
+
+**Options:**
+- `--source <TYPE>` - Event source (kv, r2, superSlurper, vectorize, workersAi.model, workersBuilds.worker, workflows.workflow)
+- `--events <EVENTS>` - Comma-separated list of event types
+- `--name <NAME>` - Subscription name (auto-generated if omitted)
+- `--enabled` - Whether subscription is active (default: true)
+
+**Examples:**
+
+```bash
+# Subscribe to R2 bucket events
+npx wrangler queues subscription create my-queue \
+ --source r2 \
+ --events object-create,object-delete \
+ --bucket-name my-bucket
+
+# Subscribe to KV namespace events
+npx wrangler queues subscription create my-queue \
+ --source kv \
+ --events key-write,key-delete \
+ --namespace-id abc123
+
+# Subscribe to Worker build events
+npx wrangler queues subscription create build-queue \
+ --source workersBuilds.worker \
+ --events build-complete,build-failed \
+ --worker-name my-worker
+```
+
+---
+
+### List Subscriptions
+
+```bash
+npx wrangler queues subscription list <QUEUE-NAME> [OPTIONS]
+```
+
+**Options:**
+- `--page <NUMBER>` - Page number
+- `--per-page <NUMBER>` - Results per page
+- `--json` - Output as JSON
+
+**Example:**
+
+```bash
+npx wrangler queues subscription list my-queue --json
+```
+
+---
+
+### Get Subscription
+
+```bash
+npx wrangler queues subscription get <QUEUE-NAME> --id <SUBSCRIPTION-ID> [--json]
+```
+
+**Example:**
+
+```bash
+npx wrangler queues subscription get my-queue --id sub_123 --json
+```
+
+---
+
+### Delete Subscription
+
+```bash
+npx wrangler queues subscription delete <QUEUE-NAME> --id <SUBSCRIPTION-ID>
+```
+
+**Example:**
+
+```bash
+npx wrangler queues subscription delete my-queue --id sub_123
+```
+
+---
+
+## Global Flags
+
+These flags work on all commands:
+
+- `--help` - Show help
+- `--config <PATH>` - Path to wrangler.toml or wrangler.jsonc
+- `--cwd <PATH>` - Run as if started in specified directory
+
+---
+
+## Complete Workflow Example
+
+```bash
+# 1. Create queues
+npx wrangler queues create my-queue
+npx wrangler queues create my-dlq
+
+# 2. Create and deploy producer Worker
+cd my-producer
+npm create cloudflare@latest -- --type hello-world --ts
+# Add producer binding to wrangler.jsonc
+npm run deploy
+
+# 3. Create and deploy consumer Worker
+cd ../my-consumer
+npm create cloudflare@latest -- --type hello-world --ts
+# Add consumer handler
+npm run deploy
+
+# 4. Add consumer to queue
+npx wrangler queues consumer add my-queue my-consumer \
+ --batch-size 50 \
+ --message-retries 5 \
+ --dead-letter-queue my-dlq
+
+# 5. Monitor queue
+npx wrangler queues info my-queue
+
+# 6. Watch consumer logs
+npx wrangler tail my-consumer
+
+# 7. If needed, pause delivery
+npx wrangler queues pause-delivery my-queue
+
+# 8. Resume delivery
+npx wrangler queues resume-delivery my-queue
+```
+
+---
+
+## Troubleshooting
+
+### Check queue backlog
+
+```bash
+npx wrangler queues info my-queue | grep "Backlog"
+```
+
+### Clear stuck queue
+
+```bash
+npx wrangler queues purge my-queue
+```
+
+### Verify consumer is attached
+
+```bash
+npx wrangler queues info my-queue | grep "Consumers"
+```
+
+### Check for delivery paused
+
+```bash
+npx wrangler queues info my-queue
+# Look for "Delivery: paused"
+```
+
+---
+
+**Last Updated**: 2025-10-21
+**Wrangler Version**: 4.43.0+
diff --git a/skills/cloudflare-queues/templates/queues-consumer-basic.ts b/skills/cloudflare-queues/templates/queues-consumer-basic.ts
new file mode 100644
index 00000000..c736e85c
--- /dev/null
+++ b/skills/cloudflare-queues/templates/queues-consumer-basic.ts
@@ -0,0 +1,127 @@
+/**
+ * Basic Queue Consumer (Implicit Acknowledgement)
+ *
+ * Use when: Operations are idempotent (safe to retry)
+ * Examples: Logging, sending emails (idempotent with deduplication), metrics
+ *
+ * How it works:
+ * - If handler returns successfully β†’ all messages acknowledged
+ * - If handler throws error β†’ entire batch retried
+ *
+ * Setup:
+ * 1. Create queue: npx wrangler queues create my-queue
+ * 2. Add consumer binding to wrangler.jsonc (see wrangler-queues-config.jsonc)
+ * 3. Deploy: npm run deploy
+ */
+
+type Env = {
+ // Add your bindings here (D1, KV, R2, etc.)
+ LOGS: KVNamespace;
+};
+
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ console.log(`Processing batch of ${batch.messages.length} messages from queue: ${batch.queue}`);
+
+ // Process each message
+ for (const message of batch.messages) {
+ console.log(`Message ID: ${message.id}`);
+ console.log(`Attempt: ${message.attempts}`);
+ console.log(`Timestamp: ${message.timestamp}`);
+ console.log(`Body:`, message.body);
+
+ // Your processing logic
+ await processMessage(message.body, env);
+ }
+
+ // Implicit acknowledgement:
+ // Returning successfully acknowledges ALL messages
+ // If this function throws, ALL messages will be retried
+ },
+};
+
+/**
+ * Process individual message
+ */
+async function processMessage(body: any, env: Env) {
+ switch (body.type) {
+ case 'send-email':
+ await sendEmail(body);
+ break;
+
+ case 'log-event':
+ await logEvent(body, env);
+ break;
+
+ case 'update-metrics':
+ await updateMetrics(body, env);
+ break;
+
+ default:
+ console.warn(`Unknown message type: ${body.type}`);
+ }
+}
+
+/**
+ * Example: Send email (idempotent with external deduplication)
+ */
+async function sendEmail(data: any) {
+ console.log(`Sending email to ${data.to}`);
+
+ // Call email API (e.g., Resend, SendGrid)
+ const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${process.env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ to: data.to,
+ subject: data.subject,
+ html: data.html,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to send email: ${response.statusText}`);
+ }
+
+ console.log(`Email sent successfully to ${data.to}`);
+}
+
+/**
+ * Example: Log event to KV (idempotent)
+ */
+async function logEvent(data: any, env: Env) {
+ const logKey = `log:${data.eventId}:${Date.now()}`;
+
+ await env.LOGS.put(logKey, JSON.stringify({
+ event: data.event,
+ userId: data.userId,
+ timestamp: new Date().toISOString(),
+ metadata: data.metadata,
+ }), {
+ expirationTtl: 86400 * 30, // 30 days
+ });
+
+ console.log(`Event logged: ${logKey}`);
+}
+
+/**
+ * Example: Update metrics (idempotent aggregation)
+ */
+async function updateMetrics(data: any, env: Env) {
+ // Increment counter in KV
+ const key = `metric:${data.metric}`;
+ const current = await env.LOGS.get(key);
+ const count = current ? parseInt(current) : 0;
+
+ await env.LOGS.put(key, String(count + 1));
+
+ console.log(`Metric ${data.metric} updated: ${count + 1}`);
+}
diff --git a/skills/cloudflare-queues/templates/queues-consumer-explicit-ack.ts b/skills/cloudflare-queues/templates/queues-consumer-explicit-ack.ts
new file mode 100644
index 00000000..dcba97ae
--- /dev/null
+++ b/skills/cloudflare-queues/templates/queues-consumer-explicit-ack.ts
@@ -0,0 +1,157 @@
+/**
+ * Queue Consumer with Explicit Acknowledgement
+ *
+ * Use when: Operations are non-idempotent (NOT safe to retry)
+ * Examples: Database writes, payment processing, API calls with side effects
+ *
+ * How it works:
+ * - Call message.ack() after successful processing
+ * - Only acknowledged messages are removed from queue
+ * - Failed messages can retry independently
+ *
+ * Setup:
+ * 1. Create queue: npx wrangler queues create my-queue
+ * 2. Create DLQ: npx wrangler queues create my-dlq
+ * 3. Add consumer binding with DLQ (see wrangler-queues-config.jsonc)
+ * 4. Deploy: npm run deploy
+ */
+
+type Env = {
+ DB: D1Database;
+ API_KEY: string;
+};
+
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ console.log(`Processing batch of ${batch.messages.length} messages`);
+
+ // Process each message individually
+ for (const message of batch.messages) {
+ try {
+ // Non-idempotent operation
+ await processNonIdempotent(message.body, env);
+
+ // CRITICAL: Explicitly acknowledge success
+ message.ack();
+
+ console.log(`βœ… Message ${message.id} processed successfully`);
+ } catch (error) {
+ console.error(`❌ Failed to process message ${message.id}:`, error);
+
+ // Don't call ack() - message will retry
+ // After max_retries, sent to DLQ (if configured)
+ }
+ }
+
+ // Note: We DON'T throw an error here
+ // Only unacknowledged messages will retry
+ },
+};
+
+/**
+ * Process message with non-idempotent operations
+ */
+async function processNonIdempotent(body: any, env: Env) {
+ switch (body.type) {
+ case 'create-order':
+ await createOrder(body, env);
+ break;
+
+ case 'charge-payment':
+ await chargePayment(body, env);
+ break;
+
+ case 'update-inventory':
+ await updateInventory(body, env);
+ break;
+
+ default:
+ throw new Error(`Unknown message type: ${body.type}`);
+ }
+}
+
+/**
+ * Example: Create database record (non-idempotent)
+ */
+async function createOrder(data: any, env: Env) {
+ // Insert into database (can't be retried safely)
+ const result = await env.DB.prepare(`
+ INSERT INTO orders (id, user_id, total, status, created_at)
+ VALUES (?, ?, ?, ?, ?)
+ `)
+ .bind(
+ data.orderId,
+ data.userId,
+ data.total,
+ 'pending',
+ new Date().toISOString()
+ )
+ .run();
+
+ if (!result.success) {
+ throw new Error(`Failed to create order: ${data.orderId}`);
+ }
+
+ console.log(`Order created: ${data.orderId}`);
+}
+
+/**
+ * Example: Charge payment (non-idempotent)
+ */
+async function chargePayment(data: any, env: Env) {
+ // Call payment API (can't be retried safely without deduplication)
+ const response = await fetch('https://api.stripe.com/v1/charges', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.API_KEY}`,
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: new URLSearchParams({
+ amount: String(data.amount),
+ currency: data.currency,
+ source: data.token,
+ description: data.description,
+ }),
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(`Payment failed: ${error}`);
+ }
+
+ const charge = await response.json();
+ console.log(`Payment charged: ${charge.id}`);
+
+ // Update database with charge ID
+ await env.DB.prepare(`
+ UPDATE orders SET payment_id = ?, status = 'paid' WHERE id = ?
+ `)
+ .bind(charge.id, data.orderId)
+ .run();
+}
+
+/**
+ * Example: Update inventory (non-idempotent)
+ */
+async function updateInventory(data: any, env: Env) {
+ for (const item of data.items) {
+ // Decrement inventory count
+ const result = await env.DB.prepare(`
+ UPDATE inventory
+ SET quantity = quantity - ?
+ WHERE sku = ? AND quantity >= ?
+ `)
+ .bind(item.quantity, item.sku, item.quantity)
+ .run();
+
+ if (result.changes === 0) {
+ throw new Error(`Insufficient inventory for SKU: ${item.sku}`);
+ }
+
+ console.log(`Inventory updated: ${item.sku} (-${item.quantity})`);
+ }
+}
diff --git a/skills/cloudflare-queues/templates/queues-dlq-pattern.ts b/skills/cloudflare-queues/templates/queues-dlq-pattern.ts
new file mode 100644
index 00000000..a985edbd
--- /dev/null
+++ b/skills/cloudflare-queues/templates/queues-dlq-pattern.ts
@@ -0,0 +1,215 @@
+/**
+ * Dead Letter Queue (DLQ) Consumer
+ *
+ * Handles messages that failed after max retries in the main queue.
+ *
+ * Use when: You need to:
+ * - Log permanently failed messages
+ * - Alert ops team about failures
+ * - Store failed messages for manual review
+ * - Implement custom retry logic
+ *
+ * Setup:
+ * 1. Create DLQ: npx wrangler queues create my-dlq
+ * 2. Configure main queue consumer with DLQ:
+ * "dead_letter_queue": "my-dlq" in wrangler.jsonc
+ * 3. Create consumer for DLQ (this file)
+ * 4. Deploy both consumers
+ */
+
+type Env = {
+ DB: D1Database;
+ ALERTS: KVNamespace;
+ MAIN_QUEUE: Queue; // Reference to main queue for retry
+};
+
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ console.log(`⚠️ Processing ${batch.messages.length} FAILED messages from DLQ`);
+
+ for (const message of batch.messages) {
+ try {
+ await handleFailedMessage(message, env);
+
+ // Acknowledge to remove from DLQ
+ message.ack();
+ } catch (error) {
+ console.error(`Failed to process DLQ message ${message.id}:`, error);
+ // Don't ack - will retry in DLQ
+ }
+ }
+ },
+};
+
+/**
+ * Handle permanently failed message
+ */
+async function handleFailedMessage(message: Message, env: Env) {
+ console.log(`πŸ’€ Dead Letter Message:`);
+ console.log(` ID: ${message.id}`);
+ console.log(` Attempts: ${message.attempts}`);
+ console.log(` Original Timestamp: ${message.timestamp}`);
+ console.log(` Body:`, message.body);
+
+ // 1. Store in database for manual review
+ await storeFailed Message(message, env);
+
+ // 2. Send alert to ops team
+ await sendAlert(message, env);
+
+ // 3. Optional: Implement custom retry logic
+ if (shouldRetryInMainQueue(message)) {
+ await retryInMainQueue(message, env);
+ }
+}
+
+/**
+ * Store failed message in database
+ */
+async function storeFailedMessage(message: Message, env: Env) {
+ await env.DB.prepare(`
+ INSERT INTO failed_messages (
+ id,
+ queue_name,
+ body,
+ attempts,
+ original_timestamp,
+ failed_at,
+ error_details
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
+ `)
+ .bind(
+ message.id,
+ 'my-queue', // Or get from message.body if you include it
+ JSON.stringify(message.body),
+ message.attempts,
+ message.timestamp.toISOString(),
+ new Date().toISOString(),
+ JSON.stringify({
+ reason: 'Max retries exceeded',
+ lastAttempt: message.attempts,
+ })
+ )
+ .run();
+
+ console.log(`Stored failed message in database: ${message.id}`);
+}
+
+/**
+ * Send alert to ops team
+ */
+async function sendAlert(message: Message, env: Env) {
+ // Send to monitoring service (e.g., PagerDuty, Slack, Email)
+ const alert = {
+ severity: 'high',
+ title: 'Queue Message Permanently Failed',
+ description: `Message ${message.id} failed after ${message.attempts} attempts`,
+ details: {
+ messageId: message.id,
+ attempts: message.attempts,
+ body: message.body,
+ timestamp: message.timestamp.toISOString(),
+ },
+ };
+
+ // Example: Store in KV for alert aggregation
+ const alertKey = `alert:${message.id}`;
+ await env.ALERTS.put(alertKey, JSON.stringify(alert), {
+ expirationTtl: 86400 * 7, // 7 days
+ });
+
+ // Example: Send webhook to Slack
+ await fetch(process.env.SLACK_WEBHOOK_URL || '', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ text: `🚨 Queue DLQ Alert: Message ${message.id} failed permanently`,
+ blocks: [
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: `*Message ID:* ${message.id}\n*Attempts:* ${message.attempts}\n*Type:* ${message.body.type}`,
+ },
+ },
+ ],
+ }),
+ });
+
+ console.log(`Alert sent for message: ${message.id}`);
+}
+
+/**
+ * Determine if message should be retried in main queue
+ * (e.g., after fixing a bug, or for specific message types)
+ */
+function shouldRetryInMainQueue(message: Message): boolean {
+ // Example: Retry if it's a payment message and attempts < 10
+ if (message.body.type === 'charge-payment' && message.attempts < 10) {
+ return true;
+ }
+
+ // Example: Retry if it failed due to a specific error
+ if (message.body.retryable === true) {
+ return true;
+ }
+
+ return false;
+}
+
+/**
+ * Retry message in main queue (with delay)
+ */
+async function retryInMainQueue(message: Message, env: Env) {
+ console.log(`Retrying message ${message.id} in main queue`);
+
+ // Send back to main queue with exponential delay
+ const delaySeconds = Math.min(
+ 3600 * Math.pow(2, message.attempts - 3), // Start from where DLQ picked up
+ 43200 // Max 12 hours
+ );
+
+ await env.MAIN_QUEUE.send(
+ {
+ ...message.body,
+ retriedFromDLQ: true,
+ originalMessageId: message.id,
+ dlqAttempts: message.attempts,
+ },
+ { delaySeconds }
+ );
+
+ console.log(`Message ${message.id} re-queued with ${delaySeconds}s delay`);
+}
+
+/**
+ * Manual retry endpoint (call via REST API or dashboard)
+ */
+export async function manualRetry(messageId: string, env: Env) {
+ // Fetch failed message from database
+ const result = await env.DB.prepare(
+ 'SELECT * FROM failed_messages WHERE id = ?'
+ )
+ .bind(messageId)
+ .first();
+
+ if (!result) {
+ throw new Error(`Message ${messageId} not found in DLQ`);
+ }
+
+ const body = JSON.parse(result.body as string);
+
+ // Send back to main queue
+ await env.MAIN_QUEUE.send({
+ ...body,
+ manualRetry: true,
+ retriedBy: 'admin',
+ retriedAt: new Date().toISOString(),
+ });
+
+ console.log(`Manually retried message: ${messageId}`);
+}
diff --git a/skills/cloudflare-queues/templates/queues-producer.ts b/skills/cloudflare-queues/templates/queues-producer.ts
new file mode 100644
index 00000000..49af3500
--- /dev/null
+++ b/skills/cloudflare-queues/templates/queues-producer.ts
@@ -0,0 +1,243 @@
+/**
+ * Queue Producer Example
+ *
+ * Shows how to send messages to Cloudflare Queues from a Hono Worker.
+ *
+ * Setup:
+ * 1. Create queue: npx wrangler queues create my-queue
+ * 2. Add producer binding to wrangler.jsonc (see wrangler-queues-config.jsonc)
+ * 3. Deploy: npm run deploy
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ MY_QUEUE: Queue;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Send Single Message
+// ============================================================================
+
+app.post('/send', async (c) => {
+ const body = await c.req.json();
+
+ // Simple send
+ await c.env.MY_QUEUE.send({
+ type: 'process-order',
+ orderId: body.orderId,
+ userId: body.userId,
+ timestamp: Date.now(),
+ });
+
+ return c.json({ status: 'queued' });
+});
+
+// ============================================================================
+// Send Message with Delay
+// ============================================================================
+
+app.post('/send-delayed', async (c) => {
+ const { task, delayMinutes } = await c.req.json();
+
+ // Delay message delivery
+ await c.env.MY_QUEUE.send(
+ {
+ type: 'scheduled-task',
+ task,
+ scheduledFor: Date.now() + (delayMinutes * 60 * 1000),
+ },
+ {
+ delaySeconds: delayMinutes * 60, // Convert minutes to seconds
+ }
+ );
+
+ return c.json({
+ status: 'scheduled',
+ delayMinutes,
+ processAt: new Date(Date.now() + (delayMinutes * 60 * 1000)).toISOString(),
+ });
+});
+
+// ============================================================================
+// Send Batch of Messages
+// ============================================================================
+
+app.post('/send-batch', async (c) => {
+ const items = await c.req.json<Array<any>>();
+
+ // Validate batch size (max 100 messages)
+ if (items.length > 100) {
+ return c.json(
+ { error: 'Maximum 100 messages per batch' },
+ 400
+ );
+ }
+
+ // Send batch
+ await c.env.MY_QUEUE.sendBatch(
+ items.map((item) => ({
+ body: {
+ type: 'batch-process',
+ itemId: item.id,
+ data: item.data,
+ },
+ }))
+ );
+
+ return c.json({
+ status: 'queued',
+ count: items.length,
+ });
+});
+
+// ============================================================================
+// Send Batch with Individual Delays
+// ============================================================================
+
+app.post('/send-scheduled-batch', async (c) => {
+ const tasks = await c.req.json<Array<{ task: string; delayMinutes: number }>>();
+
+ await c.env.MY_QUEUE.sendBatch(
+ tasks.map((task) => ({
+ body: {
+ type: 'scheduled-task',
+ task: task.task,
+ },
+ delaySeconds: task.delayMinutes * 60,
+ }))
+ );
+
+ return c.json({
+ status: 'scheduled',
+ count: tasks.length,
+ });
+});
+
+// ============================================================================
+// Validate Message Size (< 128 KB)
+// ============================================================================
+
+app.post('/send-validated', async (c) => {
+ const body = await c.req.json();
+
+ // Check message size
+ const messageSize = new TextEncoder().encode(JSON.stringify(body)).length;
+ const MAX_SIZE = 128 * 1024; // 128 KB
+
+ if (messageSize > MAX_SIZE) {
+ return c.json(
+ {
+ error: 'Message too large',
+ size: messageSize,
+ maxSize: MAX_SIZE,
+ },
+ 400
+ );
+ }
+
+ await c.env.MY_QUEUE.send(body);
+
+ return c.json({
+ status: 'queued',
+ messageSize,
+ });
+});
+
+// ============================================================================
+// Real-World Example: E-commerce Order Processing
+// ============================================================================
+
+interface Order {
+ orderId: string;
+ userId: string;
+ items: Array<{ sku: string; quantity: number; price: number }>;
+ total: number;
+ email: string;
+}
+
+app.post('/orders', async (c) => {
+ const order: Order = await c.req.json();
+
+ // Queue multiple tasks for this order
+ await c.env.MY_QUEUE.sendBatch([
+ // Immediate: Send confirmation email
+ {
+ body: {
+ type: 'send-email',
+ template: 'order-confirmation',
+ to: order.email,
+ orderId: order.orderId,
+ },
+ },
+
+ // Immediate: Update inventory
+ {
+ body: {
+ type: 'update-inventory',
+ items: order.items,
+ orderId: order.orderId,
+ },
+ },
+
+ // Delayed: Send shipping notification (estimated 2 hours)
+ {
+ body: {
+ type: 'send-email',
+ template: 'shipping-notification',
+ to: order.email,
+ orderId: order.orderId,
+ },
+ delaySeconds: 2 * 60 * 60, // 2 hours
+ },
+
+ // Delayed: Request review (3 days later)
+ {
+ body: {
+ type: 'send-email',
+ template: 'review-request',
+ to: order.email,
+ orderId: order.orderId,
+ },
+ delaySeconds: 3 * 24 * 60 * 60, // 3 days
+ },
+ ]);
+
+ return c.json({
+ status: 'success',
+ orderId: order.orderId,
+ tasksQueued: 4,
+ });
+});
+
+// ============================================================================
+// Webhook Handler Example
+// ============================================================================
+
+app.post('/webhooks/:service', async (c) => {
+ const service = c.req.param('service');
+ const payload = await c.req.json();
+
+ // Queue webhook for async processing
+ await c.env.MY_QUEUE.send({
+ type: 'webhook',
+ service,
+ payload,
+ receivedAt: Date.now(),
+ });
+
+ // Respond immediately (don't block webhook)
+ return c.json({ received: true }, 200);
+});
+
+// ============================================================================
+// Health Check
+// ============================================================================
+
+app.get('/health', (c) => {
+ return c.json({ status: 'ok' });
+});
+
+export default app;
diff --git a/skills/cloudflare-queues/templates/queues-retry-with-delay.ts b/skills/cloudflare-queues/templates/queues-retry-with-delay.ts
new file mode 100644
index 00000000..dc941019
--- /dev/null
+++ b/skills/cloudflare-queues/templates/queues-retry-with-delay.ts
@@ -0,0 +1,241 @@
+/**
+ * Queue Consumer with Exponential Backoff Retry
+ *
+ * Use when: Calling rate-limited APIs or handling temporary failures
+ *
+ * Strategy:
+ * - Retry with increasing delays: 1m β†’ 2m β†’ 4m β†’ 8m β†’ ...
+ * - Different delays for different error types
+ * - Max delay cap to prevent excessive waits
+ *
+ * Setup:
+ * 1. Create queue: npx wrangler queues create api-tasks
+ * 2. Create DLQ: npx wrangler queues create api-tasks-dlq
+ * 3. Configure consumer with higher max_retries (e.g., 10)
+ * 4. Deploy: npm run deploy
+ */
+
+type Env = {
+ DB: D1Database;
+ API_KEY: string;
+};
+
+export default {
+ async queue(
+ batch: MessageBatch,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<void> {
+ console.log(`Processing batch of ${batch.messages.length} messages`);
+
+ for (const message of batch.messages) {
+ try {
+ await processWithRetry(message, env);
+ message.ack();
+ } catch (error) {
+ await handleError(message, error);
+ }
+ }
+ },
+};
+
+/**
+ * Process message with smart retry logic
+ */
+async function processWithRetry(message: Message, env: Env) {
+ const { type, data } = message.body;
+
+ console.log(`Processing ${type} (attempt ${message.attempts})`);
+
+ switch (type) {
+ case 'call-api':
+ await callExternalAPI(data, message.attempts);
+ break;
+
+ case 'process-webhook':
+ await processWebhook(data);
+ break;
+
+ default:
+ throw new Error(`Unknown message type: ${type}`);
+ }
+}
+
+/**
+ * Call external API with retry handling
+ */
+async function callExternalAPI(data: any, attempts: number) {
+ const response = await fetch(data.url, {
+ method: data.method || 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...data.headers,
+ },
+ body: JSON.stringify(data.payload),
+ });
+
+ // Handle different response codes
+ if (response.ok) {
+ console.log(`βœ… API call successful`);
+ return await response.json();
+ }
+
+ // Rate limiting
+ if (response.status === 429) {
+ const retryAfter = response.headers.get('Retry-After');
+ const delaySeconds = retryAfter ? parseInt(retryAfter) : undefined;
+
+ throw new RateLimitError('Rate limited', delaySeconds, attempts);
+ }
+
+ // Server errors (500-599) - retry
+ if (response.status >= 500) {
+ throw new ServerError(`Server error: ${response.status}`, attempts);
+ }
+
+ // Client errors (400-499) - don't retry
+ if (response.status >= 400) {
+ const error = await response.text();
+ throw new ClientError(`Client error: ${error}`);
+ }
+
+ throw new Error(`Unexpected response: ${response.status}`);
+}
+
+/**
+ * Process webhook with timeout
+ */
+async function processWebhook(data: any) {
+ // Simulate processing
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ console.log(`Webhook processed: ${data.id}`);
+}
+
+/**
+ * Handle errors with appropriate retry strategy
+ */
+async function handleError(message: Message, error: any) {
+ console.error(`Error processing message ${message.id}:`, error);
+
+ // Rate limit error - use suggested delay or exponential backoff
+ if (error instanceof RateLimitError) {
+ const delaySeconds = error.suggestedDelay || calculateExponentialBackoff(
+ message.attempts,
+ 60, // Base delay: 1 minute
+ 3600 // Max delay: 1 hour
+ );
+
+ console.log(`⏰ Rate limited. Retrying in ${delaySeconds}s (attempt ${message.attempts})`);
+
+ message.retry({ delaySeconds });
+ return;
+ }
+
+ // Server error - exponential backoff
+ if (error instanceof ServerError) {
+ const delaySeconds = calculateExponentialBackoff(
+ message.attempts,
+ 30, // Base delay: 30 seconds
+ 1800 // Max delay: 30 minutes
+ );
+
+ console.log(`πŸ”„ Server error. Retrying in ${delaySeconds}s (attempt ${message.attempts})`);
+
+ message.retry({ delaySeconds });
+ return;
+ }
+
+ // Client error - don't retry (will go to DLQ)
+ if (error instanceof ClientError) {
+ console.error(`❌ Client error. Not retrying: ${error.message}`);
+ // Don't call ack() or retry() - will fail and go to DLQ
+ return;
+ }
+
+ // Unknown error - retry with exponential backoff
+ const delaySeconds = calculateExponentialBackoff(
+ message.attempts,
+ 60, // Base delay: 1 minute
+ 7200 // Max delay: 2 hours
+ );
+
+ console.log(`⚠️ Unknown error. Retrying in ${delaySeconds}s (attempt ${message.attempts})`);
+
+ message.retry({ delaySeconds });
+}
+
+/**
+ * Calculate exponential backoff delay
+ *
+ * Formula: min(baseDelay * 2^(attempts-1), maxDelay)
+ *
+ * Example (baseDelay=60, maxDelay=3600):
+ * - Attempt 1: 60s (1 min)
+ * - Attempt 2: 120s (2 min)
+ * - Attempt 3: 240s (4 min)
+ * - Attempt 4: 480s (8 min)
+ * - Attempt 5: 960s (16 min)
+ * - Attempt 6: 1920s (32 min)
+ * - Attempt 7+: 3600s (1 hour) - capped
+ */
+function calculateExponentialBackoff(
+ attempts: number,
+ baseDelay: number,
+ maxDelay: number
+): number {
+ const delay = baseDelay * Math.pow(2, attempts - 1);
+ return Math.min(delay, maxDelay);
+}
+
+/**
+ * Calculate jittered backoff (prevents thundering herd)
+ *
+ * Adds randomness to delay to spread out retries
+ */
+function calculateJitteredBackoff(
+ attempts: number,
+ baseDelay: number,
+ maxDelay: number
+): number {
+ const exponentialDelay = baseDelay * Math.pow(2, attempts - 1);
+ const delay = Math.min(exponentialDelay, maxDelay);
+
+ // Add jitter: Β±25% randomness
+ const jitter = delay * 0.25 * (Math.random() * 2 - 1);
+
+ return Math.floor(delay + jitter);
+}
+
+// ============================================================================
+// Custom Error Classes
+// ============================================================================
+
+class RateLimitError extends Error {
+ suggestedDelay?: number;
+ attempts: number;
+
+ constructor(message: string, suggestedDelay?: number, attempts: number = 1) {
+ super(message);
+ this.name = 'RateLimitError';
+ this.suggestedDelay = suggestedDelay;
+ this.attempts = attempts;
+ }
+}
+
+class ServerError extends Error {
+ attempts: number;
+
+ constructor(message: string, attempts: number = 1) {
+ super(message);
+ this.name = 'ServerError';
+ this.attempts = attempts;
+ }
+}
+
+class ClientError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'ClientError';
+ }
+}
diff --git a/skills/cloudflare-queues/templates/wrangler-queues-config.jsonc b/skills/cloudflare-queues/templates/wrangler-queues-config.jsonc
new file mode 100644
index 00000000..2305f6a8
--- /dev/null
+++ b/skills/cloudflare-queues/templates/wrangler-queues-config.jsonc
@@ -0,0 +1,57 @@
+{
+ "name": "my-worker",
+ "main": "src/index.ts",
+ "compatibility_date": "2025-10-11",
+
+ // Queue Bindings Configuration
+ "queues": {
+
+ // Producer Configuration (send messages TO queues)
+ "producers": [
+ {
+ "binding": "MY_QUEUE", // Available as env.MY_QUEUE in code
+ "queue": "my-queue", // Queue name (must be created first)
+ "delivery_delay": 0 // Optional: delay all messages (0-43200 seconds)
+ },
+ {
+ "binding": "HIGH_PRIORITY_QUEUE",
+ "queue": "high-priority-queue"
+ },
+ {
+ "binding": "LOW_PRIORITY_QUEUE",
+ "queue": "low-priority-queue",
+ "delivery_delay": 60 // Delay all messages by 1 minute
+ }
+ ],
+
+ // Consumer Configuration (receive messages FROM queues)
+ "consumers": [
+ {
+ "queue": "my-queue", // Queue to consume from
+ "max_batch_size": 10, // Max messages per batch (1-100, default: 10)
+ "max_batch_timeout": 5, // Max seconds to wait (0-60, default: 5)
+ "max_retries": 3, // Max retry attempts (0-100, default: 3)
+ "dead_letter_queue": "my-dlq", // Optional: where failed messages go
+ "retry_delay": 0, // Optional: delay retries (seconds)
+ "max_concurrency": null // Optional: limit concurrent consumers (default: auto-scale to 250)
+ },
+ {
+ "queue": "high-priority-queue",
+ "max_batch_size": 50, // Larger batches for high volume
+ "max_batch_timeout": 1, // Low latency
+ "max_retries": 5,
+ "dead_letter_queue": "priority-dlq"
+ },
+ {
+ "queue": "my-dlq", // Consumer for dead letter queue
+ "max_batch_size": 10,
+ "max_batch_timeout": 30 // Can wait longer for DLQ
+ }
+ ]
+ },
+
+ // Optional: Increase CPU limit for long-running consumers
+ "limits": {
+ "cpu_ms": 30000 // 30 seconds (default). Can be increased to 300000 (5 minutes)
+ }
+}
diff --git a/skills/cloudflare-workers-ai/README.md b/skills/cloudflare-workers-ai/README.md
new file mode 100644
index 00000000..23071dc9
--- /dev/null
+++ b/skills/cloudflare-workers-ai/README.md
@@ -0,0 +1,192 @@
+# Cloudflare Workers AI
+
+Complete knowledge domain for Cloudflare Workers AI - Run AI models on serverless GPUs across Cloudflare's global network.
+
+---
+
+## Auto-Trigger Keywords
+
+### Primary Keywords
+- workers ai
+- cloudflare ai
+- ai bindings
+- llm workers
+- @cf/meta/llama
+- workers ai models
+- ai inference
+- cloudflare llm
+
+### Secondary Keywords
+- ai streaming
+- text generation ai
+- ai embeddings
+- image generation ai
+- workers ai rag
+- ai gateway
+- llama workers
+- flux image generation
+- stable diffusion workers
+- vision models ai
+- ai chat completion
+
+### Error-Based Keywords
+- AI_ERROR
+- rate limit ai
+- model not found
+- token limit exceeded
+- neurons exceeded
+- ai quota exceeded
+- streaming failed
+- model unavailable
+
+### Framework Integration Keywords
+- workers ai hono
+- ai gateway workers
+- vercel ai sdk workers
+- openai compatible workers
+- workers ai vectorize
+- ai bindings wrangler
+- workers ai streaming
+
+---
+
+## What This Skill Does
+
+This skill provides complete Workers AI knowledge including:
+
+- βœ… **Text Generation (LLMs)** - Llama 3.1/3.2, Qwen, Mistral, DeepSeek (50+ models)
+- βœ… **Streaming Responses** - Real-time text generation without buffering
+- βœ… **Text Embeddings** - BGE models for RAG and semantic search
+- βœ… **Image Generation** - Flux, Stable Diffusion XL for text-to-image
+- βœ… **Vision Models** - Llama 3.2 Vision for image understanding
+- βœ… **AI Gateway Integration** - Caching, logging, and cost tracking
+- βœ… **OpenAI Compatibility** - Drop-in replacement for OpenAI API
+- βœ… **RAG Patterns** - Complete Retrieval Augmented Generation examples
+- βœ… **Function Calling** - Embedded function calling with tools
+- βœ… **Vercel AI SDK** - Integration with workers-ai-provider
+
+---
+
+## Known Issues Prevented
+
+| Issue | Description | Prevention |
+|-------|-------------|------------|
+| **Rate limit errors (429)** | Text generation exceeds 300 req/min | Implement exponential backoff retry |
+| **Response buffering** | Large responses timeout without streaming | Always use `stream: true` for text generation |
+| **Token limit exceeded** | Input exceeds model context window | Validate prompt length before inference |
+| **Model not found** | Invalid model ID | Use correct @cf/ or @hf/ prefixes from catalog |
+| **Missing cost tracking** | Production costs unmonitored | Always use AI Gateway for logging |
+| **Free tier exhaustion** | Exceeds 10,000 neurons/day | Plan for Workers Paid ($0.011/1000 neurons) |
+
+---
+
+## Quick Example
+
+```typescript
+import { Hono } from 'hono';
+
+type Bindings = {
+ AI: Ai;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// Text generation with streaming
+app.post('/chat', async (c) => {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const stream = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ stream: true,
+ }
+ );
+
+ return new Response(stream, {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+});
+
+export default app;
+```
+
+**wrangler.jsonc:**
+```jsonc
+{
+ "ai": {
+ "binding": "AI"
+ }
+}
+```
+
+---
+
+## Token Efficiency
+
+**Without this skill:**
+- 15-20 documentation lookups for model selection
+- 10+ searches for rate limits and pricing
+- 8-12 examples for different task types
+- ~8,000 tokens of repetitive context
+
+**With this skill:**
+- 1 skill invocation with complete knowledge
+- ~3,200 tokens of focused, battle-tested patterns
+- **~60% token savings**
+
+---
+
+## Coverage
+
+### Models Catalog
+- **Text Generation**: 20+ LLMs (Llama, Qwen, Mistral, DeepSeek, Gemma)
+- **Text Embeddings**: BGE-base, BGE-large, BGE-small
+- **Image Generation**: Flux, Stable Diffusion XL, DreamShaper
+- **Vision Models**: Llama 3.2 11B Vision Instruct
+- **Translation**: M2M100, Opus MT
+- **Classification**: DistilBERT, RoBERTa
+- **Speech Recognition**: Whisper models
+
+### Patterns
+- Chat completions with message history
+- RAG (Retrieval Augmented Generation)
+- Structured output with Zod schemas
+- Function calling with tools
+- Image generation and storage
+- Vision model image understanding
+- AI Gateway caching and logging
+
+### Production Topics
+- Rate limits by task type
+- Neurons-based pricing
+- Streaming best practices
+- Error handling strategies
+- OpenAI API compatibility
+- Vercel AI SDK integration
+- Cost optimization
+
+---
+
+## When to Use This Skill
+
+Use this skill when you see keywords like:
+- "integrate Workers AI"
+- "add LLM to my Worker"
+- "generate embeddings for RAG"
+- "create AI image generator"
+- "stream AI responses"
+- "setup AI Gateway"
+- "OpenAI compatible API"
+- "model rate limit"
+- "Workers AI pricing"
+
+---
+
+## References
+
+- [Workers AI Documentation](https://developers.cloudflare.com/workers-ai/)
+- [Models Catalog](https://developers.cloudflare.com/workers-ai/models/)
+- [AI Gateway](https://developers.cloudflare.com/ai-gateway/)
+- [Pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/)
+- [Rate Limits](https://developers.cloudflare.com/workers-ai/platform/limits/)
diff --git a/skills/cloudflare-workers-ai/SKILL.md b/skills/cloudflare-workers-ai/SKILL.md
new file mode 100644
index 00000000..e4e16842
--- /dev/null
+++ b/skills/cloudflare-workers-ai/SKILL.md
@@ -0,0 +1,605 @@
+# Cloudflare Workers AI - Complete Reference
+
+Production-ready knowledge domain for building AI-powered applications with Cloudflare Workers AI.
+
+---
+
+## Table of Contents
+
+1. [Quick Start (5 minutes)](#quick-start-5-minutes)
+2. [Workers AI API Reference](#workers-ai-api-reference)
+3. [Model Selection Guide](#model-selection-guide)
+4. [Common Patterns](#common-patterns)
+5. [AI Gateway Integration](#ai-gateway-integration)
+6. [Rate Limits & Pricing](#rate-limits--pricing)
+7. [Production Checklist](#production-checklist)
+
+---
+
+## Quick Start (5 minutes)
+
+### 1. Add AI Binding
+
+**wrangler.jsonc:**
+```jsonc
+{
+ "ai": {
+ "binding": "AI"
+ }
+}
+```
+
+### 2. Run Your First Model
+
+```typescript
+export interface Env {
+ AI: Ai;
+}
+
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ prompt: 'What is Cloudflare?',
+ });
+
+ return Response.json(response);
+ },
+};
+```
+
+### 3. Add Streaming (Recommended)
+
+```typescript
+const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [{ role: 'user', content: 'Tell me a story' }],
+ stream: true, // Always use streaming for text generation!
+});
+
+return new Response(stream, {
+ headers: { 'content-type': 'text/event-stream' },
+});
+```
+
+**Why streaming?**
+- Prevents buffering large responses in memory
+- Faster time-to-first-token
+- Better user experience for long-form content
+- Avoids Worker timeout issues
+
+---
+
+## Workers AI API Reference
+
+### `env.AI.run()`
+
+Run an AI model inference.
+
+**Signature:**
+```typescript
+async env.AI.run(
+ model: string,
+ inputs: ModelInputs,
+ options?: { gateway?: { id: string; skipCache?: boolean } }
+): Promise<ModelOutput | ReadableStream>
+```
+
+**Parameters:**
+
+- `model` (string, required) - Model ID (e.g., `@cf/meta/llama-3.1-8b-instruct`)
+- `inputs` (object, required) - Model-specific inputs
+- `options` (object, optional) - Additional options
+ - `gateway` (object) - AI Gateway configuration
+ - `id` (string) - Gateway ID
+ - `skipCache` (boolean) - Skip AI Gateway cache
+
+**Returns:**
+
+- Non-streaming: `Promise<ModelOutput>` - JSON response
+- Streaming: `ReadableStream` - Server-sent events stream
+
+---
+
+### Text Generation Models
+
+**Input Format:**
+```typescript
+{
+ messages?: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;
+ prompt?: string; // Deprecated, use messages
+ stream?: boolean; // Default: false
+ max_tokens?: number; // Max tokens to generate
+ temperature?: number; // 0.0-1.0, default varies by model
+ top_p?: number; // 0.0-1.0
+ top_k?: number;
+}
+```
+
+**Output Format (Non-Streaming):**
+```typescript
+{
+ response: string; // Generated text
+}
+```
+
+**Example:**
+```typescript
+const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ { role: 'system', content: 'You are a helpful assistant.' },
+ { role: 'user', content: 'What is TypeScript?' },
+ ],
+ stream: false,
+});
+
+console.log(response.response);
+```
+
+---
+
+### Text Embeddings Models
+
+**Input Format:**
+```typescript
+{
+ text: string | string[]; // Single text or array of texts
+}
+```
+
+**Output Format:**
+```typescript
+{
+ shape: number[]; // [batch_size, embedding_dimensions]
+ data: number[][]; // Array of embedding vectors
+}
+```
+
+**Example:**
+```typescript
+const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: ['Hello world', 'Cloudflare Workers'],
+});
+
+console.log(embeddings.shape); // [2, 768]
+console.log(embeddings.data[0]); // [0.123, -0.456, ...]
+```
+
+---
+
+### Image Generation Models
+
+**Input Format:**
+```typescript
+{
+ prompt: string; // Text description
+ num_steps?: number; // Default: 20
+ guidance?: number; // CFG scale, default: 7.5
+ strength?: number; // For img2img, default: 1.0
+ image?: number[][]; // For img2img (base64 or array)
+}
+```
+
+**Output Format:**
+- Binary image data (PNG/JPEG)
+
+**Example:**
+```typescript
+const imageStream = await env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
+ prompt: 'A beautiful sunset over mountains',
+});
+
+return new Response(imageStream, {
+ headers: { 'content-type': 'image/png' },
+});
+```
+
+---
+
+### Vision Models
+
+**Input Format:**
+```typescript
+{
+ messages: Array<{
+ role: 'user' | 'assistant';
+ content: Array<{ type: 'text' | 'image_url'; text?: string; image_url?: { url: string } }>;
+ }>;
+}
+```
+
+**Example:**
+```typescript
+const response = await env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'What is in this image?' },
+ { type: 'image_url', image_url: { url: 'data:image/png;base64,iVBOR...' } },
+ ],
+ },
+ ],
+});
+```
+
+---
+
+## Model Selection Guide
+
+### Text Generation (LLMs)
+
+| Model | Best For | Rate Limit | Size |
+|-------|----------|------------|------|
+| `@cf/meta/llama-3.1-8b-instruct` | General purpose, fast | 300/min | 8B |
+| `@cf/meta/llama-3.2-1b-instruct` | Ultra-fast, simple tasks | 300/min | 1B |
+| `@cf/qwen/qwen1.5-14b-chat-awq` | High quality, complex reasoning | 150/min | 14B |
+| `@cf/deepseek-ai/deepseek-r1-distill-qwen-32b` | Coding, technical content | 300/min | 32B |
+| `@hf/thebloke/mistral-7b-instruct-v0.1-awq` | Fast, efficient | 400/min | 7B |
+
+### Text Embeddings
+
+| Model | Dimensions | Best For | Rate Limit |
+|-------|-----------|----------|------------|
+| `@cf/baai/bge-base-en-v1.5` | 768 | General purpose RAG | 3000/min |
+| `@cf/baai/bge-large-en-v1.5` | 1024 | High accuracy search | 1500/min |
+| `@cf/baai/bge-small-en-v1.5` | 384 | Fast, low storage | 3000/min |
+
+### Image Generation
+
+| Model | Best For | Rate Limit | Speed |
+|-------|----------|------------|-------|
+| `@cf/black-forest-labs/flux-1-schnell` | High quality, photorealistic | 720/min | Fast |
+| `@cf/stabilityai/stable-diffusion-xl-base-1.0` | General purpose | 720/min | Medium |
+| `@cf/lykon/dreamshaper-8-lcm` | Artistic, stylized | 720/min | Fast |
+
+### Vision Models
+
+| Model | Best For | Rate Limit |
+|-------|----------|------------|
+| `@cf/meta/llama-3.2-11b-vision-instruct` | Image understanding | 720/min |
+| `@cf/unum/uform-gen2-qwen-500m` | Fast image captioning | 720/min |
+
+---
+
+## Common Patterns
+
+### Pattern 1: Chat Completion with History
+
+```typescript
+app.post('/chat', async (c) => {
+ const { messages } = await c.req.json<{
+ messages: Array<{ role: string; content: string }>;
+ }>();
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages,
+ stream: true,
+ });
+
+ return new Response(response, {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+});
+```
+
+---
+
+### Pattern 2: RAG (Retrieval Augmented Generation)
+
+```typescript
+// Step 1: Generate embeddings
+const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: [userQuery],
+});
+
+const vector = embeddings.data[0];
+
+// Step 2: Search Vectorize
+const matches = await env.VECTORIZE.query(vector, { topK: 3 });
+
+// Step 3: Build context from matches
+const context = matches.matches.map((m) => m.metadata.text).join('\n\n');
+
+// Step 4: Generate response with context
+const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'system',
+ content: `Answer using this context:\n${context}`,
+ },
+ { role: 'user', content: userQuery },
+ ],
+ stream: true,
+});
+
+return new Response(response, {
+ headers: { 'content-type': 'text/event-stream' },
+});
+```
+
+---
+
+### Pattern 3: Structured Output with Zod
+
+```typescript
+import { z } from 'zod';
+
+const RecipeSchema = z.object({
+ name: z.string(),
+ ingredients: z.array(z.string()),
+ instructions: z.array(z.string()),
+ prepTime: z.number(),
+});
+
+app.post('/recipe', async (c) => {
+ const { dish } = await c.req.json<{ dish: string }>();
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: `Generate a recipe for ${dish}. Return ONLY valid JSON matching this schema: ${JSON.stringify(RecipeSchema.shape)}`,
+ },
+ ],
+ });
+
+ // Parse and validate
+ const recipe = RecipeSchema.parse(JSON.parse(response.response));
+
+ return c.json(recipe);
+});
+```
+
+---
+
+### Pattern 4: Image Generation + R2 Storage
+
+```typescript
+app.post('/generate-image', async (c) => {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ // Generate image
+ const imageStream = await c.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
+ prompt,
+ });
+
+ const imageBytes = await new Response(imageStream).bytes();
+
+ // Store in R2
+ const key = `images/${Date.now()}.png`;
+ await c.env.BUCKET.put(key, imageBytes, {
+ httpMetadata: { contentType: 'image/png' },
+ });
+
+ return c.json({
+ success: true,
+ url: `https://your-domain.com/${key}`,
+ });
+});
+```
+
+---
+
+## AI Gateway Integration
+
+AI Gateway provides caching, logging, and analytics for AI requests.
+
+**Setup:**
+```typescript
+const response = await env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ { prompt: 'Hello' },
+ {
+ gateway: {
+ id: 'my-gateway', // Your gateway ID
+ skipCache: false, // Use cache
+ },
+ }
+);
+```
+
+**Benefits:**
+- βœ… **Cost Tracking** - Monitor neurons usage per request
+- βœ… **Caching** - Reduce duplicate inference costs
+- βœ… **Logging** - Debug and analyze AI requests
+- βœ… **Rate Limiting** - Additional layer of protection
+- βœ… **Analytics** - Request patterns and performance
+
+**Access Gateway Logs:**
+```typescript
+const gateway = env.AI.gateway('my-gateway');
+const logId = env.AI.aiGatewayLogId;
+
+// Send feedback
+await gateway.patchLog(logId, {
+ feedback: { rating: 1, comment: 'Great response' },
+});
+```
+
+---
+
+## Rate Limits & Pricing
+
+### Rate Limits (per minute)
+
+| Task Type | Default Limit | Notes |
+|-----------|---------------|-------|
+| **Text Generation** | 300/min | Some fast models: 400-1500/min |
+| **Text Embeddings** | 3000/min | BGE-large: 1500/min |
+| **Image Generation** | 720/min | All image models |
+| **Vision Models** | 720/min | Image understanding |
+| **Translation** | 720/min | M2M100, Opus MT |
+| **Classification** | 2000/min | Text classification |
+| **Speech Recognition** | 720/min | Whisper models |
+
+### Pricing (Neurons-Based)
+
+**Free Tier:**
+- 10,000 neurons per day
+- Resets daily at 00:00 UTC
+
+**Paid Tier:**
+- $0.011 per 1,000 neurons
+- 10,000 neurons/day included
+- Unlimited usage above free allocation
+
+**Example Costs:**
+
+| Model | Input (1M tokens) | Output (1M tokens) |
+|-------|-------------------|-------------------|
+| Llama 3.2 1B | $0.027 | $0.201 |
+| Llama 3.1 8B | $0.088 | $0.606 |
+| BGE-base embeddings | $0.005 | N/A |
+| Flux image generation | ~$0.011/image | N/A |
+
+---
+
+## Production Checklist
+
+### Before Deploying
+
+- [ ] **Enable AI Gateway** for cost tracking and logging
+- [ ] **Implement streaming** for all text generation endpoints
+- [ ] **Add rate limit retry** with exponential backoff
+- [ ] **Validate input length** to prevent token limit errors
+- [ ] **Set appropriate timeouts** (Workers: 30s CPU default, 5m max)
+- [ ] **Monitor neurons usage** in Cloudflare dashboard
+- [ ] **Test error handling** for model unavailable, rate limits
+- [ ] **Add input sanitization** to prevent prompt injection
+- [ ] **Configure CORS** if using from browser
+- [ ] **Plan for scale** - upgrade to Paid plan if needed
+
+### Error Handling
+
+```typescript
+async function runAIWithRetry(
+ env: Env,
+ model: string,
+ inputs: any,
+ maxRetries = 3
+): Promise<any> {
+ let lastError: Error;
+
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ return await env.AI.run(model, inputs);
+ } catch (error) {
+ lastError = error as Error;
+ const message = lastError.message.toLowerCase();
+
+ // Rate limit - retry with backoff
+ if (message.includes('429') || message.includes('rate limit')) {
+ const delay = Math.pow(2, i) * 1000; // Exponential backoff
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ continue;
+ }
+
+ // Other errors - throw immediately
+ throw error;
+ }
+ }
+
+ throw lastError!;
+}
+```
+
+### Monitoring
+
+```typescript
+app.use('*', async (c, next) => {
+ const start = Date.now();
+
+ await next();
+
+ // Log AI usage
+ console.log({
+ path: c.req.path,
+ duration: Date.now() - start,
+ logId: c.env.AI.aiGatewayLogId,
+ });
+});
+```
+
+---
+
+## OpenAI Compatibility
+
+Workers AI supports OpenAI-compatible endpoints.
+
+**Using OpenAI SDK:**
+```typescript
+import OpenAI from 'openai';
+
+const openai = new OpenAI({
+ apiKey: env.CLOUDFLARE_API_KEY,
+ baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/ai/v1`,
+});
+
+// Chat completions
+const completion = await openai.chat.completions.create({
+ model: '@cf/meta/llama-3.1-8b-instruct',
+ messages: [{ role: 'user', content: 'Hello!' }],
+});
+
+// Embeddings
+const embeddings = await openai.embeddings.create({
+ model: '@cf/baai/bge-base-en-v1.5',
+ input: 'Hello world',
+});
+```
+
+**Endpoints:**
+- `/v1/chat/completions` - Text generation
+- `/v1/embeddings` - Text embeddings
+
+---
+
+## Vercel AI SDK Integration
+
+```bash
+npm install workers-ai-provider ai
+```
+
+```typescript
+import { createWorkersAI } from 'workers-ai-provider';
+import { generateText, streamText } from 'ai';
+
+const workersai = createWorkersAI({ binding: env.AI });
+
+// Generate text
+const result = await generateText({
+ model: workersai('@cf/meta/llama-3.1-8b-instruct'),
+ prompt: 'Write a poem',
+});
+
+// Stream text
+const stream = streamText({
+ model: workersai('@cf/meta/llama-3.1-8b-instruct'),
+ prompt: 'Tell me a story',
+});
+```
+
+---
+
+## Limits Summary
+
+| Feature | Limit |
+|---------|-------|
+| Concurrent requests | No hard limit (rate limits apply) |
+| Max input tokens | Varies by model (typically 2K-128K) |
+| Max output tokens | Varies by model (typically 512-2048) |
+| Streaming chunk size | ~1 KB |
+| Image size (output) | ~5 MB |
+| Request timeout | Workers timeout applies (30s default, 5m max CPU) |
+| Daily free neurons | 10,000 |
+| Rate limits | See "Rate Limits & Pricing" section |
+
+---
+
+## References
+
+- [Workers AI Docs](https://developers.cloudflare.com/workers-ai/)
+- [Models Catalog](https://developers.cloudflare.com/workers-ai/models/)
+- [AI Gateway](https://developers.cloudflare.com/ai-gateway/)
+- [Pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/)
+- [Limits](https://developers.cloudflare.com/workers-ai/platform/limits/)
+- [REST API](https://developers.cloudflare.com/workers-ai/get-started/rest-api/)
diff --git a/skills/cloudflare-workers-ai/reference/best-practices.md b/skills/cloudflare-workers-ai/reference/best-practices.md
new file mode 100644
index 00000000..c488bf87
--- /dev/null
+++ b/skills/cloudflare-workers-ai/reference/best-practices.md
@@ -0,0 +1,524 @@
+# Cloudflare Workers AI - Best Practices
+
+Production-tested patterns for building reliable, cost-effective AI applications with Workers AI.
+
+---
+
+## Table of Contents
+
+1. [Streaming Best Practices](#streaming-best-practices)
+2. [Error Handling](#error-handling)
+3. [Cost Optimization](#cost-optimization)
+4. [Performance Optimization](#performance-optimization)
+5. [Security](#security)
+6. [Monitoring & Observability](#monitoring--observability)
+7. [Production Checklist](#production-checklist)
+
+---
+
+## Streaming Best Practices
+
+### Why Streaming is Essential
+
+**❌ Without streaming:**
+- Buffers entire response in memory
+- Higher latency (wait for complete response)
+- Risk of Worker timeout (30s default)
+- Poor user experience for long content
+
+**βœ… With streaming:**
+- Immediate first token
+- Lower memory usage
+- Better UX (progressive rendering)
+- No timeout issues
+
+### Implementation
+
+```typescript
+// Always use stream: true for text generation
+const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [{ role: 'user', content: prompt }],
+ stream: true, // CRITICAL
+});
+
+return new Response(stream, {
+ headers: { 'content-type': 'text/event-stream' },
+});
+```
+
+### Client-Side Handling
+
+```typescript
+const response = await fetch('/api/chat', {
+ method: 'POST',
+ body: JSON.stringify({ prompt }),
+});
+
+const reader = response.body.getReader();
+const decoder = new TextDecoder();
+
+while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ // Update UI with chunk
+}
+```
+
+---
+
+## Error Handling
+
+### 1. Rate Limit Errors (429)
+
+**Pattern: Exponential Backoff**
+
+```typescript
+async function runWithRetry(
+ ai: Ai,
+ model: string,
+ inputs: any,
+ maxRetries = 3
+): Promise<any> {
+ let delay = 1000;
+
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ return await ai.run(model, inputs);
+ } catch (error) {
+ const message = (error as Error).message.toLowerCase();
+
+ if (message.includes('429') || message.includes('rate limit')) {
+ if (i < maxRetries - 1) {
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ delay *= 2; // Exponential backoff: 1s, 2s, 4s
+ continue;
+ }
+ }
+
+ throw error;
+ }
+ }
+}
+```
+
+### 2. Model Unavailable
+
+**Pattern: Fallback Models**
+
+```typescript
+const models = [
+ '@cf/meta/llama-3.1-8b-instruct', // Primary
+ '@cf/meta/llama-3.2-1b-instruct', // Fallback (faster)
+ '@cf/qwen/qwen1.5-7b-chat-awq', // Fallback (alternative)
+];
+
+async function runWithFallback(ai: Ai, inputs: any): Promise<any> {
+ for (const model of models) {
+ try {
+ return await ai.run(model, inputs);
+ } catch (error) {
+ const message = (error as Error).message.toLowerCase();
+ if (!message.includes('unavailable')) throw error;
+ // Try next model
+ }
+ }
+
+ throw new Error('All models unavailable');
+}
+```
+
+### 3. Token Limit Exceeded
+
+**Pattern: Input Validation**
+
+```typescript
+function estimateTokens(text: string): number {
+ return Math.ceil(text.length / 4);
+}
+
+function validateInput(text: string, maxTokens = 2048): void {
+ const tokens = estimateTokens(text);
+
+ if (tokens > maxTokens) {
+ throw new Error(
+ `Input too long: ${tokens} tokens (max: ${maxTokens})`
+ );
+ }
+}
+
+// Usage
+try {
+ validateInput(userInput);
+ const response = await env.AI.run(model, { prompt: userInput });
+} catch (error) {
+ return c.json({ error: (error as Error).message }, 400);
+}
+```
+
+---
+
+## Cost Optimization
+
+### 1. Use AI Gateway for Caching
+
+**Without AI Gateway:**
+- Same prompt = new inference = cost
+
+**With AI Gateway:**
+- Same prompt = cached response = free
+
+```typescript
+const response = await env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ { messages },
+ { gateway: { id: 'my-gateway' } } // Enable caching
+);
+```
+
+**Savings**: 50-90% for repeated queries
+
+### 2. Choose the Right Model
+
+**Cost Comparison** (per 1M output tokens):
+
+| Model | Cost | Use Case |
+|-------|------|----------|
+| Llama 3.2 1B | $0.201 | Simple tasks, high volume |
+| Llama 3.1 8B | $0.606 | General purpose |
+| Qwen 1.5 14B | $1.20+ | Complex reasoning |
+
+**Strategy**: Use smallest model that meets quality requirements
+
+### 3. Limit Output Length
+
+```typescript
+const response = await env.AI.run(model, {
+ messages,
+ max_tokens: 256, // Limit output (default: varies)
+});
+```
+
+### 4. Batch Embeddings
+
+```typescript
+// ❌ Bad: 100 separate requests
+for (const text of texts) {
+ await env.AI.run('@cf/baai/bge-base-en-v1.5', { text: [text] });
+}
+
+// βœ… Good: 1 batch request
+await env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: texts, // Up to 100 texts per request
+});
+```
+
+### 5. Monitor Neurons Usage
+
+```typescript
+app.use('*', async (c, next) => {
+ const start = Date.now();
+ await next();
+
+ console.log({
+ path: c.req.path,
+ duration: Date.now() - start,
+ logId: c.env.AI.aiGatewayLogId, // Check dashboard for neurons
+ });
+});
+```
+
+---
+
+## Performance Optimization
+
+### 1. Use Faster Models When Appropriate
+
+**Speed Ranking** (fastest to slowest):
+
+1. `@cf/qwen/qwen1.5-0.5b-chat` (1500/min limit)
+2. `@cf/meta/llama-3.2-1b-instruct`
+3. `@cf/tinyllama/tinyllama-1.1b-chat-v1.0` (720/min)
+4. `@hf/thebloke/mistral-7b-instruct-v0.1-awq` (400/min)
+5. `@cf/meta/llama-3.1-8b-instruct`
+6. `@cf/qwen/qwen1.5-14b-chat-awq` (150/min)
+
+### 2. Parallel Requests
+
+```typescript
+// Process multiple tasks in parallel
+const [summary, keywords, sentiment] = await Promise.all([
+ env.AI.run(model, { prompt: `Summarize: ${text}` }),
+ env.AI.run(model, { prompt: `Extract keywords: ${text}` }),
+ env.AI.run(model, { prompt: `Sentiment: ${text}` }),
+]);
+```
+
+### 3. Edge Caching for Static Prompts
+
+```typescript
+// Cache AI responses in KV
+const cacheKey = `ai:${hash(prompt)}`;
+
+let response = await env.CACHE.get(cacheKey);
+if (!response) {
+ const result = await env.AI.run(model, { prompt });
+ response = result.response;
+ await env.CACHE.put(cacheKey, response, { expirationTtl: 3600 });
+}
+```
+
+---
+
+## Security
+
+### 1. Never Expose API Keys
+
+**❌ Bad:**
+```typescript
+const openai = new OpenAI({
+ apiKey: 'sk-1234...', // Hardcoded!
+});
+```
+
+**βœ… Good:**
+```typescript
+const openai = new OpenAI({
+ apiKey: env.OPENAI_API_KEY, // Environment variable
+});
+```
+
+### 2. Input Sanitization
+
+```typescript
+function sanitizeInput(text: string): string {
+ // Remove potential prompt injection attempts
+ return text
+ .replace(/\{system\}/gi, '')
+ .replace(/\{assistant\}/gi, '')
+ .trim();
+}
+
+const prompt = sanitizeInput(userInput);
+```
+
+### 3. Rate Limiting Per User
+
+```typescript
+import { RateLimiter } from '@/lib/rate-limiter';
+
+const limiter = new RateLimiter({
+ requests: 10,
+ window: 60, // 10 requests per minute
+});
+
+app.post('/chat', async (c) => {
+ const userId = c.req.header('x-user-id');
+
+ if (!await limiter.check(userId)) {
+ return c.json({ error: 'Rate limit exceeded' }, 429);
+ }
+
+ // Process request...
+});
+```
+
+### 4. Content Filtering
+
+```typescript
+const BLOCKED_PATTERNS = [
+ /generate.*exploit/i,
+ /create.*malware/i,
+ /hack/i,
+];
+
+function isSafePrompt(prompt: string): boolean {
+ return !BLOCKED_PATTERNS.some((pattern) => pattern.test(prompt));
+}
+```
+
+---
+
+## Monitoring & Observability
+
+### 1. Structured Logging
+
+```typescript
+interface AILog {
+ timestamp: string;
+ model: string;
+ duration: number;
+ success: boolean;
+ error?: string;
+ logId?: string;
+}
+
+async function logAIRequest(log: AILog): Promise<void> {
+ console.log(JSON.stringify(log));
+ // Or send to logging service (Datadog, Sentry, etc.)
+}
+```
+
+### 2. Error Tracking
+
+```typescript
+app.onError((err, c) => {
+ console.error({
+ error: err.message,
+ stack: err.stack,
+ path: c.req.path,
+ timestamp: new Date().toISOString(),
+ });
+
+ return c.json({ error: 'Internal server error' }, 500);
+});
+```
+
+### 3. Performance Metrics
+
+```typescript
+const metrics = {
+ requests: 0,
+ errors: 0,
+ totalDuration: 0,
+};
+
+app.use('*', async (c, next) => {
+ metrics.requests++;
+ const start = Date.now();
+
+ try {
+ await next();
+ } catch (error) {
+ metrics.errors++;
+ throw error;
+ } finally {
+ metrics.totalDuration += Date.now() - start;
+ }
+});
+
+app.get('/metrics', (c) => {
+ return c.json({
+ ...metrics,
+ avgDuration: metrics.totalDuration / metrics.requests,
+ errorRate: (metrics.errors / metrics.requests) * 100,
+ });
+});
+```
+
+---
+
+## Production Checklist
+
+### Before Deploying
+
+- [ ] **Streaming enabled** for all text generation endpoints
+- [ ] **AI Gateway configured** for cost tracking and caching
+- [ ] **Error handling** with retry logic for rate limits
+- [ ] **Input validation** to prevent token limit errors
+- [ ] **Rate limiting** implemented per user
+- [ ] **Monitoring** and logging configured
+- [ ] **Model selection** optimized for cost/quality balance
+- [ ] **Fallback models** configured for high availability
+- [ ] **Security** review completed (input sanitization, content filtering)
+- [ ] **Load testing** completed with expected traffic
+- [ ] **Cost estimation** based on expected usage
+- [ ] **Documentation** for API endpoints and error codes
+
+### Cost Planning
+
+**Estimate your costs:**
+
+1. Expected requests/day: _____
+2. Avg tokens per request (input + output): _____
+3. Model neurons cost: _____
+4. Daily neurons = requests Γ— tokens Γ— neurons_per_token
+5. Daily cost = (daily neurons - 10,000 free) / 1,000 Γ— $0.011
+
+**Example:**
+- 10,000 requests/day
+- 500 tokens/request (avg)
+- Llama 3.1 8B: ~50 neurons/1K tokens
+- Daily neurons: 10,000 Γ— 0.5K Γ— 50 = 250,000
+- Daily cost: (250,000 - 10,000) / 1,000 Γ— $0.011 = **$2.64**
+
+### Performance Targets
+
+- **Time to first token**: <500ms
+- **Avg response time**: <2s (streaming)
+- **Error rate**: <1%
+- **Cache hit rate**: >50% (with AI Gateway)
+
+---
+
+## Common Patterns
+
+### 1. RAG Pattern
+
+```typescript
+// 1. Generate query embedding
+const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: [query],
+});
+
+// 2. Search Vectorize
+const results = await env.VECTORIZE.query(embeddings.data[0], {
+ topK: 3,
+});
+
+// 3. Build context
+const context = results.matches.map((m) => m.metadata.text).join('\n\n');
+
+// 4. Generate response with context
+const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ { role: 'system', content: `Context:\n${context}` },
+ { role: 'user', content: query },
+ ],
+ stream: true,
+});
+```
+
+### 2. Multi-Model Consensus
+
+```typescript
+const models = [
+ '@cf/meta/llama-3.1-8b-instruct',
+ '@cf/qwen/qwen1.5-7b-chat-awq',
+ '@hf/thebloke/mistral-7b-instruct-v0.1-awq',
+];
+
+const responses = await Promise.all(
+ models.map((model) => env.AI.run(model, { prompt }))
+);
+
+// Combine or compare responses
+```
+
+### 3. Progressive Enhancement
+
+```typescript
+// Start with fast model, upgrade if needed
+let response = await env.AI.run('@cf/meta/llama-3.2-1b-instruct', {
+ prompt,
+});
+
+// Check quality (length, coherence, etc.)
+if (response.response.length < 50) {
+ // Retry with better model
+ response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ prompt,
+ });
+}
+```
+
+---
+
+## References
+
+- [Workers AI Documentation](https://developers.cloudflare.com/workers-ai/)
+- [AI Gateway](https://developers.cloudflare.com/ai-gateway/)
+- [Pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/)
+- [Limits](https://developers.cloudflare.com/workers-ai/platform/limits/)
+- [Models Catalog](https://developers.cloudflare.com/workers-ai/models/)
diff --git a/skills/cloudflare-workers-ai/reference/models-catalog.md b/skills/cloudflare-workers-ai/reference/models-catalog.md
new file mode 100644
index 00000000..67a3592d
--- /dev/null
+++ b/skills/cloudflare-workers-ai/reference/models-catalog.md
@@ -0,0 +1,245 @@
+# Cloudflare Workers AI - Models Catalog
+
+Complete catalog of Workers AI models organized by task type.
+
+**Last Updated**: 2025-10-21
+**Official Catalog**: https://developers.cloudflare.com/workers-ai/models/
+
+---
+
+## Text Generation (LLMs)
+
+### Meta Llama Models
+
+| Model ID | Size | Best For | Rate Limit |
+|----------|------|----------|------------|
+| `@cf/meta/llama-3.1-8b-instruct` | 8B | General purpose, balanced | 300/min |
+| `@cf/meta/llama-3.1-8b-instruct-fast` | 8B | Faster inference | 300/min |
+| `@cf/meta/llama-3.2-1b-instruct` | 1B | Ultra-fast, simple tasks | 300/min |
+| `@cf/meta/llama-3.2-3b-instruct` | 3B | Fast, good quality | 300/min |
+| `@cf/meta/llama-2-7b-chat-int8` | 7B | Legacy, reliable | 300/min |
+| `@cf/meta/llama-2-13b-chat-awq` | 13B | Higher quality (slower) | 300/min |
+
+### Qwen Models
+
+| Model ID | Size | Best For | Rate Limit |
+|----------|------|----------|------------|
+| `@cf/qwen/qwen1.5-14b-chat-awq` | 14B | High quality, complex reasoning | 150/min |
+| `@cf/qwen/qwen1.5-7b-chat-awq` | 7B | Balanced quality/speed | 300/min |
+| `@cf/qwen/qwen1.5-1.8b-chat` | 1.8B | Fast, lightweight | 720/min |
+| `@cf/qwen/qwen1.5-0.5b-chat` | 0.5B | Ultra-fast, ultra-lightweight | 1500/min |
+
+### Mistral Models
+
+| Model ID | Size | Best For | Rate Limit |
+|----------|------|----------|------------|
+| `@hf/thebloke/mistral-7b-instruct-v0.1-awq` | 7B | Fast, efficient | 400/min |
+| `@hf/thebloke/openhermes-2.5-mistral-7b-awq` | 7B | Instruction following | 300/min |
+
+### DeepSeek Models
+
+| Model ID | Size | Best For | Rate Limit |
+|----------|------|----------|------------|
+| `@cf/deepseek-ai/deepseek-r1-distill-qwen-32b` | 32B | Coding, technical content | 300/min |
+| `@cf/deepseek-ai/deepseek-coder-6.7b-instruct-awq` | 6.7B | Code generation | 300/min |
+
+### Other Models
+
+| Model ID | Size | Best For | Rate Limit |
+|----------|------|----------|------------|
+| `@cf/tinyllama/tinyllama-1.1b-chat-v1.0` | 1.1B | Extremely fast, limited capability | 720/min |
+| `@cf/microsoft/phi-2` | 2.7B | Fast, efficient | 720/min |
+| `@cf/google/gemma-2b-it-lora` | 2B | Instruction tuned | 300/min |
+| `@cf/google/gemma-7b-it-lora` | 7B | Higher quality | 300/min |
+
+---
+
+## Text Embeddings
+
+| Model ID | Dimensions | Best For | Rate Limit |
+|----------|-----------|----------|------------|
+| `@cf/baai/bge-base-en-v1.5` | 768 | General purpose RAG | 3000/min |
+| `@cf/baai/bge-large-en-v1.5` | 1024 | High accuracy search | 1500/min |
+| `@cf/baai/bge-small-en-v1.5` | 384 | Fast, low storage | 3000/min |
+| `@cf/baai/bge-m3` | 1024 | Multilingual | 3000/min |
+
+**Use Case**: RAG, semantic search, similarity detection, clustering
+
+---
+
+## Image Generation
+
+| Model ID | Type | Best For | Rate Limit |
+|----------|------|----------|------------|
+| `@cf/black-forest-labs/flux-1-schnell` | Text-to-Image | Photorealistic, high quality | 720/min |
+| `@cf/stabilityai/stable-diffusion-xl-base-1.0` | Text-to-Image | General purpose | 720/min |
+| `@cf/lykon/dreamshaper-8-lcm` | Text-to-Image | Artistic, stylized | 720/min |
+| `@cf/runwayml/stable-diffusion-v1-5-img2img` | Image-to-Image | Transform images | 1500/min |
+| `@cf/runwayml/stable-diffusion-v1-5-inpainting` | Inpainting | Edit specific areas | 1500/min |
+| `@cf/bytedance/stable-diffusion-xl-lightning` | Text-to-Image | Fast generation | 720/min |
+
+**Output**: PNG images (~5 MB max)
+
+---
+
+## Vision Models
+
+| Model ID | Task | Best For | Rate Limit |
+|----------|------|----------|------------|
+| `@cf/meta/llama-3.2-11b-vision-instruct` | Image Understanding | Q&A, captioning, analysis | 720/min |
+| `@cf/unum/uform-gen2-qwen-500m` | Image Captioning | Fast captions | 720/min |
+
+**Input**: Base64-encoded images
+
+---
+
+## Translation
+
+| Model ID | Languages | Rate Limit |
+|----------|-----------|------------|
+| `@cf/meta/m2m100-1.2b` | 100+ languages | 720/min |
+
+**Supported Language Pairs**: https://developers.cloudflare.com/workers-ai/models/m2m100-1.2b/
+
+---
+
+## Text Classification
+
+| Model ID | Task | Rate Limit |
+|----------|------|------------|
+| `@cf/huggingface/distilbert-sst-2-int8` | Sentiment analysis | 2000/min |
+| `@hf/thebloke/openhermes-2.5-mistral-7b-awq` | General classification | 300/min |
+
+**Output**: Label + confidence score
+
+---
+
+## Automatic Speech Recognition
+
+| Model ID | Best For | Rate Limit |
+|----------|----------|------------|
+| `@cf/openai/whisper` | General transcription | 720/min |
+| `@cf/openai/whisper-tiny-en` | English only, fast | 720/min |
+
+**Input**: Audio files (MP3, WAV, etc.)
+
+---
+
+## Object Detection
+
+| Model ID | Task | Rate Limit |
+|----------|------|------------|
+| `@cf/facebook/detr-resnet-50` | Object detection | 3000/min |
+
+**Output**: Bounding boxes + labels
+
+---
+
+## Image Classification
+
+| Model ID | Classes | Rate Limit |
+|----------|---------|------------|
+| `@cf/microsoft/resnet-50` | 1000 ImageNet classes | 3000/min |
+
+**Output**: Top-5 predictions with probabilities
+
+---
+
+## Summarization
+
+| Model ID | Best For | Rate Limit |
+|----------|----------|------------|
+| `@cf/facebook/bart-large-cnn` | News articles, documents | 1500/min |
+
+---
+
+## Text-to-Image (Legacy)
+
+| Model ID | Type | Rate Limit |
+|----------|------|------------|
+| `@cf/stabilityai/stable-diffusion-v1-5-img2img` | Image-to-Image | 1500/min |
+
+---
+
+## Model Selection Guide
+
+### For Text Generation
+
+**Speed Priority:**
+1. `@cf/qwen/qwen1.5-0.5b-chat` (1500/min)
+2. `@cf/meta/llama-3.2-1b-instruct` (300/min)
+3. `@cf/tinyllama/tinyllama-1.1b-chat-v1.0` (720/min)
+
+**Quality Priority:**
+1. `@cf/qwen/qwen1.5-14b-chat-awq` (150/min)
+2. `@cf/deepseek-ai/deepseek-r1-distill-qwen-32b` (300/min)
+3. `@cf/meta/llama-3.1-8b-instruct` (300/min)
+
+**Balanced:**
+1. `@cf/meta/llama-3.1-8b-instruct` (300/min)
+2. `@hf/thebloke/mistral-7b-instruct-v0.1-awq` (400/min)
+3. `@cf/qwen/qwen1.5-7b-chat-awq` (300/min)
+
+### For Embeddings
+
+**General Purpose RAG:**
+- `@cf/baai/bge-base-en-v1.5` (768 dims, 3000/min)
+
+**High Accuracy:**
+- `@cf/baai/bge-large-en-v1.5` (1024 dims, 1500/min)
+
+**Fast/Low Storage:**
+- `@cf/baai/bge-small-en-v1.5` (384 dims, 3000/min)
+
+### For Image Generation
+
+**Best Quality:**
+- `@cf/black-forest-labs/flux-1-schnell`
+
+**General Purpose:**
+- `@cf/stabilityai/stable-diffusion-xl-base-1.0`
+
+**Artistic/Stylized:**
+- `@cf/lykon/dreamshaper-8-lcm`
+
+**Fast:**
+- `@cf/bytedance/stable-diffusion-xl-lightning`
+
+---
+
+## Rate Limits Summary
+
+| Task Type | Default Limit | High-Speed Models |
+|-----------|---------------|-------------------|
+| Text Generation | 300/min | 400-1500/min |
+| Text Embeddings | 3000/min | 1500/min (large) |
+| Image Generation | 720/min | 720/min |
+| Vision Models | 720/min | 720/min |
+| Translation | 720/min | 720/min |
+| Classification | 2000/min | 2000/min |
+| Speech Recognition | 720/min | 720/min |
+| Object Detection | 3000/min | 3000/min |
+
+---
+
+## Pricing (Neurons)
+
+Pricing varies by model. Common examples:
+
+| Model | Input (1M tokens) | Output (1M tokens) |
+|-------|-------------------|-------------------|
+| Llama 3.2 1B | $0.027 | $0.201 |
+| Llama 3.1 8B | $0.088 | $0.606 |
+| BGE-base embeddings | $0.005 | N/A |
+| Flux image gen | ~$0.011/image | N/A |
+
+**Free Tier**: 10,000 neurons/day
+**Paid Tier**: $0.011 per 1,000 neurons
+
+---
+
+## References
+
+- [Official Models Catalog](https://developers.cloudflare.com/workers-ai/models/)
+- [Rate Limits](https://developers.cloudflare.com/workers-ai/platform/limits/)
+- [Pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/)
diff --git a/skills/cloudflare-workers-ai/templates/ai-embeddings-rag.ts b/skills/cloudflare-workers-ai/templates/ai-embeddings-rag.ts
new file mode 100644
index 00000000..69e565dc
--- /dev/null
+++ b/skills/cloudflare-workers-ai/templates/ai-embeddings-rag.ts
@@ -0,0 +1,491 @@
+/**
+ * Cloudflare Workers AI - Embeddings & RAG Examples
+ *
+ * This template demonstrates:
+ * - Generating text embeddings with BGE models
+ * - Storing embeddings in Vectorize
+ * - Semantic search with vector similarity
+ * - Complete RAG (Retrieval Augmented Generation) pattern
+ * - Document chunking strategies
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ AI: Ai;
+ VECTORIZE: Vectorize;
+ DB?: D1Database;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Generate Embeddings
+// ============================================================================
+
+/**
+ * Generate embeddings for text
+ * BGE-base: 768 dimensions, good balance
+ * BGE-large: 1024 dimensions, higher accuracy
+ * BGE-small: 384 dimensions, faster/smaller
+ */
+
+app.post('/embeddings', async (c) => {
+ try {
+ const { text } = await c.req.json<{ text: string | string[] }>();
+
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: Array.isArray(text) ? text : [text],
+ });
+
+ return c.json({
+ success: true,
+ shape: embeddings.shape, // [batch_size, dimensions]
+ data: embeddings.data, // Array of vectors
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Batch Embeddings
+// ============================================================================
+
+/**
+ * Generate embeddings for multiple texts in one request
+ * More efficient than individual requests
+ */
+
+app.post('/embeddings/batch', async (c) => {
+ try {
+ const { texts } = await c.req.json<{ texts: string[] }>();
+
+ if (!texts || texts.length === 0) {
+ return c.json({ error: 'texts array is required' }, 400);
+ }
+
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: texts,
+ });
+
+ return c.json({
+ success: true,
+ count: texts.length,
+ shape: embeddings.shape,
+ embeddings: embeddings.data,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Store Embeddings in Vectorize
+// ============================================================================
+
+app.post('/documents', async (c) => {
+ try {
+ const { id, text, metadata } = await c.req.json<{
+ id: string;
+ text: string;
+ metadata?: Record<string, any>;
+ }>();
+
+ // Generate embedding
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: [text],
+ });
+
+ const vector = embeddings.data[0];
+
+ // Store in Vectorize
+ await c.env.VECTORIZE.upsert([
+ {
+ id,
+ values: vector,
+ metadata: {
+ text,
+ ...metadata,
+ createdAt: Date.now(),
+ },
+ },
+ ]);
+
+ return c.json({
+ success: true,
+ message: 'Document indexed',
+ id,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Semantic Search
+// ============================================================================
+
+app.post('/search', async (c) => {
+ try {
+ const { query, topK = 5 } = await c.req.json<{
+ query: string;
+ topK?: number;
+ }>();
+
+ // Convert query to embedding
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: [query],
+ });
+
+ const vector = embeddings.data[0];
+
+ // Search Vectorize
+ const results = await c.env.VECTORIZE.query(vector, {
+ topK,
+ returnMetadata: true,
+ });
+
+ return c.json({
+ success: true,
+ query,
+ results: results.matches.map((match) => ({
+ id: match.id,
+ score: match.score,
+ text: match.metadata?.text,
+ metadata: match.metadata,
+ })),
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// RAG Pattern: Query with Context
+// ============================================================================
+
+app.post('/rag/ask', async (c) => {
+ try {
+ const { question, topK = 3 } = await c.req.json<{
+ question: string;
+ topK?: number;
+ }>();
+
+ // Step 1: Convert question to embedding
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: [question],
+ });
+
+ const vector = embeddings.data[0];
+
+ // Step 2: Find relevant documents
+ const results = await c.env.VECTORIZE.query(vector, {
+ topK,
+ returnMetadata: true,
+ });
+
+ // Step 3: Build context from matches
+ const context = results.matches
+ .map((match) => match.metadata?.text)
+ .filter(Boolean)
+ .join('\n\n');
+
+ // Step 4: Generate answer with context
+ const stream = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'system',
+ content: `Answer the question using ONLY the following context. If the context doesn't contain relevant information, say "I don't have enough information to answer that."\n\nContext:\n${context}`,
+ },
+ {
+ role: 'user',
+ content: question,
+ },
+ ],
+ stream: true,
+ });
+
+ return new Response(stream, {
+ headers: {
+ 'content-type': 'text/event-stream',
+ 'x-sources': JSON.stringify(
+ results.matches.map((m) => ({ id: m.id, score: m.score }))
+ ),
+ },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Document Chunking
+// ============================================================================
+
+/**
+ * Split long documents into chunks for better embedding quality
+ * Recommended: 200-500 tokens per chunk
+ */
+
+function chunkText(text: string, chunkSize = 500, overlap = 50): string[] {
+ const words = text.split(/\s+/);
+ const chunks: string[] = [];
+
+ for (let i = 0; i < words.length; i += chunkSize - overlap) {
+ const chunk = words.slice(i, i + chunkSize).join(' ');
+ chunks.push(chunk);
+ }
+
+ return chunks;
+}
+
+app.post('/documents/long', async (c) => {
+ try {
+ const { id, text, chunkSize = 500 } = await c.req.json<{
+ id: string;
+ text: string;
+ chunkSize?: number;
+ }>();
+
+ // Split into chunks
+ const chunks = chunkText(text, chunkSize);
+
+ // Generate embeddings for all chunks
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: chunks,
+ });
+
+ // Store each chunk in Vectorize
+ const vectors = chunks.map((chunk, index) => ({
+ id: `${id}-chunk-${index}`,
+ values: embeddings.data[index],
+ metadata: {
+ documentId: id,
+ chunkIndex: index,
+ text: chunk,
+ totalChunks: chunks.length,
+ },
+ }));
+
+ await c.env.VECTORIZE.upsert(vectors);
+
+ return c.json({
+ success: true,
+ message: 'Document indexed with chunks',
+ documentId: id,
+ chunks: chunks.length,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// RAG with Citations
+// ============================================================================
+
+app.post('/rag/ask-with-citations', async (c) => {
+ try {
+ const { question } = await c.req.json<{ question: string }>();
+
+ // Find relevant chunks
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: [question],
+ });
+
+ const results = await c.env.VECTORIZE.query(embeddings.data[0], {
+ topK: 5,
+ returnMetadata: true,
+ });
+
+ // Build context with citations
+ const context = results.matches
+ .map(
+ (match, i) =>
+ `[Source ${i + 1}] ${match.metadata?.text} (Relevance: ${(match.score * 100).toFixed(1)}%)`
+ )
+ .join('\n\n');
+
+ // Generate answer
+ const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'system',
+ content: `Answer the question using the provided sources. Cite sources using [Source N] format.
+
+${context}`,
+ },
+ {
+ role: 'user',
+ content: question,
+ },
+ ],
+ });
+
+ return c.json({
+ success: true,
+ answer: response.response,
+ sources: results.matches.map((m, i) => ({
+ id: i + 1,
+ documentId: m.metadata?.documentId,
+ text: m.metadata?.text,
+ score: m.score,
+ })),
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Hybrid Search (Keyword + Semantic)
+// ============================================================================
+
+/**
+ * Combine keyword search (D1) with semantic search (Vectorize)
+ * for better recall
+ */
+
+app.post('/search/hybrid', async (c) => {
+ try {
+ const { query } = await c.req.json<{ query: string }>();
+
+ // Semantic search
+ const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
+ text: [query],
+ });
+
+ const vectorResults = await c.env.VECTORIZE.query(embeddings.data[0], {
+ topK: 5,
+ returnMetadata: true,
+ });
+
+ // Keyword search (if D1 available)
+ let keywordResults: any[] = [];
+ if (c.env.DB) {
+ const { results } = await c.env.DB.prepare(
+ 'SELECT id, text FROM documents WHERE text LIKE ? LIMIT 5'
+ )
+ .bind(`%${query}%`)
+ .all();
+
+ keywordResults = results || [];
+ }
+
+ // Combine and deduplicate
+ const combined = [
+ ...vectorResults.matches.map((m) => ({
+ id: m.id,
+ text: m.metadata?.text,
+ score: m.score,
+ source: 'vector',
+ })),
+ ...keywordResults.map((r) => ({
+ id: r.id,
+ text: r.text,
+ score: 1.0,
+ source: 'keyword',
+ })),
+ ];
+
+ // Deduplicate by ID
+ const unique = Array.from(new Map(combined.map((item) => [item.id, item])).values());
+
+ return c.json({
+ success: true,
+ query,
+ results: unique,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Delete Documents
+// ============================================================================
+
+app.delete('/documents/:id', async (c) => {
+ try {
+ const id = c.req.param('id');
+
+ // Delete from Vectorize
+ await c.env.VECTORIZE.deleteByIds([id]);
+
+ return c.json({
+ success: true,
+ message: 'Document deleted',
+ id,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Health Check
+// ============================================================================
+
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-workers-ai/templates/ai-gateway-integration.ts b/skills/cloudflare-workers-ai/templates/ai-gateway-integration.ts
new file mode 100644
index 00000000..02db4c80
--- /dev/null
+++ b/skills/cloudflare-workers-ai/templates/ai-gateway-integration.ts
@@ -0,0 +1,432 @@
+/**
+ * Cloudflare AI Gateway - Integration Examples
+ *
+ * This template demonstrates:
+ * - AI Gateway setup and configuration
+ * - Caching AI responses
+ * - Logging and analytics
+ * - Cost tracking
+ * - Rate limiting
+ * - Feedback collection
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ AI: Ai;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Basic AI Gateway Usage
+// ============================================================================
+
+/**
+ * Create a gateway at: https://dash.cloudflare.com/ai/ai-gateway
+ * Use the gateway ID in your requests
+ */
+
+app.post('/gateway/basic', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const response = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ },
+ {
+ gateway: {
+ id: 'my-gateway', // Your gateway ID
+ },
+ }
+ );
+
+ // Access log ID for analytics
+ const logId = c.env.AI.aiGatewayLogId;
+
+ return c.json({
+ success: true,
+ response: response.response,
+ logId, // Use for tracking and feedback
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// AI Gateway with Caching
+// ============================================================================
+
+/**
+ * AI Gateway can cache responses to reduce costs
+ * Same prompt = cached response (no inference cost)
+ */
+
+app.post('/gateway/cached', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const response = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ },
+ {
+ gateway: {
+ id: 'my-gateway',
+ skipCache: false, // Use cache (default)
+ },
+ }
+ );
+
+ return c.json({
+ success: true,
+ response: response.response,
+ logId: c.env.AI.aiGatewayLogId,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Skip Cache for Dynamic Content
+// ============================================================================
+
+app.post('/gateway/no-cache', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const response = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ },
+ {
+ gateway: {
+ id: 'my-gateway',
+ skipCache: true, // Always fetch fresh response
+ },
+ }
+ );
+
+ return c.json({
+ success: true,
+ response: response.response,
+ logId: c.env.AI.aiGatewayLogId,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Send Feedback to AI Gateway
+// ============================================================================
+
+/**
+ * Track user satisfaction with AI responses
+ * Helps optimize prompts and model selection
+ */
+
+app.post('/gateway/feedback', async (c) => {
+ try {
+ const { logId, rating, comment } = await c.req.json<{
+ logId: string;
+ rating: number; // 1-5
+ comment?: string;
+ }>();
+
+ const gateway = c.env.AI.gateway('my-gateway');
+
+ await gateway.patchLog(logId, {
+ feedback: {
+ rating,
+ comment,
+ },
+ });
+
+ return c.json({
+ success: true,
+ message: 'Feedback recorded',
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Track Cost Per Request
+// ============================================================================
+
+/**
+ * Monitor neurons usage per request
+ * AI Gateway logs show cost breakdown
+ */
+
+app.post('/gateway/track-cost', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const start = Date.now();
+
+ const response = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ },
+ {
+ gateway: {
+ id: 'my-gateway',
+ },
+ }
+ );
+
+ const duration = Date.now() - start;
+ const logId = c.env.AI.aiGatewayLogId;
+
+ return c.json({
+ success: true,
+ response: response.response,
+ metrics: {
+ logId,
+ duration,
+ // Check AI Gateway dashboard for neurons usage
+ },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Multi-Model Gateway
+// ============================================================================
+
+/**
+ * Use different models through the same gateway
+ * Compare performance and costs
+ */
+
+app.post('/gateway/multi-model', async (c) => {
+ try {
+ const { prompt, model = '@cf/meta/llama-3.1-8b-instruct' } = await c.req.json<{
+ prompt: string;
+ model?: string;
+ }>();
+
+ const response = await c.env.AI.run(
+ model,
+ {
+ messages: [{ role: 'user', content: prompt }],
+ },
+ {
+ gateway: {
+ id: 'my-gateway',
+ },
+ }
+ );
+
+ return c.json({
+ success: true,
+ model,
+ response: response.response,
+ logId: c.env.AI.aiGatewayLogId,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Streaming with AI Gateway
+// ============================================================================
+
+app.post('/gateway/stream', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const stream = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ stream: true,
+ },
+ {
+ gateway: {
+ id: 'my-gateway',
+ },
+ }
+ );
+
+ // Log ID available after streaming starts
+ const logId = c.env.AI.aiGatewayLogId;
+
+ return new Response(stream, {
+ headers: {
+ 'content-type': 'text/event-stream',
+ 'x-ai-gateway-log-id': logId || '',
+ },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Request Analytics Middleware
+// ============================================================================
+
+/**
+ * Log all AI requests for analytics
+ */
+
+app.use('/ai/*', async (c, next) => {
+ const start = Date.now();
+ const path = c.req.path;
+
+ await next();
+
+ const duration = Date.now() - start;
+ const logId = c.env.AI.aiGatewayLogId;
+
+ // Log to console (or send to analytics service)
+ console.log({
+ timestamp: new Date().toISOString(),
+ path,
+ duration,
+ logId,
+ status: c.res.status,
+ });
+});
+
+app.post('/ai/chat', async (c) => {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const response = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ },
+ {
+ gateway: { id: 'my-gateway' },
+ }
+ );
+
+ return c.json({
+ success: true,
+ response: response.response,
+ });
+});
+
+// ============================================================================
+// Rate Limit Protection
+// ============================================================================
+
+/**
+ * AI Gateway provides additional rate limiting
+ * Configure in dashboard: https://dash.cloudflare.com/ai/ai-gateway
+ */
+
+app.post('/gateway/rate-limited', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const response = await c.env.AI.run(
+ '@cf/meta/llama-3.1-8b-instruct',
+ {
+ messages: [{ role: 'user', content: prompt }],
+ },
+ {
+ gateway: {
+ id: 'my-gateway',
+ },
+ }
+ );
+
+ return c.json({
+ success: true,
+ response: response.response,
+ });
+ } catch (error) {
+ const message = (error as Error).message;
+
+ // Check for rate limit error
+ if (message.includes('429') || message.includes('rate limit')) {
+ return c.json(
+ {
+ success: false,
+ error: 'Rate limit exceeded. Please try again later.',
+ retryAfter: 60, // seconds
+ },
+ 429
+ );
+ }
+
+ return c.json(
+ {
+ success: false,
+ error: message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Health Check
+// ============================================================================
+
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-workers-ai/templates/ai-image-generation.ts b/skills/cloudflare-workers-ai/templates/ai-image-generation.ts
new file mode 100644
index 00000000..9d37155e
--- /dev/null
+++ b/skills/cloudflare-workers-ai/templates/ai-image-generation.ts
@@ -0,0 +1,391 @@
+/**
+ * Cloudflare Workers AI - Image Generation Examples
+ *
+ * This template demonstrates:
+ * - Text-to-image with Flux models (highest quality)
+ * - Stable Diffusion XL
+ * - Image storage in R2
+ * - Base64 and binary responses
+ * - Custom prompts and parameters
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ AI: Ai;
+ BUCKET?: R2Bucket;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Flux - Text-to-Image (Highest Quality)
+// ============================================================================
+
+/**
+ * Flux 1 Schnell - Fast, high-quality image generation
+ * Best for: Photorealistic images, detailed artwork
+ * Rate limit: 720/min
+ */
+
+app.post('/generate/flux', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const imageStream = await c.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
+ prompt,
+ });
+
+ return new Response(imageStream, {
+ headers: { 'content-type': 'image/png' },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Stable Diffusion XL
+// ============================================================================
+
+app.post('/generate/sdxl', async (c) => {
+ try {
+ const { prompt, num_steps = 20, guidance = 7.5 } = await c.req.json<{
+ prompt: string;
+ num_steps?: number;
+ guidance?: number;
+ }>();
+
+ const imageStream = await c.env.AI.run(
+ '@cf/stabilityai/stable-diffusion-xl-base-1.0',
+ {
+ prompt,
+ num_steps, // More steps = higher quality, slower
+ guidance, // CFG scale: higher = more prompt adherence
+ }
+ );
+
+ return new Response(imageStream, {
+ headers: { 'content-type': 'image/png' },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// DreamShaper (Artistic/Stylized)
+// ============================================================================
+
+app.post('/generate/dreamshaper', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const imageStream = await c.env.AI.run('@cf/lykon/dreamshaper-8-lcm', {
+ prompt,
+ });
+
+ return new Response(imageStream, {
+ headers: { 'content-type': 'image/png' },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Generate and Store in R2
+// ============================================================================
+
+app.post('/generate/save', async (c) => {
+ try {
+ const { prompt, filename } = await c.req.json<{
+ prompt: string;
+ filename?: string;
+ }>();
+
+ if (!c.env.BUCKET) {
+ return c.json({ error: 'R2 bucket not configured' }, 500);
+ }
+
+ // Generate image
+ const imageStream = await c.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
+ prompt,
+ });
+
+ const imageBytes = await new Response(imageStream).bytes();
+
+ // Generate filename
+ const key = filename || `images/${Date.now()}.png`;
+
+ // Store in R2
+ await c.env.BUCKET.put(key, imageBytes, {
+ httpMetadata: {
+ contentType: 'image/png',
+ },
+ customMetadata: {
+ prompt,
+ generatedAt: new Date().toISOString(),
+ },
+ });
+
+ return c.json({
+ success: true,
+ message: 'Image generated and saved',
+ key,
+ url: `https://your-domain.com/${key}`, // Update with your R2 public URL
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Return Base64 Encoded Image
+// ============================================================================
+
+app.post('/generate/base64', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const imageStream = await c.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
+ prompt,
+ });
+
+ const imageBytes = await new Response(imageStream).bytes();
+ const base64 = btoa(String.fromCharCode(...imageBytes));
+
+ return c.json({
+ success: true,
+ image: `data:image/png;base64,${base64}`,
+ prompt,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Image-to-Image (Stable Diffusion)
+// ============================================================================
+
+/**
+ * Transform existing images based on prompts
+ * Requires base64-encoded input image
+ */
+
+app.post('/generate/img2img', async (c) => {
+ try {
+ const { prompt, image, strength = 0.8 } = await c.req.json<{
+ prompt: string;
+ image: string; // Base64 encoded
+ strength?: number; // 0.0-1.0, higher = more transformation
+ }>();
+
+ // Decode base64 image to array
+ const imageData = Uint8Array.from(atob(image.replace(/^data:image\/\w+;base64,/, '')), (c) =>
+ c.charCodeAt(0)
+ );
+
+ const result = await c.env.AI.run('@cf/runwayml/stable-diffusion-v1-5-img2img', {
+ prompt,
+ image: Array.from(imageData),
+ strength,
+ });
+
+ return new Response(result, {
+ headers: { 'content-type': 'image/png' },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Batch Generation
+// ============================================================================
+
+app.post('/generate/batch', async (c) => {
+ try {
+ const { prompts } = await c.req.json<{ prompts: string[] }>();
+
+ if (!prompts || prompts.length === 0) {
+ return c.json({ error: 'prompts array is required' }, 400);
+ }
+
+ if (prompts.length > 5) {
+ return c.json({ error: 'Maximum 5 prompts per batch' }, 400);
+ }
+
+ const images = await Promise.all(
+ prompts.map(async (prompt) => {
+ const imageStream = await c.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
+ prompt,
+ });
+
+ const imageBytes = await new Response(imageStream).bytes();
+ const base64 = btoa(String.fromCharCode(...imageBytes));
+
+ return {
+ prompt,
+ image: `data:image/png;base64,${base64}`,
+ };
+ })
+ );
+
+ return c.json({
+ success: true,
+ count: images.length,
+ images,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Prompt Enhancement
+// ============================================================================
+
+/**
+ * Use LLM to enhance user prompts for better image quality
+ */
+
+app.post('/generate/enhanced', async (c) => {
+ try {
+ const { userPrompt } = await c.req.json<{ userPrompt: string }>();
+
+ // Step 1: Enhance prompt with LLM
+ const enhancement = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'system',
+ content:
+ 'You are a Stable Diffusion prompt expert. Enhance the user prompt for image generation. Add details about style, lighting, quality, composition. Return ONLY the enhanced prompt, no explanations.',
+ },
+ {
+ role: 'user',
+ content: userPrompt,
+ },
+ ],
+ });
+
+ const enhancedPrompt = enhancement.response.trim();
+
+ // Step 2: Generate image with enhanced prompt
+ const imageStream = await c.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
+ prompt: enhancedPrompt,
+ });
+
+ const imageBytes = await new Response(imageStream).bytes();
+ const base64 = btoa(String.fromCharCode(...imageBytes));
+
+ return c.json({
+ success: true,
+ originalPrompt: userPrompt,
+ enhancedPrompt,
+ image: `data:image/png;base64,${base64}`,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// List Generated Images (from R2)
+// ============================================================================
+
+app.get('/images', async (c) => {
+ try {
+ if (!c.env.BUCKET) {
+ return c.json({ error: 'R2 bucket not configured' }, 500);
+ }
+
+ const listed = await c.env.BUCKET.list({
+ prefix: 'images/',
+ limit: 100,
+ });
+
+ const images = listed.objects.map((obj) => ({
+ key: obj.key,
+ size: obj.size,
+ uploaded: obj.uploaded,
+ url: `https://your-domain.com/${obj.key}`,
+ }));
+
+ return c.json({
+ success: true,
+ count: images.length,
+ images,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Health Check
+// ============================================================================
+
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-workers-ai/templates/ai-text-generation.ts b/skills/cloudflare-workers-ai/templates/ai-text-generation.ts
new file mode 100644
index 00000000..0429c15f
--- /dev/null
+++ b/skills/cloudflare-workers-ai/templates/ai-text-generation.ts
@@ -0,0 +1,437 @@
+/**
+ * Cloudflare Workers AI - Text Generation Examples
+ *
+ * This template demonstrates:
+ * - Basic text generation (prompt and messages)
+ * - Streaming responses (RECOMMENDED for production)
+ * - Chat completions with conversation history
+ * - Structured output with JSON
+ * - Error handling and retry logic
+ * - Rate limit management
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ AI: Ai;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Basic Text Generation
+// ============================================================================
+
+// Simple prompt (deprecated pattern, use messages instead)
+app.post('/simple', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ prompt,
+ });
+
+ return c.json({
+ success: true,
+ response: response.response,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Streaming Text Generation (RECOMMENDED)
+// ============================================================================
+
+/**
+ * Streaming is ESSENTIAL for production:
+ * - Prevents buffering large responses in memory
+ * - Faster time-to-first-token
+ * - Better user experience
+ * - Avoids Worker timeout issues
+ */
+
+app.post('/stream', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const stream = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [{ role: 'user', content: prompt }],
+ stream: true, // Enable streaming
+ });
+
+ return new Response(stream, {
+ headers: {
+ 'content-type': 'text/event-stream',
+ 'cache-control': 'no-cache',
+ connection: 'keep-alive',
+ },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Chat Completions with History
+// ============================================================================
+
+app.post('/chat', async (c) => {
+ try {
+ const { messages } = await c.req.json<{
+ messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;
+ }>();
+
+ // Validate messages
+ if (!messages || messages.length === 0) {
+ return c.json({ error: 'Messages array is required' }, 400);
+ }
+
+ const stream = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages,
+ stream: true,
+ max_tokens: 512, // Limit response length
+ });
+
+ return new Response(stream, {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Streaming with Custom Parameters
+// ============================================================================
+
+app.post('/stream/custom', async (c) => {
+ try {
+ const { prompt, temperature = 0.7, max_tokens = 512 } = await c.req.json<{
+ prompt: string;
+ temperature?: number;
+ max_tokens?: number;
+ }>();
+
+ const stream = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'system',
+ content: 'You are a helpful AI assistant.',
+ },
+ {
+ role: 'user',
+ content: prompt,
+ },
+ ],
+ stream: true,
+ max_tokens,
+ temperature, // Controls randomness (0.0-1.0)
+ });
+
+ return new Response(stream, {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Structured Output (JSON)
+// ============================================================================
+
+/**
+ * Generate structured JSON output
+ * Useful for extracting data, generating schemas, etc.
+ */
+
+app.post('/structured', async (c) => {
+ try {
+ const { topic } = await c.req.json<{ topic: string }>();
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'system',
+ content:
+ 'You are a helpful assistant that ONLY returns valid JSON. Never include explanations or markdown, just raw JSON.',
+ },
+ {
+ role: 'user',
+ content: `Generate a recipe for ${topic}. Return JSON with keys: name, ingredients (array), instructions (array), prepTime (number in minutes)`,
+ },
+ ],
+ max_tokens: 1024,
+ });
+
+ // Parse JSON response
+ const data = JSON.parse(response.response);
+
+ return c.json({
+ success: true,
+ data,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Model Comparison
+// ============================================================================
+
+/**
+ * Compare different models side-by-side
+ */
+
+app.post('/compare', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const models = [
+ '@cf/meta/llama-3.1-8b-instruct', // Balanced
+ '@cf/meta/llama-3.2-1b-instruct', // Fast
+ '@cf/qwen/qwen1.5-14b-chat-awq', // High quality
+ ];
+
+ const results = await Promise.all(
+ models.map(async (model) => {
+ const start = Date.now();
+ const response = await c.env.AI.run(model, {
+ messages: [{ role: 'user', content: prompt }],
+ max_tokens: 256,
+ });
+ const duration = Date.now() - start;
+
+ return {
+ model,
+ response: response.response,
+ duration,
+ };
+ })
+ );
+
+ return c.json({
+ success: true,
+ results,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Error Handling with Retry
+// ============================================================================
+
+/**
+ * Retry logic for rate limits and transient errors
+ */
+
+async function runWithRetry(
+ ai: Ai,
+ model: string,
+ inputs: any,
+ maxRetries = 3
+): Promise<any> {
+ let lastError: Error;
+
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ return await ai.run(model, inputs);
+ } catch (error) {
+ lastError = error as Error;
+ const message = lastError.message.toLowerCase();
+
+ // Rate limit (429) - retry with exponential backoff
+ if (message.includes('429') || message.includes('rate limit')) {
+ if (i < maxRetries - 1) {
+ const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
+ console.log(`Rate limited. Retrying in ${delay}ms...`);
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ continue;
+ }
+ }
+
+ // Model unavailable - try fallback model
+ if (message.includes('model') && message.includes('unavailable')) {
+ if (i === 0) {
+ console.log('Model unavailable, trying fallback...');
+ model = '@cf/meta/llama-3.2-1b-instruct'; // Faster fallback
+ continue;
+ }
+ }
+
+ // Other errors - throw immediately
+ throw error;
+ }
+ }
+
+ throw lastError!;
+}
+
+app.post('/reliable', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const response = await runWithRetry(c.env.AI, '@cf/meta/llama-3.1-8b-instruct', {
+ messages: [{ role: 'user', content: prompt }],
+ });
+
+ return c.json({
+ success: true,
+ response: response.response,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Token Length Validation
+// ============================================================================
+
+/**
+ * Validate input length to prevent token limit errors
+ * Approximate: 1 token β‰ˆ 4 characters
+ */
+
+function estimateTokens(text: string): number {
+ return Math.ceil(text.length / 4);
+}
+
+app.post('/validate', async (c) => {
+ try {
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ const estimatedTokens = estimateTokens(prompt);
+ const maxInputTokens = 2048; // Most models support 2K-128K
+
+ if (estimatedTokens > maxInputTokens) {
+ return c.json(
+ {
+ success: false,
+ error: `Input too long: ${estimatedTokens} tokens (max: ${maxInputTokens})`,
+ },
+ 400
+ );
+ }
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [{ role: 'user', content: prompt }],
+ });
+
+ return c.json({
+ success: true,
+ response: response.response,
+ estimatedTokens,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// System Prompts & Personas
+// ============================================================================
+
+const PERSONAS = {
+ helpful: 'You are a helpful AI assistant.',
+ concise: 'You are a concise AI assistant. Keep responses brief.',
+ technical: 'You are a technical AI assistant. Provide detailed, accurate information.',
+ creative: 'You are a creative AI assistant. Be imaginative and original.',
+};
+
+app.post('/persona/:persona', async (c) => {
+ try {
+ const persona = c.req.param('persona') as keyof typeof PERSONAS;
+ const { prompt } = await c.req.json<{ prompt: string }>();
+
+ if (!PERSONAS[persona]) {
+ return c.json({ error: 'Invalid persona' }, 400);
+ }
+
+ const stream = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ { role: 'system', content: PERSONAS[persona] },
+ { role: 'user', content: prompt },
+ ],
+ stream: true,
+ });
+
+ return new Response(stream, {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Health Check
+// ============================================================================
+
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-workers-ai/templates/ai-vision-models.ts b/skills/cloudflare-workers-ai/templates/ai-vision-models.ts
new file mode 100644
index 00000000..c34ea553
--- /dev/null
+++ b/skills/cloudflare-workers-ai/templates/ai-vision-models.ts
@@ -0,0 +1,417 @@
+/**
+ * Cloudflare Workers AI - Vision Models Examples
+ *
+ * This template demonstrates:
+ * - Llama 3.2 11B Vision Instruct for image understanding
+ * - Image captioning and description
+ * - Visual question answering
+ * - Base64 image encoding
+ * - Combining vision + text prompts
+ */
+
+import { Hono } from 'hono';
+
+type Bindings = {
+ AI: Ai;
+};
+
+const app = new Hono<{ Bindings: Bindings }>();
+
+// ============================================================================
+// Image Understanding
+// ============================================================================
+
+/**
+ * Llama 3.2 11B Vision Instruct
+ * - Understands images and answers questions
+ * - Accepts base64-encoded images
+ * - Rate limit: 720/min
+ */
+
+app.post('/vision/understand', async (c) => {
+ try {
+ const { image, question = 'What is in this image?' } = await c.req.json<{
+ image: string; // Base64 data URL or base64 string
+ question?: string;
+ }>();
+
+ // Ensure image has proper data URL prefix
+ const imageUrl = image.startsWith('data:')
+ ? image
+ : `data:image/png;base64,${image}`;
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: question },
+ { type: 'image_url', image_url: { url: imageUrl } },
+ ],
+ },
+ ],
+ });
+
+ return c.json({
+ success: true,
+ question,
+ answer: response.response,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Image Captioning
+// ============================================================================
+
+app.post('/vision/caption', async (c) => {
+ try {
+ const { image } = await c.req.json<{ image: string }>();
+
+ const imageUrl = image.startsWith('data:')
+ ? image
+ : `data:image/png;base64,${image}`;
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ {
+ type: 'text',
+ text: 'Generate a detailed caption for this image. Describe what you see, including objects, people, setting, mood, and any notable details.',
+ },
+ { type: 'image_url', image_url: { url: imageUrl } },
+ ],
+ },
+ ],
+ });
+
+ return c.json({
+ success: true,
+ caption: response.response,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Visual Question Answering
+// ============================================================================
+
+app.post('/vision/qa', async (c) => {
+ try {
+ const { image, questions } = await c.req.json<{
+ image: string;
+ questions: string[];
+ }>();
+
+ if (!questions || questions.length === 0) {
+ return c.json({ error: 'questions array is required' }, 400);
+ }
+
+ const imageUrl = image.startsWith('data:')
+ ? image
+ : `data:image/png;base64,${image}`;
+
+ // Answer all questions
+ const answers = await Promise.all(
+ questions.map(async (question) => {
+ const response = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: question },
+ { type: 'image_url', image_url: { url: imageUrl } },
+ ],
+ },
+ ],
+ });
+
+ return {
+ question,
+ answer: response.response,
+ };
+ })
+ );
+
+ return c.json({
+ success: true,
+ count: answers.length,
+ results: answers,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Image Analysis (Structured Output)
+// ============================================================================
+
+app.post('/vision/analyze', async (c) => {
+ try {
+ const { image } = await c.req.json<{ image: string }>();
+
+ const imageUrl = image.startsWith('data:')
+ ? image
+ : `data:image/png;base64,${image}`;
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ {
+ type: 'text',
+ text: `Analyze this image and return a JSON object with:
+- objects: array of objects detected
+- scene: description of the setting
+- mood: emotional tone
+- colors: dominant colors
+- text: any visible text
+
+Return ONLY valid JSON, no explanations.`,
+ },
+ { type: 'image_url', image_url: { url: imageUrl } },
+ ],
+ },
+ ],
+ });
+
+ // Parse JSON response
+ try {
+ const analysis = JSON.parse(response.response);
+ return c.json({
+ success: true,
+ analysis,
+ });
+ } catch {
+ return c.json({
+ success: true,
+ raw: response.response,
+ });
+ }
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Image Comparison
+// ============================================================================
+
+app.post('/vision/compare', async (c) => {
+ try {
+ const { image1, image2, question = 'What are the differences between these images?' } =
+ await c.req.json<{
+ image1: string;
+ image2: string;
+ question?: string;
+ }>();
+
+ const imageUrl1 = image1.startsWith('data:')
+ ? image1
+ : `data:image/png;base64,${image1}`;
+ const imageUrl2 = image2.startsWith('data:')
+ ? image2
+ : `data:image/png;base64,${image2}`;
+
+ // Analyze first image
+ const analysis1 = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Describe this image in detail.' },
+ { type: 'image_url', image_url: { url: imageUrl1 } },
+ ],
+ },
+ ],
+ });
+
+ // Analyze second image
+ const analysis2 = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Describe this image in detail.' },
+ { type: 'image_url', image_url: { url: imageUrl2 } },
+ ],
+ },
+ ],
+ });
+
+ // Compare using text generation
+ const comparison = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: `Compare these two images based on their descriptions:
+
+Image 1: ${analysis1.response}
+
+Image 2: ${analysis2.response}
+
+Question: ${question}`,
+ },
+ ],
+ });
+
+ return c.json({
+ success: true,
+ image1Description: analysis1.response,
+ image2Description: analysis2.response,
+ comparison: comparison.response,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Image Upload from URL
+// ============================================================================
+
+/**
+ * Fetch image from URL, convert to base64, and analyze
+ */
+
+app.post('/vision/url', async (c) => {
+ try {
+ const { url, question = 'What is in this image?' } = await c.req.json<{
+ url: string;
+ question?: string;
+ }>();
+
+ // Fetch image
+ const imageResponse = await fetch(url);
+ if (!imageResponse.ok) {
+ return c.json({ error: 'Failed to fetch image' }, 400);
+ }
+
+ // Convert to base64
+ const imageBytes = await imageResponse.bytes();
+ const base64 = btoa(String.fromCharCode(...imageBytes));
+ const contentType = imageResponse.headers.get('content-type') || 'image/png';
+ const imageUrl = `data:${contentType};base64,${base64}`;
+
+ // Analyze image
+ const response = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: question },
+ { type: 'image_url', image_url: { url: imageUrl } },
+ ],
+ },
+ ],
+ });
+
+ return c.json({
+ success: true,
+ sourceUrl: url,
+ question,
+ answer: response.response,
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Accessibility: Alt Text Generation
+// ============================================================================
+
+app.post('/vision/alt-text', async (c) => {
+ try {
+ const { image } = await c.req.json<{ image: string }>();
+
+ const imageUrl = image.startsWith('data:')
+ ? image
+ : `data:image/png;base64,${image}`;
+
+ const response = await c.env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ {
+ type: 'text',
+ text: 'Generate a concise, descriptive alt text for this image for accessibility purposes. Keep it under 125 characters.',
+ },
+ { type: 'image_url', image_url: { url: imageUrl } },
+ ],
+ },
+ ],
+ });
+
+ return c.json({
+ success: true,
+ altText: response.response.trim(),
+ });
+ } catch (error) {
+ return c.json(
+ {
+ success: false,
+ error: (error as Error).message,
+ },
+ 500
+ );
+ }
+});
+
+// ============================================================================
+// Health Check
+// ============================================================================
+
+app.get('/health', (c) => {
+ return c.json({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ });
+});
+
+export default app;
diff --git a/skills/cloudflare-workers-ai/templates/wrangler-ai-config.jsonc b/skills/cloudflare-workers-ai/templates/wrangler-ai-config.jsonc
new file mode 100644
index 00000000..a8dae369
--- /dev/null
+++ b/skills/cloudflare-workers-ai/templates/wrangler-ai-config.jsonc
@@ -0,0 +1,138 @@
+/**
+ * Cloudflare Workers AI - Wrangler Configuration
+ *
+ * This configuration file sets up Workers AI binding for your Worker.
+ * Place this in your project root as wrangler.jsonc
+ */
+
+{
+ "name": "my-ai-worker",
+ "main": "src/index.ts",
+ "compatibility_date": "2025-10-21",
+
+ /**
+ * AI Binding
+ * Provides access to Workers AI models via env.AI
+ */
+ "ai": {
+ "binding": "AI" // Available in your Worker as env.AI
+ },
+
+ /**
+ * Optional: AI Gateway Integration
+ * Provides caching, logging, and analytics for AI requests
+ * Create a gateway at: https://dash.cloudflare.com/ai/ai-gateway
+ */
+ // Note: AI Gateway is configured per-request, not in wrangler.jsonc
+ // Use the gateway option in env.AI.run():
+ // env.AI.run(model, inputs, { gateway: { id: 'my-gateway' } })
+
+ /**
+ * Optional: Vectorize Binding (for RAG patterns)
+ * Store and search vector embeddings
+ */
+ "vectorize": [
+ {
+ "binding": "VECTORIZE",
+ "index_name": "my-embeddings-index"
+ }
+ ],
+
+ /**
+ * Optional: D1 Database (for RAG document storage)
+ */
+ "d1_databases": [
+ {
+ "binding": "DB",
+ "database_name": "my-database",
+ "database_id": "YOUR_DATABASE_ID"
+ }
+ ],
+
+ /**
+ * Optional: R2 Bucket (for image storage)
+ */
+ "r2_buckets": [
+ {
+ "binding": "BUCKET",
+ "bucket_name": "ai-generated-images"
+ }
+ ],
+
+ /**
+ * Optional: KV Namespace (for caching AI responses)
+ */
+ "kv_namespaces": [
+ {
+ "binding": "CACHE",
+ "id": "YOUR_KV_NAMESPACE_ID"
+ }
+ ],
+
+ /**
+ * Environment Variables
+ * Store API keys and configuration
+ */
+ "vars": {
+ "ENVIRONMENT": "production"
+ },
+
+ /**
+ * Secrets (use: wrangler secret put SECRET_NAME)
+ * - CLOUDFLARE_API_KEY
+ * - CLOUDFLARE_ACCOUNT_ID
+ */
+
+ /**
+ * Workers Configuration
+ */
+ "limits": {
+ "cpu_ms": 30000 // 30 seconds (increase for long AI operations)
+ },
+
+ /**
+ * Local Development
+ * Run: npx wrangler dev
+ */
+ "dev": {
+ "port": 8787
+ }
+}
+
+/**
+ * TypeScript Types
+ *
+ * Add to your src/index.ts:
+ *
+ * export interface Env {
+ * AI: Ai;
+ * VECTORIZE?: Vectorize;
+ * DB?: D1Database;
+ * BUCKET?: R2Bucket;
+ * CACHE?: KVNamespace;
+ * CLOUDFLARE_API_KEY?: string;
+ * CLOUDFLARE_ACCOUNT_ID?: string;
+ * }
+ */
+
+/**
+ * Usage Examples
+ *
+ * Basic AI inference:
+ * const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ * prompt: 'Hello!',
+ * });
+ *
+ * With AI Gateway:
+ * const response = await env.AI.run(
+ * '@cf/meta/llama-3.1-8b-instruct',
+ * { prompt: 'Hello!' },
+ * { gateway: { id: 'my-gateway' } }
+ * );
+ *
+ * Streaming:
+ * const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
+ * messages: [{ role: 'user', content: 'Hello!' }],
+ * stream: true,
+ * });
+ */