intermediate
KV
Store globally replicated key-value data for configuration, flags, and cache-like reads with eventual consistency constraints.
KV is a globally replicated key-value store optimized for high-read, low-write configuration, feature flags, JWT blocklists, and cache-like lookups from Workers. Values are eventually consistent — writes propagate globally with delay; do not use KV as a strongly consistent database.
const theme = (await env.FLAGS.get(`user:${userId}:theme`)) ?? 'light';
await env.FLAGS.put('maintenance', 'true', { expirationTtl: 3600 });
| Pattern | Fit | |---------|-----| | Config blob | JSON settings read on every request | | Negative cache | Store 404 markers to protect origin | | Session hint | Non-authoritative prefs only | | Counter | Poor fit — use Durable Objects instead |
List operations are slow and paginated; design keys with predictable prefixes. TTL and expiration purge keys automatically.
On interviews: eventual consistency implications, KV vs Redis vs D1, key naming, write rate limits, and cache stampede mitigation.
Common pitfalls: storing authoritative balances or inventory; expecting immediate read-your-writes globally; huge values; frequent writes to the same hot key.
The trade-off is cheap global reads and simplicity versus weak consistency and unsuitability for transactional state.
Checklist:
- Use KV for read-heavy, tolerate-stale data.
- Namespace keys by tenant and feature.
- Set TTL on ephemeral flags and caches.
- Move counters and locks to Durable Objects.