[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AK0RJMB0DCDYRXNVCE1Z0Y":3,"skill-same:01M7AK0RJMB0DCDYRXNVCE1Z0Y":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":5,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7AK0RJMB0DCDYRXNVCE1Z0Y","cloudflare-kv",null,"Complete knowledge domain for Cloudflare Workers KV - global, low-latency key-value storage on Cloudflare's edge network.\n\nUse when: creating KV namespaces, storing configuration data, caching API responses, managing user preferences,\nimplementing TTL expiration, handling KV metadata, or encountering \"KV_ERROR\", \"429 too many requests\",\n\"kv rate limit\", cacheTtl errors, or eventual consistency issues.\n\nKeywords: kv storage, cloudflare kv, workers kv, kv namespace, kv bindings, kv cache, kv ttl, kv metadata,\nkv list, kv pagination, cache optimization, edge caching, KV_ERROR, 429 too many requests, kv rate limit,\neventually consistent, wrangler kv, kv operations, key value storage","davidanthonyn\u002Fagent-skills","davidanthonyn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F55152980?v=4","01M7AJ4MY8S5C2RJCGX6626J0G","01M7AJ4MZB7EC7CAP27ANCSE7N",1,"MIT","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-kv\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: cloudflare-kv\ndescription: |\n  Complete knowledge domain for Cloudflare Workers KV - global, low-latency key-value storage on Cloudflare's edge network.\n\n  Use when: creating KV namespaces, storing configuration data, caching API responses, managing user preferences,\n  implementing TTL expiration, handling KV metadata, or encountering \"KV_ERROR\", \"429 too many requests\",\n  \"kv rate limit\", cacheTtl errors, or eventual consistency issues.\n\n  Keywords: kv storage, cloudflare kv, workers kv, kv namespace, kv bindings, kv cache, kv ttl, kv metadata,\n  kv list, kv pagination, cache optimization, edge caching, KV_ERROR, 429 too many requests, kv rate limit,\n  eventually consistent, wrangler kv, kv operations, key value storage\nlicense: MIT\n---\n\n# Cloudflare Workers KV\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-21\n**Dependencies**: cloudflare-worker-base (for Worker setup)\n**Latest Versions**: wrangler@4.43.0, @cloudflare\u002Fworkers-types@4.20251014.0\n\n---\n\n## Quick Start (5 Minutes)\n\n### 1. Create KV Namespace\n\n```bash\n# Create a new KV namespace\nnpx wrangler kv namespace create MY_NAMESPACE\n\n# Output includes namespace_id - save this!\n# ✅ Success!\n# Add the following to your wrangler.toml or wrangler.jsonc:\n#\n# [[kv_namespaces]]\n# binding = \"MY_NAMESPACE\"\n# id = \"\u003CUUID>\"\n```\n\n**For development (preview) namespace:**\n\n```bash\nnpx wrangler kv namespace create MY_NAMESPACE --preview\n\n# Output:\n# [[kv_namespaces]]\n# binding = \"MY_NAMESPACE\"\n# preview_id = \"\u003CUUID>\"\n```\n\n### 2. Configure Bindings\n\nAdd to your `wrangler.jsonc`:\n\n```jsonc\n{\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-11\",\n  \"kv_namespaces\": [\n    {\n      \"binding\": \"MY_NAMESPACE\",          \u002F\u002F Available as env.MY_NAMESPACE\n      \"id\": \"\u003Cproduction-uuid>\",           \u002F\u002F Production namespace ID\n      \"preview_id\": \"\u003Cpreview-uuid>\"       \u002F\u002F Local dev namespace ID (optional)\n    }\n  ]\n}\n```\n\n**Or use `wrangler.toml`:**\n\n```toml\nname = \"my-worker\"\nmain = \"src\u002Findex.ts\"\ncompatibility_date = \"2025-10-11\"\n\n[[kv_namespaces]]\nbinding = \"MY_NAMESPACE\"\nid = \"\u003Cproduction-uuid>\"\npreview_id = \"\u003Cpreview-uuid>\"  # optional\n```\n\n**CRITICAL:**\n- `binding` is how you access the namespace in code (`env.MY_NAMESPACE`)\n- `id` is the production namespace UUID\n- `preview_id` is for local dev (optional, separate namespace)\n- **Never commit real namespace IDs to public repos** - use environment variables or secrets\n\n### 3. Write Your First Key-Value Pair\n\n```typescript\nimport { Hono } from 'hono';\n\ntype Bindings = {\n  MY_NAMESPACE: KVNamespace;\n};\n\nconst app = new Hono\u003C{ Bindings: Bindings }>();\n\napp.post('\u002Fset\u002F:key', async (c) => {\n  const key = c.req.param('key');\n  const value = await c.req.text();\n\n  \u002F\u002F Simple write\n  await c.env.MY_NAMESPACE.put(key, value);\n\n  return c.json({ success: true, key });\n});\n\napp.get('\u002Fget\u002F:key', async (c) => {\n  const key = c.req.param('key');\n  const value = await c.env.MY_NAMESPACE.get(key);\n\n  if (!value) {\n    return c.json({ error: 'Not found' }, 404);\n  }\n\n  return c.json({ value });\n});\n\nexport default app;\n```\n\n### 4. Test Locally\n\n```bash\n# Start local development server\nnpm run dev\n\n# In another terminal, test the endpoints\ncurl -X POST http:\u002F\u002Flocalhost:8787\u002Fset\u002Ftest -d \"Hello KV\"\n# {\"success\":true,\"key\":\"test\"}\n\ncurl http:\u002F\u002Flocalhost:8787\u002Fget\u002Ftest\n# {\"value\":\"Hello KV\"}\n```\n\n---\n\n## Complete Workers KV API\n\n### 1. Read Operations\n\n#### `get()` - Read Single Key\n\n```typescript\n\u002F\u002F Get as string (default)\nconst value: string | null = await env.MY_KV.get('my-key');\n\n\u002F\u002F Get as JSON\nconst data: MyType | null = await env.MY_KV.get('my-key', { type: 'json' });\n\n\u002F\u002F Get as ArrayBuffer\nconst buffer: ArrayBuffer | null = await env.MY_KV.get('my-key', { type: 'arrayBuffer' });\n\n\u002F\u002F Get as ReadableStream\nconst stream: ReadableStream | null = await env.MY_KV.get('my-key', { type: 'stream' });\n\n\u002F\u002F Get with cache optimization\nconst value = await env.MY_KV.get('my-key', {\n  type: 'text',\n  cacheTtl: 300, \u002F\u002F Cache at edge for 5 minutes (minimum 60 seconds)\n});\n```\n\n#### `get()` - Read Multiple Keys (Bulk)\n\n```typescript\n\u002F\u002F Read multiple keys at once (counts as 1 operation)\nconst keys = ['key1', 'key2', 'key3'];\nconst values: Map\u003Cstring, string | null> = await env.MY_KV.get(keys);\n\n\u002F\u002F Access values\nconst value1 = values.get('key1'); \u002F\u002F string | null\nconst value2 = values.get('key2'); \u002F\u002F string | null\n\n\u002F\u002F Convert to object\nconst obj = Object.fromEntries(values);\n```\n\n#### `getWithMetadata()` - Read with Metadata\n\n```typescript\n\u002F\u002F Get single key with metadata\nconst { value, metadata } = await env.MY_KV.getWithMetadata('my-key');\n\n\u002F\u002F value: string | null\n\u002F\u002F metadata: any | null\n\n\u002F\u002F Get as JSON with metadata\nconst { value, metadata } = await env.MY_KV.getWithMetadata\u003CMyType>('my-key', {\n  type: 'json',\n  cacheTtl: 300,\n});\n\n\u002F\u002F Get multiple keys with metadata\nconst keys = ['key1', 'key2'];\nconst result: Map\u003Cstring, { value: string | null, metadata: any | null }> =\n  await env.MY_KV.getWithMetadata(keys);\n\nfor (const [key, data] of result) {\n  console.log(key, data.value, data.metadata);\n}\n```\n\n**Type Options:**\n- `text` (default) - Returns `string`\n- `json` - Parses JSON, returns `object`\n- `arrayBuffer` - Returns `ArrayBuffer`\n- `stream` - Returns `ReadableStream`\n\n**Note:** Bulk read with `get(keys[])` only supports `text` and `json` types. For `arrayBuffer` or `stream`, use individual `get()` calls with `Promise.all()`.\n\n---\n\n### 2. Write Operations\n\n#### `put()` - Write Key-Value Pair\n\n```typescript\n\u002F\u002F Simple write\nawait env.MY_KV.put('key', 'value');\n\n\u002F\u002F Write JSON\nawait env.MY_KV.put('user:123', JSON.stringify({ name: 'John', age: 30 }));\n\n\u002F\u002F Write with expiration (TTL)\nawait env.MY_KV.put('session:abc', sessionData, {\n  expirationTtl: 3600, \u002F\u002F Expire in 1 hour (minimum 60 seconds)\n});\n\n\u002F\u002F Write with absolute expiration\nconst expirationTime = Math.floor(Date.now() \u002F 1000) + 86400; \u002F\u002F 24 hours from now\nawait env.MY_KV.put('token', tokenValue, {\n  expiration: expirationTime, \u002F\u002F Seconds since epoch\n});\n\n\u002F\u002F Write with metadata\nawait env.MY_KV.put('config:theme', 'dark', {\n  metadata: {\n    updatedAt: Date.now(),\n    updatedBy: 'admin',\n    version: 2\n  },\n});\n\n\u002F\u002F Write with everything\nawait env.MY_KV.put('feature:flags', JSON.stringify(flags), {\n  expirationTtl: 600,\n  metadata: { source: 'api', timestamp: Date.now() },\n});\n```\n\n**CRITICAL Limits:**\n- **Key size**: Maximum 512 bytes\n- **Value size**: Maximum 25 MiB\n- **Metadata size**: Maximum 1024 bytes (JSON serialized)\n- **Write rate**: Maximum 1 write per second **per key**\n- **Expiration minimum**: 60 seconds (both TTL and absolute)\n\n**Rate Limit Handling:**\n\n```typescript\nasync function putWithRetry(\n  kv: KVNamespace,\n  key: string,\n  value: string,\n  options?: KVPutOptions\n) {\n  let attempts = 0;\n  const maxAttempts = 5;\n  let delay = 1000; \u002F\u002F Start with 1 second\n\n  while (attempts \u003C maxAttempts) {\n    try {\n      await kv.put(key, value, options);\n      return; \u002F\u002F Success\n    } catch (error) {\n      const message = (error as Error).message;\n\n      if (message.includes('429') || message.includes('Too Many Requests')) {\n        attempts++;\n        if (attempts >= maxAttempts) {\n          throw new Error('Max retry attempts reached');\n        }\n\n        console.warn(`Attempt ${attempts} failed. Retrying in ${delay}ms...`);\n        await new Promise(resolve => setTimeout(resolve, delay));\n\n        \u002F\u002F Exponential backoff\n        delay *= 2;\n      } else {\n        throw error; \u002F\u002F Different error, rethrow\n      }\n    }\n  }\n}\n```\n\n---\n\n### 3. List Operations\n\n#### `list()` - List Keys\n\n```typescript\n\u002F\u002F List all keys (up to 1000)\nconst result = await env.MY_KV.list();\n\nconsole.log(result.keys);         \u002F\u002F Array of key objects\nconsole.log(result.list_complete); \u002F\u002F boolean - false if more keys exist\nconsole.log(result.cursor);        \u002F\u002F string - for pagination\n\n\u002F\u002F List with prefix filter\nconst result = await env.MY_KV.list({\n  prefix: 'user:', \u002F\u002F Only keys starting with 'user:'\n});\n\n\u002F\u002F List with limit\nconst result = await env.MY_KV.list({\n  limit: 100, \u002F\u002F Maximum 1000 (default 1000)\n});\n\n\u002F\u002F Pagination with cursor\nlet cursor: string | undefined;\nlet allKeys: any[] = [];\n\ndo {\n  const result = await env.MY_KV.list({ cursor });\n  allKeys = allKeys.concat(result.keys);\n  cursor = result.list_complete ? undefined : result.cursor;\n} while (cursor);\n\n\u002F\u002F Combined: prefix + pagination\nlet cursor: string | undefined;\nconst userKeys: any[] = [];\n\ndo {\n  const result = await env.MY_KV.list({\n    prefix: 'user:',\n    cursor,\n  });\n\n  userKeys.push(...result.keys);\n  cursor = result.list_complete ? undefined : result.cursor;\n} while (cursor);\n```\n\n**List Response Format:**\n\n```typescript\n{\n  keys: [\n    {\n      name: \"user:123\",\n      expiration: 1234567890,  \u002F\u002F Optional: seconds since epoch\n      metadata: { ... }         \u002F\u002F Optional: metadata object\n    },\n    \u002F\u002F ... more keys\n  ],\n  list_complete: false,  \u002F\u002F true if no more keys\n  cursor: \"6Ck1la0VxJ0djhidm1MdX2FyD\"  \u002F\u002F Use for next page\n}\n```\n\n**IMPORTANT:**\n- Keys are **always** returned in lexicographically sorted order (UTF-8)\n- **Always check `list_complete`**, not `keys.length === 0`\n- Empty `keys` array doesn't mean no more data (expired\u002Fdeleted keys create \"tombstones\")\n- When paginating with `prefix`, you **must** pass the same `prefix` with each `cursor` request\n\n---\n\n### 4. Delete Operations\n\n#### `delete()` - Delete Key\n\n```typescript\n\u002F\u002F Delete single key\nawait env.MY_KV.delete('my-key');\n\n\u002F\u002F Delete always succeeds, even if key doesn't exist\nawait env.MY_KV.delete('non-existent-key'); \u002F\u002F No error\n\n\u002F\u002F Bulk delete pattern (in Worker)\nconst keysToDelete = ['key1', 'key2', 'key3', ...];\n\n\u002F\u002F Delete in parallel (careful of Worker subrequest limits)\nawait Promise.all(\n  keysToDelete.map(key => env.MY_KV.delete(key))\n);\n\n\u002F\u002F For more than 1000 keys, use REST API bulk delete (via wrangler or API)\n```\n\n**Bulk Delete via REST API:**\n\nThe Workers binding doesn't support bulk delete, but you can use the REST API (via `wrangler` or direct API calls):\n\n```bash\n# Using wrangler CLI\nnpx wrangler kv bulk delete --namespace-id=\u003CUUID> keys.json\n\n# keys.json format:\n# [\"key1\", \"key2\", \"key3\"]\n```\n\n**REST API Limit:** Up to 10,000 keys per bulk delete request.\n\n---\n\n## Advanced Patterns & Best Practices\n\n### 1. Caching Pattern with CacheTtl\n\n```typescript\nasync function getCachedData(\n  kv: KVNamespace,\n  cacheKey: string,\n  fetchFn: () => Promise\u003Cany>,\n  cacheTtl: number = 300\n) {\n  \u002F\u002F Try to get from KV cache\n  const cached = await kv.get(cacheKey, {\n    type: 'json',\n    cacheTtl, \u002F\u002F Cache at edge for faster subsequent reads\n  });\n\n  if (cached) {\n    return cached;\n  }\n\n  \u002F\u002F Cache miss - fetch fresh data\n  const data = await fetchFn();\n\n  \u002F\u002F Store in KV with expiration\n  await kv.put(cacheKey, JSON.stringify(data), {\n    expirationTtl: cacheTtl * 2, \u002F\u002F Store longer than cache\n  });\n\n  return data;\n}\n\n\u002F\u002F Usage\napp.get('\u002Fapi\u002Fdata\u002F:id', async (c) => {\n  const id = c.req.param('id');\n\n  const data = await getCachedData(\n    c.env.CACHE,\n    `data:${id}`,\n    () => fetchFromDatabase(id),\n    300 \u002F\u002F 5 minutes\n  );\n\n  return c.json(data);\n});\n```\n\n**CacheTtl Guidelines:**\n- **Minimum:** 60 seconds\n- **Default:** 60 seconds\n- **Maximum:** `Number.MAX_SAFE_INTEGER`\n- **Use case:** Frequently read, infrequently updated data\n- **Trade-off:** Higher cacheTtl = faster reads but slower update propagation\n\n---\n\n### 2. Metadata Optimization Pattern\n\nStore small values in metadata to avoid separate `get()` calls:\n\n```typescript\n\u002F\u002F ❌ Bad: Two operations\nawait env.MY_KV.put('user:123', 'active');\nconst status = await env.MY_KV.get('user:123');\n\n\u002F\u002F ✅ Good: Store in metadata with empty value\nawait env.MY_KV.put('user:123', '', {\n  metadata: {\n    status: 'active',\n    lastSeen: Date.now(),\n    plan: 'pro'\n  },\n});\n\n\u002F\u002F List returns metadata automatically\nconst users = await env.MY_KV.list({ prefix: 'user:' });\n\nusers.keys.forEach(({ name, metadata }) => {\n  console.log(name, metadata.status, metadata.plan);\n  \u002F\u002F No additional get() calls needed!\n});\n```\n\n**When to Use:**\n- ✅ Values fit in 1024 bytes\n- ✅ You frequently use `list()` operations\n- ✅ You need to filter\u002Fprocess many keys\n- ❌ Don't use for large values (use regular value storage)\n\n---\n\n### 3. Key Coalescing for Performance\n\nCombine related cold keys with hot keys:\n\n```typescript\n\u002F\u002F ❌ Bad: Many individual keys (some hot, some cold)\nawait kv.put('user:123:name', 'John');\nawait kv.put('user:123:email', 'john@example.com');\nawait kv.put('user:123:age', '30');\n\n\u002F\u002F ✅ Good: Coalesce into single hot key\nawait kv.put('user:123', JSON.stringify({\n  name: 'John',\n  email: 'john@example.com',\n  age: 30,\n}));\n\n\u002F\u002F Single read gets everything\nconst user = await kv.get\u003CUser>('user:123', { type: 'json' });\n```\n\n**Advantages:**\n- Cold keys benefit from hot key caching\n- Fewer operations = better performance\n- Single cache entry instead of multiple\n\n**Disadvantages:**\n- Can't update individual fields easily (requires read-modify-write)\n- Large coalesced values may hit memory limits\n- Concurrent updates need locking mechanism\n\n---\n\n### 4. Pagination Helper\n\n```typescript\nasync function* paginateKV(\n  kv: KVNamespace,\n  options: { prefix?: string; limit?: number } = {}\n) {\n  let cursor: string | undefined;\n\n  do {\n    const result = await kv.list({\n      prefix: options.prefix,\n      limit: options.limit || 1000,\n      cursor,\n    });\n\n    yield result.keys;\n\n    cursor = result.list_complete ? undefined : result.cursor;\n  } while (cursor);\n}\n\n\u002F\u002F Usage\napp.get('\u002Fall-users', async (c) => {\n  const allUsers = [];\n\n  for await (const keys of paginateKV(c.env.MY_KV, { prefix: 'user:' })) {\n    \u002F\u002F Process batch\n    allUsers.push(...keys.map(k => k.name));\n  }\n\n  return c.json({ users: allUsers, count: allUsers.length });\n});\n```\n\n---\n\n### 5. Feature Flags Pattern\n\n```typescript\ninterface FeatureFlags {\n  darkMode: boolean;\n  newDashboard: boolean;\n  betaFeatures: boolean;\n}\n\nasync function getFeatureFlags(\n  kv: KVNamespace,\n  userId?: string\n): Promise\u003CFeatureFlags> {\n  \u002F\u002F Try user-specific flags first\n  if (userId) {\n    const userFlags = await kv.get\u003CFeatureFlags>(`flags:user:${userId}`, {\n      type: 'json',\n      cacheTtl: 300,\n    });\n    if (userFlags) return userFlags;\n  }\n\n  \u002F\u002F Fallback to global flags\n  const globalFlags = await kv.get\u003CFeatureFlags>('flags:global', {\n    type: 'json',\n    cacheTtl: 300,\n  });\n\n  return globalFlags || {\n    darkMode: false,\n    newDashboard: false,\n    betaFeatures: false,\n  };\n}\n\n\u002F\u002F Update global flags\napp.post('\u002Fadmin\u002Fflags', async (c) => {\n  const flags = await c.req.json\u003CFeatureFlags>();\n\n  await c.env.CONFIG.put('flags:global', JSON.stringify(flags), {\n    metadata: { updatedAt: Date.now() },\n  });\n\n  return c.json({ success: true });\n});\n```\n\n---\n\n## Understanding Eventual Consistency\n\nKV is **eventually consistent** across Cloudflare's global network:\n\n### How It Works:\n\n1. **Writes** are immediately visible in the **same location**\n2. **Other locations** see the update within **~60 seconds** (or your `cacheTtl` value)\n3. **Cached reads** may return stale data during propagation\n\n### Implications:\n\n```typescript\n\u002F\u002F In Tokyo data center:\nawait env.MY_KV.put('counter', '1');\nconst value1 = await env.MY_KV.get('counter'); \u002F\u002F \"1\" ✅\n\n\u002F\u002F In London data center (within 60 seconds):\nconst value2 = await env.MY_KV.get('counter'); \u002F\u002F Might still be old value ⚠️\n\n\u002F\u002F After 60+ seconds:\nconst value3 = await env.MY_KV.get('counter'); \u002F\u002F \"1\" ✅\n```\n\n### Best Practices:\n\n✅ **Use KV for:**\n- Read-heavy workloads (100:1 read\u002Fwrite ratio)\n- Data that doesn't require immediate global consistency\n- Configuration, feature flags, caching\n- User preferences, session data\n\n❌ **Don't use KV for:**\n- Financial transactions requiring atomic operations\n- Data requiring strong consistency\n- High-frequency writes to same key (>1\u002Fsecond)\n- Critical data where stale reads are unacceptable\n\n**If you need strong consistency, use [Durable Objects](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F).**\n\n---\n\n## Wrangler CLI Operations\n\n### Create Namespace\n\n```bash\n# Production namespace\nnpx wrangler kv namespace create MY_NAMESPACE\n\n# Preview\u002Fdevelopment namespace\nnpx wrangler kv namespace create MY_NAMESPACE --preview\n```\n\n### List Namespaces\n\n```bash\nnpx wrangler kv namespace list\n```\n\n### Write Key-Value Pairs\n\n```bash\n# Write single key\nnpx wrangler kv key put --binding=MY_NAMESPACE \"my-key\" \"my-value\"\n\n# Write from file\nnpx wrangler kv key put --binding=MY_NAMESPACE \"config\" --path=config.json\n\n# Write with metadata\nnpx wrangler kv key put --binding=MY_NAMESPACE \"key\" \"value\" --metadata='{\"version\":1}'\n\n# Write with TTL (seconds)\nnpx wrangler kv key put --binding=MY_NAMESPACE \"session\" \"data\" --ttl=3600\n```\n\n### Read Key-Value Pairs\n\n```bash\n# Read single key\nnpx wrangler kv key get --binding=MY_NAMESPACE \"my-key\"\n\n# Read to file\nnpx wrangler kv key get --binding=MY_NAMESPACE \"image\" --path=image.png\n```\n\n### List Keys\n\n```bash\n# List all keys\nnpx wrangler kv key list --binding=MY_NAMESPACE\n\n# List with prefix\nnpx wrangler kv key list --binding=MY_NAMESPACE --prefix=\"user:\"\n\n# Pretty print\nnpx wrangler kv key list --binding=MY_NAMESPACE | jq \".\"\n```\n\n### Delete Keys\n\n```bash\n# Delete single key\nnpx wrangler kv key delete --binding=MY_NAMESPACE \"my-key\"\n```\n\n### Bulk Operations\n\n```bash\n# Bulk write (up to 10,000 keys)\nnpx wrangler kv bulk put --binding=MY_NAMESPACE data.json\n\n# data.json format:\n# [\n#   {\"key\": \"key1\", \"value\": \"value1\"},\n#   {\"key\": \"key2\", \"value\": \"value2\", \"expiration_ttl\": 3600}\n# ]\n\n# Bulk delete (up to 10,000 keys)\nnpx wrangler kv bulk delete --binding=MY_NAMESPACE keys.json\n\n# keys.json format:\n# [\"key1\", \"key2\", \"key3\"]\n```\n\n---\n\n## Limits & Quotas\n\n| Feature | Free Plan | Paid Plan |\n|---------|-----------|-----------|\n| **Reads per day** | 100,000 | Unlimited |\n| **Writes per day** (different keys) | 1,000 | Unlimited |\n| **Writes per key per second** | 1 | 1 |\n| **Operations per Worker invocation** | 1,000 | 1,000 |\n| **Namespaces per account** | 1,000 | 1,000 |\n| **Storage per account** | 1 GB | Unlimited |\n| **Storage per namespace** | 1 GB | Unlimited |\n| **Keys per namespace** | Unlimited | Unlimited |\n| **Key size** | 512 bytes | 512 bytes |\n| **Metadata size** | 1024 bytes | 1024 bytes |\n| **Value size** | 25 MiB | 25 MiB |\n| **Minimum cacheTtl** | 60 seconds | 60 seconds |\n| **Maximum cacheTtl** | Number.MAX_SAFE_INTEGER | Number.MAX_SAFE_INTEGER |\n\n**Important Notes:**\n- **1 write\u002Fsecond per key**: Concurrent writes to the same key cause 429 errors\n- **1000 operations per invocation**: Bulk operations count as **1 operation**\n- **Bulk reads** (reading multiple keys) count as a single operation\n- **REST API** is subject to [Cloudflare API rate limits](https:\u002F\u002Fdevelopers.cloudflare.com\u002Ffundamentals\u002Fapi\u002Freference\u002Flimits\u002F)\n\n---\n\n## TypeScript Types\n\n```typescript\n\u002F\u002F KVNamespace type is provided by @cloudflare\u002Fworkers-types\ninterface KVNamespace {\n  get(key: string, options?: Partial\u003CKVGetOptions\u003Cundefined>>): Promise\u003Cstring | null>;\n  get(key: string, type: \"text\"): Promise\u003Cstring | null>;\n  get\u003CExpectedValue = unknown>(key: string, type: \"json\"): Promise\u003CExpectedValue | null>;\n  get(key: string, type: \"arrayBuffer\"): Promise\u003CArrayBuffer | null>;\n  get(key: string, type: \"stream\"): Promise\u003CReadableStream | null>;\n  get(key: string, options?: KVGetOptions\u003C\"text\">): Promise\u003Cstring | null>;\n  get\u003CExpectedValue = unknown>(key: string, options?: KVGetOptions\u003C\"json\">): Promise\u003CExpectedValue | null>;\n  get(key: string, options?: KVGetOptions\u003C\"arrayBuffer\">): Promise\u003CArrayBuffer | null>;\n  get(key: string, options?: KVGetOptions\u003C\"stream\">): Promise\u003CReadableStream | null>;\n  get(keys: string[]): Promise\u003CMap\u003Cstring, string | null>>;\n  get(keys: string[], type: \"text\"): Promise\u003CMap\u003Cstring, string | null>>;\n  get\u003CExpectedValue = unknown>(keys: string[], type: \"json\"): Promise\u003CMap\u003Cstring, ExpectedValue | null>>;\n\n  getWithMetadata\u003CMetadata = unknown>(key: string, options?: Partial\u003CKVGetOptions\u003Cundefined>>): Promise\u003CKVGetWithMetadataResult\u003Cstring, Metadata>>;\n  getWithMetadata\u003CMetadata = unknown>(key: string, type: \"text\"): Promise\u003CKVGetWithMetadataResult\u003Cstring, Metadata>>;\n  getWithMetadata\u003CExpectedValue = unknown, Metadata = unknown>(key: string, type: \"json\"): Promise\u003CKVGetWithMetadataResult\u003CExpectedValue, Metadata>>;\n  getWithMetadata\u003CMetadata = unknown>(key: string, options?: KVGetOptions\u003C\"text\">): Promise\u003CKVGetWithMetadataResult\u003Cstring, Metadata>>;\n  getWithMetadata\u003CExpectedValue = unknown, Metadata = unknown>(key: string, options?: KVGetOptions\u003C\"json\">): Promise\u003CKVGetWithMetadataResult\u003CExpectedValue, Metadata>>;\n  getWithMetadata\u003CMetadata = unknown>(keys: string[]): Promise\u003CMap\u003Cstring, KVGetWithMetadataResult\u003Cstring, Metadata>>>;\n  getWithMetadata\u003CMetadata = unknown>(keys: string[], type: \"text\"): Promise\u003CMap\u003Cstring, KVGetWithMetadataResult\u003Cstring, Metadata>>>;\n  getWithMetadata\u003CExpectedValue = unknown, Metadata = unknown>(keys: string[], type: \"json\"): Promise\u003CMap\u003Cstring, KVGetWithMetadataResult\u003CExpectedValue, Metadata>>>;\n\n  put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVPutOptions): Promise\u003Cvoid>;\n\n  delete(key: string): Promise\u003Cvoid>;\n\n  list\u003CMetadata = unknown>(options?: KVListOptions): Promise\u003CKVListResult\u003CMetadata>>;\n}\n\ninterface KVGetOptions\u003CType> {\n  type: Type;\n  cacheTtl?: number;\n}\n\ninterface KVGetWithMetadataResult\u003CValue, Metadata> {\n  value: Value | null;\n  metadata: Metadata | null;\n}\n\ninterface KVPutOptions {\n  expiration?: number;        \u002F\u002F Seconds since epoch\n  expirationTtl?: number;     \u002F\u002F Seconds from now (minimum 60)\n  metadata?: any;             \u002F\u002F Serializable to JSON, max 1024 bytes\n}\n\ninterface KVListOptions {\n  prefix?: string;\n  limit?: number;   \u002F\u002F Default 1000, max 1000\n  cursor?: string;\n}\n\ninterface KVListResult\u003CMetadata = unknown> {\n  keys: {\n    name: string;\n    expiration?: number;\n    metadata?: Metadata;\n  }[];\n  list_complete: boolean;\n  cursor?: string;\n}\n```\n\n---\n\n## Error Handling\n\n### Common Errors\n\n#### 1. Rate Limit (429 Too Many Requests)\n\n```typescript\ntry {\n  await env.MY_KV.put('counter', '1');\n  await env.MY_KV.put('counter', '2'); \u002F\u002F Too fast! \u003C 1 second\n} catch (error) {\n  \u002F\u002F Error: KV PUT failed: 429 Too Many Requests\n  console.error(error);\n}\n\n\u002F\u002F Solution: Use retry with backoff (see putWithRetry example above)\n```\n\n#### 2. Value Too Large\n\n```typescript\nconst largeValue = 'x'.repeat(26 * 1024 * 1024); \u002F\u002F > 25 MiB\n\ntry {\n  await env.MY_KV.put('large', largeValue);\n} catch (error) {\n  \u002F\u002F Error: Value too large\n  console.error(error);\n}\n\n\u002F\u002F Solution: Check size before writing\nif (value.length > 25 * 1024 * 1024) {\n  throw new Error('Value exceeds 25 MiB limit');\n}\n```\n\n#### 3. Metadata Too Large\n\n```typescript\nconst metadata = { data: 'x'.repeat(2000) }; \u002F\u002F > 1024 bytes serialized\n\ntry {\n  await env.MY_KV.put('key', 'value', { metadata });\n} catch (error) {\n  \u002F\u002F Error: Metadata too large\n  console.error(error);\n}\n\n\u002F\u002F Solution: Validate metadata size\nconst serialized = JSON.stringify(metadata);\nif (serialized.length > 1024) {\n  throw new Error('Metadata exceeds 1024 byte limit');\n}\n```\n\n#### 4. Invalid CacheTtl\n\n```typescript\n\u002F\u002F ❌ Too low\nawait env.MY_KV.get('key', { cacheTtl: 30 }); \u002F\u002F Error: minimum is 60\n\n\u002F\u002F ✅ Correct\nawait env.MY_KV.get('key', { cacheTtl: 60 });\n```\n\n---\n\n## Always Do ✅\n\n1. **Use bulk operations** when reading multiple keys (counts as 1 operation)\n2. **Set cacheTtl** for frequently-read, infrequently-updated data\n3. **Store small values in metadata** when using `list()` frequently\n4. **Check `list_complete`** when paginating, not `keys.length === 0`\n5. **Use retry logic with exponential backoff** for write operations\n6. **Validate sizes** before writing (key 512 bytes, value 25 MiB, metadata 1 KB)\n7. **Use preview namespaces** for local development\n8. **Set appropriate TTLs** for cache invalidation (minimum 60 seconds)\n9. **Coalesce related keys** for better caching performance\n10. **Use KV for read-heavy workloads** (100:1 read\u002Fwrite ratio ideal)\n\n---\n\n## Never Do ❌\n\n1. **Never write to same key >1\u002Fsecond** - Causes 429 rate limit errors\n2. **Never assume immediate global consistency** - Takes ~60 seconds to propagate\n3. **Never use KV for atomic operations** - Use Durable Objects instead\n4. **Never set cacheTtl \u003C60 seconds** - Will fail\n5. **Never commit namespace IDs to public repos** - Use environment variables\n6. **Never exceed 1000 operations per invocation** - Use bulk operations\n7. **Never rely on write order** - Eventual consistency means no guarantees\n8. **Never store sensitive data without encryption** - KV is not encrypted at rest by default\n9. **Never use KV for high-frequency writes** - Not designed for write-heavy workloads\n10. **Never forget to handle null values** - `get()` returns `null` if key doesn't exist\n\n---\n\n## Troubleshooting\n\n### Issue: \"429 Too Many Requests\" on writes\n\n**Cause:** Writing to same key more than once per second\n\n**Solution:**\n```typescript\n\u002F\u002F ❌ Bad\nfor (let i = 0; i \u003C 10; i++) {\n  await kv.put('counter', String(i)); \u002F\u002F Rate limit!\n}\n\n\u002F\u002F ✅ Good - consolidate writes\nconst finalValue = '9';\nawait kv.put('counter', finalValue);\n\n\u002F\u002F ✅ Good - use retry with backoff\nawait putWithRetry(kv, 'counter', String(i));\n```\n\n---\n\n### Issue: Stale reads after write\n\n**Cause:** Eventual consistency - writes take up to 60 seconds to propagate globally\n\n**Solution:**\n```typescript\n\u002F\u002F Accept that reads may be stale for up to 60 seconds\n\u002F\u002F OR use Durable Objects for strong consistency\n\u002F\u002F OR implement application-level cache invalidation\n```\n\n---\n\n### Issue: \"Operations limit exceeded\"\n\n**Cause:** More than 1000 KV operations in single Worker invocation\n\n**Solution:**\n```typescript\n\u002F\u002F ❌ Bad - 5000 operations\nconst keys = Array.from({ length: 5000 }, (_, i) => `key${i}`);\nfor (const key of keys) {\n  await kv.get(key); \u002F\u002F Exceeds 1000 limit\n}\n\n\u002F\u002F ✅ Good - 1 operation (bulk read)\nconst values = await kv.get(keys);\n```\n\n---\n\n### Issue: List returns empty but cursor exists\n\n**Cause:** Recently deleted\u002Fexpired keys create \"tombstones\" in the list\n\n**Solution:**\n```typescript\n\u002F\u002F Always check list_complete, not keys.length\nlet cursor: string | undefined;\n\ndo {\n  const result = await kv.list({ cursor });\n\n  \u002F\u002F Process keys even if empty\n  processKeys(result.keys);\n\n  \u002F\u002F CORRECT: Check list_complete\n  cursor = result.list_complete ? undefined : result.cursor;\n} while (cursor);\n```\n\n---\n\n## Production Checklist\n\nBefore deploying to production:\n\n- [ ] Environment-specific namespaces configured (`id` vs `preview_id`)\n- [ ] Namespace IDs stored in environment variables (not hardcoded)\n- [ ] Rate limit retry logic implemented for writes\n- [ ] Appropriate `cacheTtl` values set for reads\n- [ ] Metadata sizes validated (\u003C1024 bytes)\n- [ ] Value sizes validated (\u003C25 MiB)\n- [ ] Key sizes validated (\u003C512 bytes)\n- [ ] Bulk operations used where possible\n- [ ] Pagination implemented correctly for `list()`\n- [ ] Error handling for null values\n- [ ] Monitoring\u002Falerting for rate limits\n- [ ] Documentation for eventual consistency behavior\n\n---\n\n## Related Documentation\n\n- [Cloudflare KV Docs](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002F)\n- [KV API Reference](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002Fapi\u002F)\n- [KV Limits](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002Fplatform\u002Flimits\u002F)\n- [How KV Works](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002Fconcepts\u002Fhow-kv-works\u002F)\n- [Wrangler KV Commands](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkers\u002Fwrangler\u002Fcommands\u002F#kv)\n\n---\n\n**Last Updated**: 2025-10-21\n**Version**: 1.0.0\n**Maintainer**: Jeremy Dawes | jeremy@jezweb.net\n","# Cloudflare Workers KV\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-21\n**Dependencies**: cloudflare-worker-base (for Worker setup)\n**Latest Versions**: wrangler@4.43.0, @cloudflare\u002Fworkers-types@4.20251014.0\n\n---\n\n## Quick Start (5 Minutes)\n\n### 1. Create KV Namespace\n\n```bash\n# Create a new KV namespace\nnpx wrangler kv namespace create MY_NAMESPACE\n\n# Output includes namespace_id - save this!\n# ✅ Success!\n# Add the following to your wrangler.toml or wrangler.jsonc:\n#\n# [[kv_namespaces]]\n# binding = \"MY_NAMESPACE\"\n# id = \"\u003CUUID>\"\n```\n\n**For development (preview) namespace:**\n\n```bash\nnpx wrangler kv namespace create MY_NAMESPACE --preview\n\n# Output:\n# [[kv_namespaces]]\n# binding = \"MY_NAMESPACE\"\n# preview_id = \"\u003CUUID>\"\n```\n\n### 2. Configure Bindings\n\nAdd to your `wrangler.jsonc`:\n\n```jsonc\n{\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-11\",\n  \"kv_namespaces\": [\n    {\n      \"binding\": \"MY_NAMESPACE\",          \u002F\u002F Available as env.MY_NAMESPACE\n      \"id\": \"\u003Cproduction-uuid>\",           \u002F\u002F Production namespace ID\n      \"preview_id\": \"\u003Cpreview-uuid>\"       \u002F\u002F Local dev namespace ID (optional)\n    }\n  ]\n}\n```\n\n**Or use `wrangler.toml`:**\n\n```toml\nname = \"my-worker\"\nmain = \"src\u002Findex.ts\"\ncompatibility_date = \"2025-10-11\"\n\n[[kv_namespaces]]\nbinding = \"MY_NAMESPACE\"\nid = \"\u003Cproduction-uuid>\"\npreview_id = \"\u003Cpreview-uuid>\"  # optional\n```\n\n**CRITICAL:**\n- `binding` is how you access the namespace in code (`env.MY_NAMESPACE`)\n- `id` is the production namespace UUID\n- `preview_id` is for local dev (optional, separate namespace)\n- **Never commit real namespace IDs to public repos** - use environment variables or secrets\n\n### 3. Write Your First Key-Value Pair\n\n```typescript\nimport { Hono } from 'hono';\n\ntype Bindings = {\n  MY_NAMESPACE: KVNamespace;\n};\n\nconst app = new Hono\u003C{ Bindings: Bindings }>();\n\napp.post('\u002Fset\u002F:key', async (c) => {\n  const key = c.req.param('key');\n  const value = await c.req.text();\n\n  \u002F\u002F Simple write\n  await c.env.MY_NAMESPACE.put(key, value);\n\n  return c.json({ success: true, key });\n});\n\napp.get('\u002Fget\u002F:key', async (c) => {\n  const key = c.req.param('key');\n  const value = await c.env.MY_NAMESPACE.get(key);\n\n  if (!value) {\n    return c.json({ error: 'Not found' }, 404);\n  }\n\n  return c.json({ value });\n});\n\nexport default app;\n```\n\n### 4. Test Locally\n\n```bash\n# Start local development server\nnpm run dev\n\n# In another terminal, test the endpoints\ncurl -X POST http:\u002F\u002Flocalhost:8787\u002Fset\u002Ftest -d \"Hello KV\"\n# {\"success\":true,\"key\":\"test\"}\n\ncurl http:\u002F\u002Flocalhost:8787\u002Fget\u002Ftest\n# {\"value\":\"Hello KV\"}\n```\n\n---\n\n## Complete Workers KV API\n\n### 1. Read Operations\n\n#### `get()` - Read Single Key\n\n```typescript\n\u002F\u002F Get as string (default)\nconst value: string | null = await env.MY_KV.get('my-key');\n\n\u002F\u002F Get as JSON\nconst data: MyType | null = await env.MY_KV.get('my-key', { type: 'json' });\n\n\u002F\u002F Get as ArrayBuffer\nconst buffer: ArrayBuffer | null = await env.MY_KV.get('my-key', { type: 'arrayBuffer' });\n\n\u002F\u002F Get as ReadableStream\nconst stream: ReadableStream | null = await env.MY_KV.get('my-key', { type: 'stream' });\n\n\u002F\u002F Get with cache optimization\nconst value = await env.MY_KV.get('my-key', {\n  type: 'text',\n  cacheTtl: 300, \u002F\u002F Cache at edge for 5 minutes (minimum 60 seconds)\n});\n```\n\n#### `get()` - Read Multiple Keys (Bulk)\n\n```typescript\n\u002F\u002F Read multiple keys at once (counts as 1 operation)\nconst keys = ['key1', 'key2', 'key3'];\nconst values: Map\u003Cstring, string | null> = await env.MY_KV.get(keys);\n\n\u002F\u002F Access values\nconst value1 = values.get('key1'); \u002F\u002F string | null\nconst value2 = values.get('key2'); \u002F\u002F string | null\n\n\u002F\u002F Convert to object\nconst obj = Object.fromEntries(values);\n```\n\n#### `getWithMetadata()` - Read with Metadata\n\n```typescript\n\u002F\u002F Get single key with metadata\nconst { value, metadata } = await env.MY_KV.getWithMetadata('my-key');\n\n\u002F\u002F value: string | null\n\u002F\u002F metadata: any | null\n\n\u002F\u002F Get as JSON with metadata\nconst { value, metadata } = await env.MY_KV.getWithMetadata\u003CMyType>('my-key', {\n  type: 'json',\n  cacheTtl: 300,\n});\n\n\u002F\u002F Get multiple keys with metadata\nconst keys = ['key1', 'key2'];\nconst result: Map\u003Cstring, { value: string | null, metadata: any | null }> =\n  await env.MY_KV.getWithMetadata(keys);\n\nfor (const [key, data] of result) {\n  console.log(key, data.value, data.metadata);\n}\n```\n\n**Type Options:**\n- `text` (default) - Returns `string`\n- `json` - Parses JSON, returns `object`\n- `arrayBuffer` - Returns `ArrayBuffer`\n- `stream` - Returns `ReadableStream`\n\n**Note:** Bulk read with `get(keys[])` only supports `text` and `json` types. For `arrayBuffer` or `stream`, use individual `get()` calls with `Promise.all()`.\n\n---\n\n### 2. Write Operations\n\n#### `put()` - Write Key-Value Pair\n\n```typescript\n\u002F\u002F Simple write\nawait env.MY_KV.put('key', 'value');\n\n\u002F\u002F Write JSON\nawait env.MY_KV.put('user:123', JSON.stringify({ name: 'John', age: 30 }));\n\n\u002F\u002F Write with expiration (TTL)\nawait env.MY_KV.put('session:abc', sessionData, {\n  expirationTtl: 3600, \u002F\u002F Expire in 1 hour (minimum 60 seconds)\n});\n\n\u002F\u002F Write with absolute expiration\nconst expirationTime = Math.floor(Date.now() \u002F 1000) + 86400; \u002F\u002F 24 hours from now\nawait env.MY_KV.put('token', tokenValue, {\n  expiration: expirationTime, \u002F\u002F Seconds since epoch\n});\n\n\u002F\u002F Write with metadata\nawait env.MY_KV.put('config:theme', 'dark', {\n  metadata: {\n    updatedAt: Date.now(),\n    updatedBy: 'admin',\n    version: 2\n  },\n});\n\n\u002F\u002F Write with everything\nawait env.MY_KV.put('feature:flags', JSON.stringify(flags), {\n  expirationTtl: 600,\n  metadata: { source: 'api', timestamp: Date.now() },\n});\n```\n\n**CRITICAL Limits:**\n- **Key size**: Maximum 512 bytes\n- **Value size**: Maximum 25 MiB\n- **Metadata size**: Maximum 1024 bytes (JSON serialized)\n- **Write rate**: Maximum 1 write per second **per key**\n- **Expiration minimum**: 60 seconds (both TTL and absolute)\n\n**Rate Limit Handling:**\n\n```typescript\nasync function putWithRetry(\n  kv: KVNamespace,\n  key: string,\n  value: string,\n  options?: KVPutOptions\n) {\n  let attempts = 0;\n  const maxAttempts = 5;\n  let delay = 1000; \u002F\u002F Start with 1 second\n\n  while (attempts \u003C maxAttempts) {\n    try {\n      await kv.put(key, value, options);\n      return; \u002F\u002F Success\n    } catch (error) {\n      const message = (error as Error).message;\n\n      if (message.includes('429') || message.includes('Too Many Requests')) {\n        attempts++;\n        if (attempts >= maxAttempts) {\n          throw new Error('Max retry attempts reached');\n        }\n\n        console.warn(`Attempt ${attempts} failed. Retrying in ${delay}ms...`);\n        await new Promise(resolve => setTimeout(resolve, delay));\n\n        \u002F\u002F Exponential backoff\n        delay *= 2;\n      } else {\n        throw error; \u002F\u002F Different error, rethrow\n      }\n    }\n  }\n}\n```\n\n---\n\n### 3. List Operations\n\n#### `list()` - List Keys\n\n```typescript\n\u002F\u002F List all keys (up to 1000)\nconst result = await env.MY_KV.list();\n\nconsole.log(result.keys);         \u002F\u002F Array of key objects\nconsole.log(result.list_complete); \u002F\u002F boolean - false if more keys exist\nconsole.log(result.cursor);        \u002F\u002F string - for pagination\n\n\u002F\u002F List with prefix filter\nconst result = await env.MY_KV.list({\n  prefix: 'user:', \u002F\u002F Only keys starting with 'user:'\n});\n\n\u002F\u002F List with limit\nconst result = await env.MY_KV.list({\n  limit: 100, \u002F\u002F Maximum 1000 (default 1000)\n});\n\n\u002F\u002F Pagination with cursor\nlet cursor: string | undefined;\nlet allKeys: any[] = [];\n\ndo {\n  const result = await env.MY_KV.list({ cursor });\n  allKeys = allKeys.concat(result.keys);\n  cursor = result.list_complete ? undefined : result.cursor;\n} while (cursor);\n\n\u002F\u002F Combined: prefix + pagination\nlet cursor: string | undefined;\nconst userKeys: any[] = [];\n\ndo {\n  const result = await env.MY_KV.list({\n    prefix: 'user:',\n    cursor,\n  });\n\n  userKeys.push(...result.keys);\n  cursor = result.list_complete ? undefined : result.cursor;\n} while (cursor);\n```\n\n**List Response Format:**\n\n```typescript\n{\n  keys: [\n    {\n      name: \"user:123\",\n      expiration: 1234567890,  \u002F\u002F Optional: seconds since epoch\n      metadata: { ... }         \u002F\u002F Optional: metadata object\n    },\n    \u002F\u002F ... more keys\n  ],\n  list_complete: false,  \u002F\u002F true if no more keys\n  cursor: \"6Ck1la0VxJ0djhidm1MdX2FyD\"  \u002F\u002F Use for next page\n}\n```\n\n**IMPORTANT:**\n- Keys are **always** returned in lexicographically sorted order (UTF-8)\n- **Always check `list_complete`**, not `keys.length === 0`\n- Empty `keys` array doesn't mean no more data (expired\u002Fdeleted keys create \"tombstones\")\n- When paginating with `prefix`, you **must** pass the same `prefix` with each `cursor` request\n\n---\n\n### 4. Delete Operations\n\n#### `delete()` - Delete Key\n\n```typescript\n\u002F\u002F Delete single key\nawait env.MY_KV.delete('my-key');\n\n\u002F\u002F Delete always succeeds, even if key doesn't exist\nawait env.MY_KV.delete('non-existent-key'); \u002F\u002F No error\n\n\u002F\u002F Bulk delete pattern (in Worker)\nconst keysToDelete = ['key1', 'key2', 'key3', ...];\n\n\u002F\u002F Delete in parallel (careful of Worker subrequest limits)\nawait Promise.all(\n  keysToDelete.map(key => env.MY_KV.delete(key))\n);\n\n\u002F\u002F For more than 1000 keys, use REST API bulk delete (via wrangler or API)\n```\n\n**Bulk Delete via REST API:**\n\nThe Workers binding doesn't support bulk delete, but you can use the REST API (via `wrangler` or direct API calls):\n\n```bash\n# Using wrangler CLI\nnpx wrangler kv bulk delete --namespace-id=\u003CUUID> keys.json\n\n# keys.json format:\n# [\"key1\", \"key2\", \"key3\"]\n```\n\n**REST API Limit:** Up to 10,000 keys per bulk delete request.\n\n---\n\n## Advanced Patterns & Best Practices\n\n### 1. Caching Pattern with CacheTtl\n\n```typescript\nasync function getCachedData(\n  kv: KVNamespace,\n  cacheKey: string,\n  fetchFn: () => Promise\u003Cany>,\n  cacheTtl: number = 300\n) {\n  \u002F\u002F Try to get from KV cache\n  const cached = await kv.get(cacheKey, {\n    type: 'json',\n    cacheTtl, \u002F\u002F Cache at edge for faster subsequent reads\n  });\n\n  if (cached) {\n    return cached;\n  }\n\n  \u002F\u002F Cache miss - fetch fresh data\n  const data = await fetchFn();\n\n  \u002F\u002F Store in KV with expiration\n  await kv.put(cacheKey, JSON.stringify(data), {\n    expirationTtl: cacheTtl * 2, \u002F\u002F Store longer than cache\n  });\n\n  return data;\n}\n\n\u002F\u002F Usage\napp.get('\u002Fapi\u002Fdata\u002F:id', async (c) => {\n  const id = c.req.param('id');\n\n  const data = await getCachedData(\n    c.env.CACHE,\n    `data:${id}`,\n    () => fetchFromDatabase(id),\n    300 \u002F\u002F 5 minutes\n  );\n\n  return c.json(data);\n});\n```\n\n**CacheTtl Guidelines:**\n- **Minimum:** 60 seconds\n- **Default:** 60 seconds\n- **Maximum:** `Number.MAX_SAFE_INTEGER`\n- **Use case:** Frequently read, infrequently updated data\n- **Trade-off:** Higher cacheTtl = faster reads but slower update propagation\n\n---\n\n### 2. Metadata Optimization Pattern\n\nStore small values in metadata to avoid separate `get()` calls:\n\n```typescript\n\u002F\u002F ❌ Bad: Two operations\nawait env.MY_KV.put('user:123', 'active');\nconst status = await env.MY_KV.get('user:123');\n\n\u002F\u002F ✅ Good: Store in metadata with empty value\nawait env.MY_KV.put('user:123', '', {\n  metadata: {\n    status: 'active',\n    lastSeen: Date.now(),\n    plan: 'pro'\n  },\n});\n\n\u002F\u002F List returns metadata automatically\nconst users = await env.MY_KV.list({ prefix: 'user:' });\n\nusers.keys.forEach(({ name, metadata }) => {\n  console.log(name, metadata.status, metadata.plan);\n  \u002F\u002F No additional get() calls needed!\n});\n```\n\n**When to Use:**\n- ✅ Values fit in 1024 bytes\n- ✅ You frequently use `list()` operations\n- ✅ You need to filter\u002Fprocess many keys\n- ❌ Don't use for large values (use regular value storage)\n\n---\n\n### 3. Key Coalescing for Performance\n\nCombine related cold keys with hot keys:\n\n```typescript\n\u002F\u002F ❌ Bad: Many individual keys (some hot, some cold)\nawait kv.put('user:123:name', 'John');\nawait kv.put('user:123:email', 'john@example.com');\nawait kv.put('user:123:age', '30');\n\n\u002F\u002F ✅ Good: Coalesce into single hot key\nawait kv.put('user:123', JSON.stringify({\n  name: 'John',\n  email: 'john@example.com',\n  age: 30,\n}));\n\n\u002F\u002F Single read gets everything\nconst user = await kv.get\u003CUser>('user:123', { type: 'json' });\n```\n\n**Advantages:**\n- Cold keys benefit from hot key caching\n- Fewer operations = better performance\n- Single cache entry instead of multiple\n\n**Disadvantages:**\n- Can't update individual fields easily (requires read-modify-write)\n- Large coalesced values may hit memory limits\n- Concurrent updates need locking mechanism\n\n---\n\n### 4. Pagination Helper\n\n```typescript\nasync function* paginateKV(\n  kv: KVNamespace,\n  options: { prefix?: string; limit?: number } = {}\n) {\n  let cursor: string | undefined;\n\n  do {\n    const result = await kv.list({\n      prefix: options.prefix,\n      limit: options.limit || 1000,\n      cursor,\n    });\n\n    yield result.keys;\n\n    cursor = result.list_complete ? undefined : result.cursor;\n  } while (cursor);\n}\n\n\u002F\u002F Usage\napp.get('\u002Fall-users', async (c) => {\n  const allUsers = [];\n\n  for await (const keys of paginateKV(c.env.MY_KV, { prefix: 'user:' })) {\n    \u002F\u002F Process batch\n    allUsers.push(...keys.map(k => k.name));\n  }\n\n  return c.json({ users: allUsers, count: allUsers.length });\n});\n```\n\n---\n\n### 5. Feature Flags Pattern\n\n```typescript\ninterface FeatureFlags {\n  darkMode: boolean;\n  newDashboard: boolean;\n  betaFeatures: boolean;\n}\n\nasync function getFeatureFlags(\n  kv: KVNamespace,\n  userId?: string\n): Promise\u003CFeatureFlags> {\n  \u002F\u002F Try user-specific flags first\n  if (userId) {\n    const userFlags = await kv.get\u003CFeatureFlags>(`flags:user:${userId}`, {\n      type: 'json',\n      cacheTtl: 300,\n    });\n    if (userFlags) return userFlags;\n  }\n\n  \u002F\u002F Fallback to global flags\n  const globalFlags = await kv.get\u003CFeatureFlags>('flags:global', {\n    type: 'json',\n    cacheTtl: 300,\n  });\n\n  return globalFlags || {\n    darkMode: false,\n    newDashboard: false,\n    betaFeatures: false,\n  };\n}\n\n\u002F\u002F Update global flags\napp.post('\u002Fadmin\u002Fflags', async (c) => {\n  const flags = await c.req.json\u003CFeatureFlags>();\n\n  await c.env.CONFIG.put('flags:global', JSON.stringify(flags), {\n    metadata: { updatedAt: Date.now() },\n  });\n\n  return c.json({ success: true });\n});\n```\n\n---\n\n## Understanding Eventual Consistency\n\nKV is **eventually consistent** across Cloudflare's global network:\n\n### How It Works:\n\n1. **Writes** are immediately visible in the **same location**\n2. **Other locations** see the update within **~60 seconds** (or your `cacheTtl` value)\n3. **Cached reads** may return stale data during propagation\n\n### Implications:\n\n```typescript\n\u002F\u002F In Tokyo data center:\nawait env.MY_KV.put('counter', '1');\nconst value1 = await env.MY_KV.get('counter'); \u002F\u002F \"1\" ✅\n\n\u002F\u002F In London data center (within 60 seconds):\nconst value2 = await env.MY_KV.get('counter'); \u002F\u002F Might still be old value ⚠️\n\n\u002F\u002F After 60+ seconds:\nconst value3 = await env.MY_KV.get('counter'); \u002F\u002F \"1\" ✅\n```\n\n### Best Practices:\n\n✅ **Use KV for:**\n- Read-heavy workloads (100:1 read\u002Fwrite ratio)\n- Data that doesn't require immediate global consistency\n- Configuration, feature flags, caching\n- User preferences, session data\n\n❌ **Don't use KV for:**\n- Financial transactions requiring atomic operations\n- Data requiring strong consistency\n- High-frequency writes to same key (>1\u002Fsecond)\n- Critical data where stale reads are unacceptable\n\n**If you need strong consistency, use [Durable Objects](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F).**\n\n---\n\n## Wrangler CLI Operations\n\n### Create Namespace\n\n```bash\n# Production namespace\nnpx wrangler kv namespace create MY_NAMESPACE\n\n# Preview\u002Fdevelopment namespace\nnpx wrangler kv namespace create MY_NAMESPACE --preview\n```\n\n### List Namespaces\n\n```bash\nnpx wrangler kv namespace list\n```\n\n### Write Key-Value Pairs\n\n```bash\n# Write single key\nnpx wrangler kv key put --binding=MY_NAMESPACE \"my-key\" \"my-value\"\n\n# Write from file\nnpx wrangler kv key put --binding=MY_NAMESPACE \"config\" --path=config.json\n\n# Write with metadata\nnpx wrangler kv key put --binding=MY_NAMESPACE \"key\" \"value\" --metadata='{\"version\":1}'\n\n# Write with TTL (seconds)\nnpx wrangler kv key put --binding=MY_NAMESPACE \"session\" \"data\" --ttl=3600\n```\n\n### Read Key-Value Pairs\n\n```bash\n# Read single key\nnpx wrangler kv key get --binding=MY_NAMESPACE \"my-key\"\n\n# Read to file\nnpx wrangler kv key get --binding=MY_NAMESPACE \"image\" --path=image.png\n```\n\n### List Keys\n\n```bash\n# List all keys\nnpx wrangler kv key list --binding=MY_NAMESPACE\n\n# List with prefix\nnpx wrangler kv key list --binding=MY_NAMESPACE --prefix=\"user:\"\n\n# Pretty print\nnpx wrangler kv key list --binding=MY_NAMESPACE | jq \".\"\n```\n\n### Delete Keys\n\n```bash\n# Delete single key\nnpx wrangler kv key delete --binding=MY_NAMESPACE \"my-key\"\n```\n\n### Bulk Operations\n\n```bash\n# Bulk write (up to 10,000 keys)\nnpx wrangler kv bulk put --binding=MY_NAMESPACE data.json\n\n# data.json format:\n# [\n#   {\"key\": \"key1\", \"value\": \"value1\"},\n#   {\"key\": \"key2\", \"value\": \"value2\", \"expiration_ttl\": 3600}\n# ]\n\n# Bulk delete (up to 10,000 keys)\nnpx wrangler kv bulk delete --binding=MY_NAMESPACE keys.json\n\n# keys.json format:\n# [\"key1\", \"key2\", \"key3\"]\n```\n\n---\n\n## Limits & Quotas\n\n| Feature | Free Plan | Paid Plan |\n|---------|-----------|-----------|\n| **Reads per day** | 100,000 | Unlimited |\n| **Writes per day** (different keys) | 1,000 | Unlimited |\n| **Writes per key per second** | 1 | 1 |\n| **Operations per Worker invocation** | 1,000 | 1,000 |\n| **Namespaces per account** | 1,000 | 1,000 |\n| **Storage per account** | 1 GB | Unlimited |\n| **Storage per namespace** | 1 GB | Unlimited |\n| **Keys per namespace** | Unlimited | Unlimited |\n| **Key size** | 512 bytes | 512 bytes |\n| **Metadata size** | 1024 bytes | 1024 bytes |\n| **Value size** | 25 MiB | 25 MiB |\n| **Minimum cacheTtl** | 60 seconds | 60 seconds |\n| **Maximum cacheTtl** | Number.MAX_SAFE_INTEGER | Number.MAX_SAFE_INTEGER |\n\n**Important Notes:**\n- **1 write\u002Fsecond per key**: Concurrent writes to the same key cause 429 errors\n- **1000 operations per invocation**: Bulk operations count as **1 operation**\n- **Bulk reads** (reading multiple keys) count as a single operation\n- **REST API** is subject to [Cloudflare API rate limits](https:\u002F\u002Fdevelopers.cloudflare.com\u002Ffundamentals\u002Fapi\u002Freference\u002Flimits\u002F)\n\n---\n\n## TypeScript Types\n\n```typescript\n\u002F\u002F KVNamespace type is provided by @cloudflare\u002Fworkers-types\ninterface KVNamespace {\n  get(key: string, options?: Partial\u003CKVGetOptions\u003Cundefined>>): Promise\u003Cstring | null>;\n  get(key: string, type: \"text\"): Promise\u003Cstring | null>;\n  get\u003CExpectedValue = unknown>(key: string, type: \"json\"): Promise\u003CExpectedValue | null>;\n  get(key: string, type: \"arrayBuffer\"): Promise\u003CArrayBuffer | null>;\n  get(key: string, type: \"stream\"): Promise\u003CReadableStream | null>;\n  get(key: string, options?: KVGetOptions\u003C\"text\">): Promise\u003Cstring | null>;\n  get\u003CExpectedValue = unknown>(key: string, options?: KVGetOptions\u003C\"json\">): Promise\u003CExpectedValue | null>;\n  get(key: string, options?: KVGetOptions\u003C\"arrayBuffer\">): Promise\u003CArrayBuffer | null>;\n  get(key: string, options?: KVGetOptions\u003C\"stream\">): Promise\u003CReadableStream | null>;\n  get(keys: string[]): Promise\u003CMap\u003Cstring, string | null>>;\n  get(keys: string[], type: \"text\"): Promise\u003CMap\u003Cstring, string | null>>;\n  get\u003CExpectedValue = unknown>(keys: string[], type: \"json\"): Promise\u003CMap\u003Cstring, ExpectedValue | null>>;\n\n  getWithMetadata\u003CMetadata = unknown>(key: string, options?: Partial\u003CKVGetOptions\u003Cundefined>>): Promise\u003CKVGetWithMetadataResult\u003Cstring, Metadata>>;\n  getWithMetadata\u003CMetadata = unknown>(key: string, type: \"text\"): Promise\u003CKVGetWithMetadataResult\u003Cstring, Metadata>>;\n  getWithMetadata\u003CExpectedValue = unknown, Metadata = unknown>(key: string, type: \"json\"): Promise\u003CKVGetWithMetadataResult\u003CExpectedValue, Metadata>>;\n  getWithMetadata\u003CMetadata = unknown>(key: string, options?: KVGetOptions\u003C\"text\">): Promise\u003CKVGetWithMetadataResult\u003Cstring, Metadata>>;\n  getWithMetadata\u003CExpectedValue = unknown, Metadata = unknown>(key: string, options?: KVGetOptions\u003C\"json\">): Promise\u003CKVGetWithMetadataResult\u003CExpectedValue, Metadata>>;\n  getWithMetadata\u003CMetadata = unknown>(keys: string[]): Promise\u003CMap\u003Cstring, KVGetWithMetadataResult\u003Cstring, Metadata>>>;\n  getWithMetadata\u003CMetadata = unknown>(keys: string[], type: \"text\"): Promise\u003CMap\u003Cstring, KVGetWithMetadataResult\u003Cstring, Metadata>>>;\n  getWithMetadata\u003CExpectedValue = unknown, Metadata = unknown>(keys: string[], type: \"json\"): Promise\u003CMap\u003Cstring, KVGetWithMetadataResult\u003CExpectedValue, Metadata>>>;\n\n  put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVPutOptions): Promise\u003Cvoid>;\n\n  delete(key: string): Promise\u003Cvoid>;\n\n  list\u003CMetadata = unknown>(options?: KVListOptions): Promise\u003CKVListResult\u003CMetadata>>;\n}\n\ninterface KVGetOptions\u003CType> {\n  type: Type;\n  cacheTtl?: number;\n}\n\ninterface KVGetWithMetadataResult\u003CValue, Metadata> {\n  value: Value | null;\n  metadata: Metadata | null;\n}\n\ninterface KVPutOptions {\n  expiration?: number;        \u002F\u002F Seconds since epoch\n  expirationTtl?: number;     \u002F\u002F Seconds from now (minimum 60)\n  metadata?: any;             \u002F\u002F Serializable to JSON, max 1024 bytes\n}\n\ninterface KVListOptions {\n  prefix?: string;\n  limit?: number;   \u002F\u002F Default 1000, max 1000\n  cursor?: string;\n}\n\ninterface KVListResult\u003CMetadata = unknown> {\n  keys: {\n    name: string;\n    expiration?: number;\n    metadata?: Metadata;\n  }[];\n  list_complete: boolean;\n  cursor?: string;\n}\n```\n\n---\n\n## Error Handling\n\n### Common Errors\n\n#### 1. Rate Limit (429 Too Many Requests)\n\n```typescript\ntry {\n  await env.MY_KV.put('counter', '1');\n  await env.MY_KV.put('counter', '2'); \u002F\u002F Too fast! \u003C 1 second\n} catch (error) {\n  \u002F\u002F Error: KV PUT failed: 429 Too Many Requests\n  console.error(error);\n}\n\n\u002F\u002F Solution: Use retry with backoff (see putWithRetry example above)\n```\n\n#### 2. Value Too Large\n\n```typescript\nconst largeValue = 'x'.repeat(26 * 1024 * 1024); \u002F\u002F > 25 MiB\n\ntry {\n  await env.MY_KV.put('large', largeValue);\n} catch (error) {\n  \u002F\u002F Error: Value too large\n  console.error(error);\n}\n\n\u002F\u002F Solution: Check size before writing\nif (value.length > 25 * 1024 * 1024) {\n  throw new Error('Value exceeds 25 MiB limit');\n}\n```\n\n#### 3. Metadata Too Large\n\n```typescript\nconst metadata = { data: 'x'.repeat(2000) }; \u002F\u002F > 1024 bytes serialized\n\ntry {\n  await env.MY_KV.put('key', 'value', { metadata });\n} catch (error) {\n  \u002F\u002F Error: Metadata too large\n  console.error(error);\n}\n\n\u002F\u002F Solution: Validate metadata size\nconst serialized = JSON.stringify(metadata);\nif (serialized.length > 1024) {\n  throw new Error('Metadata exceeds 1024 byte limit');\n}\n```\n\n#### 4. Invalid CacheTtl\n\n```typescript\n\u002F\u002F ❌ Too low\nawait env.MY_KV.get('key', { cacheTtl: 30 }); \u002F\u002F Error: minimum is 60\n\n\u002F\u002F ✅ Correct\nawait env.MY_KV.get('key', { cacheTtl: 60 });\n```\n\n---\n\n## Always Do ✅\n\n1. **Use bulk operations** when reading multiple keys (counts as 1 operation)\n2. **Set cacheTtl** for frequently-read, infrequently-updated data\n3. **Store small values in metadata** when using `list()` frequently\n4. **Check `list_complete`** when paginating, not `keys.length === 0`\n5. **Use retry logic with exponential backoff** for write operations\n6. **Validate sizes** before writing (key 512 bytes, value 25 MiB, metadata 1 KB)\n7. **Use preview namespaces** for local development\n8. **Set appropriate TTLs** for cache invalidation (minimum 60 seconds)\n9. **Coalesce related keys** for better caching performance\n10. **Use KV for read-heavy workloads** (100:1 read\u002Fwrite ratio ideal)\n\n---\n\n## Never Do ❌\n\n1. **Never write to same key >1\u002Fsecond** - Causes 429 rate limit errors\n2. **Never assume immediate global consistency** - Takes ~60 seconds to propagate\n3. **Never use KV for atomic operations** - Use Durable Objects instead\n4. **Never set cacheTtl \u003C60 seconds** - Will fail\n5. **Never commit namespace IDs to public repos** - Use environment variables\n6. **Never exceed 1000 operations per invocation** - Use bulk operations\n7. **Never rely on write order** - Eventual consistency means no guarantees\n8. **Never store sensitive data without encryption** - KV is not encrypted at rest by default\n9. **Never use KV for high-frequency writes** - Not designed for write-heavy workloads\n10. **Never forget to handle null values** - `get()` returns `null` if key doesn't exist\n\n---\n\n## Troubleshooting\n\n### Issue: \"429 Too Many Requests\" on writes\n\n**Cause:** Writing to same key more than once per second\n\n**Solution:**\n```typescript\n\u002F\u002F ❌ Bad\nfor (let i = 0; i \u003C 10; i++) {\n  await kv.put('counter', String(i)); \u002F\u002F Rate limit!\n}\n\n\u002F\u002F ✅ Good - consolidate writes\nconst finalValue = '9';\nawait kv.put('counter', finalValue);\n\n\u002F\u002F ✅ Good - use retry with backoff\nawait putWithRetry(kv, 'counter', String(i));\n```\n\n---\n\n### Issue: Stale reads after write\n\n**Cause:** Eventual consistency - writes take up to 60 seconds to propagate globally\n\n**Solution:**\n```typescript\n\u002F\u002F Accept that reads may be stale for up to 60 seconds\n\u002F\u002F OR use Durable Objects for strong consistency\n\u002F\u002F OR implement application-level cache invalidation\n```\n\n---\n\n### Issue: \"Operations limit exceeded\"\n\n**Cause:** More than 1000 KV operations in single Worker invocation\n\n**Solution:**\n```typescript\n\u002F\u002F ❌ Bad - 5000 operations\nconst keys = Array.from({ length: 5000 }, (_, i) => `key${i}`);\nfor (const key of keys) {\n  await kv.get(key); \u002F\u002F Exceeds 1000 limit\n}\n\n\u002F\u002F ✅ Good - 1 operation (bulk read)\nconst values = await kv.get(keys);\n```\n\n---\n\n### Issue: List returns empty but cursor exists\n\n**Cause:** Recently deleted\u002Fexpired keys create \"tombstones\" in the list\n\n**Solution:**\n```typescript\n\u002F\u002F Always check list_complete, not keys.length\nlet cursor: string | undefined;\n\ndo {\n  const result = await kv.list({ cursor });\n\n  \u002F\u002F Process keys even if empty\n  processKeys(result.keys);\n\n  \u002F\u002F CORRECT: Check list_complete\n  cursor = result.list_complete ? undefined : result.cursor;\n} while (cursor);\n```\n\n---\n\n## Production Checklist\n\nBefore deploying to production:\n\n- [ ] Environment-specific namespaces configured (`id` vs `preview_id`)\n- [ ] Namespace IDs stored in environment variables (not hardcoded)\n- [ ] Rate limit retry logic implemented for writes\n- [ ] Appropriate `cacheTtl` values set for reads\n- [ ] Metadata sizes validated (\u003C1024 bytes)\n- [ ] Value sizes validated (\u003C25 MiB)\n- [ ] Key sizes validated (\u003C512 bytes)\n- [ ] Bulk operations used where possible\n- [ ] Pagination implemented correctly for `list()`\n- [ ] Error handling for null values\n- [ ] Monitoring\u002Falerting for rate limits\n- [ ] Documentation for eventual consistency behavior\n\n---\n\n## Related Documentation\n\n- [Cloudflare KV Docs](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002F)\n- [KV API Reference](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002Fapi\u002F)\n- [KV Limits](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002Fplatform\u002Flimits\u002F)\n- [How KV Works](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fkv\u002Fconcepts\u002Fhow-kv-works\u002F)\n- [Wrangler KV Commands](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkers\u002Fwrangler\u002Fcommands\u002F#kv)\n\n---\n\n**Last Updated**: 2025-10-21\n**Version**: 1.0.0\n**Maintainer**: Jeremy Dawes | jeremy@jezweb.net\n",{"name":5,"license":14,"description":23},"Complete knowledge domain for Cloudflare Workers KV - global, low-latency key-value storage on Cloudflare's edge network.\n\nUse when: creating KV namespaces, storing configuration data, caching API responses, managing user preferences,\nimplementing TTL expiration, handling KV metadata, or encountering \"KV_ERROR\", \"429 too many requests\",\n\"kv rate limit\", cacheTtl errors, or eventual consistency issues.\n\nKeywords: kv storage, cloudflare kv, workers kv, kv namespace, kv bindings, kv cache, kv ttl, kv metadata,\nkv list, kv pagination, cache optimization, edge caching, KV_ERROR, 429 too many requests, kv rate limit,\neventually consistent, wrangler kv, kv operations, key value storage\n","main","6b73b29e4866f997b1eb47fe8d9631396265fc24",0,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn","2026-09-09 16:06:07",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-kv",{"tool":36,"command":37},"bunx","bunx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-kv",{"tool":39,"command":40},"pnpm","pnpm dlx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-kv","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-kv\u002FSKILL.md",true,[44,50,54],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"README.md","REFERENCE","参考文档",5815,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-kv\u002FREADME.md",{"path":51,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":52,"sourceHtmlUrl":53},"SKILL.json",29186,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-kv\u002FSKILL.json",{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"SKILL.md.backup","OTHER","其他",27665,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-kv\u002FSKILL.md.backup",[61,68,76,83,90,99],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7AQNJDXVNVMN08N5BHBGZBF","zustand-state-management","Production-tested setup for Zustand state management in React applications with TypeScript.\nThis skill provides comprehensive patterns for building scalable, type-safe global state.\n\nUse when: setting up global state in React, migrating from Redux or Context API, implementing\nstate persistence with localStorage, configuring TypeScript with Zustand, using slices pattern\nfor modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration,\nor encountering hydration errors, TypeScript inference issues, or persist middleware problems.\n\nPrevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses\nsyntax errors, persist middleware export errors, infinite render loops, and slices pattern\ntype inference failures.\n\nKeywords: zustand, state management, React state, TypeScript state, persist middleware,\ndevtools, slices pattern, global state, React hooks, create store, useBoundStore,\nStateCreator, hydration error, text content mismatch, infinite render, localStorage,\nsessionStorage, immer middleware, shallow equality, selector pattern, zustand v5","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":72,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M7AQN2DW9DTPM8BYNZSHQANC","zetic-mlange","Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin\u002FJava) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android\u002FiOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch\u002FONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M7AQMEK370FBPC75N2W8WA4W","youtube-downloader","Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3\u002FM4A\u002FFLAC, downloading entire playlists\u002Fchannels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M7AQHKQ4VQB04NH6BG4SV9Q7","wordpress-plugin-core","This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks\u002Ffilters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types\u002Ftaxonomies, building admin interfaces, or working with the WordPress database.\n\nUse when: Creating new WordPress plugins, implementing nonces\u002Fsanitization\u002Fescaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation\u002Fdeactivation issues, preventing SQL injection\u002FXSS\u002FCSRF vulnerabilities.\n\nKeywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":18},"01M7AQH4JW8F2MJFS1C43TZ2TY","webapp-testing","Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":18},"01M7AQH0PWD6Z1NN66V15DT25M","web-performance-audit","Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fweb-performance-audit\u002FSKILL.md",[],[]]