Deno KV is a key-value database built directly into the Deno runtime. Zero setup, zero dependencies — just import and use. On Deno Deploy, it replicates globally.
Basic Usage
const kv = await Deno.openKv();
// Set a value
await kv.set(['users', 'alice'], { name: 'Alice', email: 'alice@example.com' });
// Get a value
const result = await kv.get(['users', 'alice']);
console.log(result.value); // { name: 'Alice', email: 'alice@example.com' }
// Delete
await kv.delete(['users', 'alice']);
Hierarchical Keys
// Users by ID
await kv.set(['users', userId], userData);
// Posts by user
await kv.set(['posts_by_user', userId, postId], postData);
// List all posts by user
const posts = kv.list({ prefix: ['posts_by_user', userId] });
for await (const entry of posts) {
console.log(entry.key, entry.value);
}
Atomic Transactions
// Transfer money atomically
const sender = await kv.get(['accounts', senderId]);
const receiver = await kv.get(['accounts', receiverId]);
const result = await kv.atomic()
.check(sender) // Ensure no concurrent modifications
.check(receiver)
.set(['accounts', senderId], { ...sender.value, balance: sender.value.balance - amount })
.set(['accounts', receiverId], { ...receiver.value, balance: receiver.value.balance + amount })
.commit();
if (!result.ok) console.log('Transaction failed — retry');
Queue (Built-in Job Queue)
// Enqueue a job
await kv.enqueue({ type: 'send-email', to: 'user@example.com', subject: 'Hello' });
// Process jobs
kv.listenQueue(async (msg) => {
if (msg.type === 'send-email') {
await sendEmail(msg.to, msg.subject);
}
});
Watch for Changes
const stream = kv.watch([['config', 'feature-flags']]);
for await (const entries of stream) {
console.log('Config changed:', entries[0].value);
}
Why This Matters
- Zero setup: Built into Deno, no install needed
- Global replication: On Deno Deploy, data in every region
- ACID transactions: Atomic operations with optimistic concurrency
- Built-in queue: Job processing without Redis or SQS
- Free tier: 1GB storage on Deno Deploy
Need custom database tools or serverless backends? I build developer tools. Check out my web scraping actors on Apify or reach out at spinov001@gmail.com for custom solutions.
Top comments (0)