Analyze KV usage patterns and suggest optimizations - identifies missing TTLs, cacheTtl opportunities, bulk operations, and cost savings
Analyzes Worker code for KV usage patterns and provides optimization recommendations to improve performance and reduce costs.
/plugin marketplace add secondsky/claude-skills/plugin install cloudflare-kv@claude-skillscloudflare-kv/commands/This command analyzes Worker code for KV usage patterns and provides actionable optimization recommendations to improve performance and reduce costs.
Analyzes Code Patterns
Checks Best Practices
Generates Report
/cloudflare-kv:optimize src/index.ts
Run multiple times for different files:
/cloudflare-kv:optimize src/index.ts
/cloudflare-kv:optimize src/api/routes.ts
/cloudflare-kv:optimize src/lib/kv-utils.ts
If no file specified, command will:
/cloudflare-kv:optimize
Execute the analysis script from the cloudflare-kv skill:
${CLAUDE_PLUGIN_ROOT}/scripts/analyze-kv-usage.sh <worker-file>
The script performs static code analysis to detect:
Cloudflare Workers KV - Usage Analyzer
======================================
Analyzing: src/index.ts
KV Operations Found:
- get(): 15
- put(): 8
- delete(): 3
- list(): 2
Issue Check 1: Missing TTL on put() operations
----------------------------------------------
⚠ 5 put() operation(s) without TTL/expiration
Issue: Data will persist indefinitely, increasing storage costs
Fix: Add expirationTtl or expiration to put() calls
Example:
await env.KV.put('key', 'value', { expirationTtl: 3600 });
Issue Check 2: Missing cacheTtl on get() operations
---------------------------------------------------
⚠ 12 get() operation(s) without cacheTtl
Issue: Missing edge caching optimization
Fix: Add cacheTtl for frequently-read data (min 60 seconds)
Example:
const value = await env.KV.get('key', { cacheTtl: 300 });
Issue Check 3: Missing error handling
-------------------------------------
✗ No try-catch blocks found
Issue: KV operations can fail (rate limits, network errors)
Fix: Wrap KV operations in try-catch
Example:
try {
const value = await env.KV.get('key');
} catch (error) {
console.error('KV error:', error);
// Handle gracefully
}
Issue Check 4: Sequential get() calls (bulk read opportunity)
-------------------------------------------------------------
⚠ Multiple sequential await get() calls detected
Issue: Each get() counts as separate operation
Fix: Consider using Promise.all() for parallel reads
Example:
const [val1, val2, val3] = await Promise.all([
env.KV.get('key1'),
env.KV.get('key2'),
env.KV.get('key3')
]);
========================================
Summary
========================================
Critical Issues: 1
Warnings: 3
Optimizations: 2
⚠ Critical issues found
Please address critical issues before deploying to production.
For more details, see:
- references/best-practices.md
- references/performance-tuning.md
These can cause runtime errors or data loss:
❌ No error handling
These affect reliability and costs:
⚠️ Missing TTL on put()
⚠️ Missing pagination on list()
These improve performance:
💡 Missing cacheTtl on get()
💡 Sequential operations
💡 No waitUntil() usage
Based on the report:
Fix Immediately
Reference Documentation
references/best-practices.md for error handling patternsreferences/troubleshooting.md for error recoveryPrioritize Fixes
Estimate Impact
Implement Gradually
Benchmark
# Before optimization
wrangler dev
# Test response times
# After optimization
wrangler dev
# Compare response times
// ❌ Data persists forever
await env.KV.put('session', sessionData);
// ✅ Auto-expires after 1 hour
await env.KV.put('session', sessionData, {
expirationTtl: 3600
});
Impact: Prevents storage bloat, reduces costs
// ❌ Each await blocks execution
const user = await env.KV.get('user:123');
const prefs = await env.KV.get('prefs:123');
const stats = await env.KV.get('stats:123');
// ✅ All reads happen simultaneously
const [user, prefs, stats] = await Promise.all([
env.KV.get('user:123'),
env.KV.get('prefs:123'),
env.KV.get('stats:123')
]);
Impact: 3x faster execution
// ❌ Response waits for write
await env.KV.put('analytics', data);
return new Response('OK');
// ✅ Response returns immediately
ctx.waitUntil(
env.KV.put('analytics', data)
);
return new Response('OK');
Impact: 50-100ms faster responses
For complex codebases, consider using the kv-optimizer agent for automated refactoring:
@kv-optimizer Please optimize my KV usage in src/index.ts
The agent will:
/cloudflare-kv:test - Test KV operations after optimization/cloudflare-kv:setup - Configure new namespacesFor comprehensive optimization guidance:
references/best-practices.md for production patternsreferences/performance-tuning.md for advanced optimizations