Deno KV is a built-in ACID key-value store in Deno, backed by FoundationDB on Deno Deploy. Its keys are stored in lexicographic order — making UUID v7 an ideal key type because UUID v7’s timestamp prefix ensures lexicographic order equals chronological order. See UUID v7 in Deno for the broader Deno context.
Setup
// No external dependencies — uuid is available via npm specifier in Deno
import { v7 as uuidv7 } from 'npm:uuid';
const kv = await Deno.openKv();
Basic CRUD with UUID v7 keys
import { v7 as uuidv7 } from 'npm:uuid';
const kv = await Deno.openKv();
interface Order {
id: string;
customerId: string;
total: number;
status: string;
}
// Create — UUID v7 as key
async function createOrder(customerId: string, total: number): Promise<Order> {
const id = uuidv7();
const order: Order = { id, customerId, total, status: 'pending' };
const result = await kv.atomic()
.check({ key: ['orders', id], versionstamp: null }) // Ensure key doesn't exist
.set(['orders', id], order)
.commit();
if (!result.ok) throw new Error('Order creation failed — key collision');
return order;
}
// Read
async function getOrder(id: string): Promise<Order | null> {
const entry = await kv.get<Order>(['orders', id]);
return entry.value;
}
// Update
async function updateOrderStatus(id: string, status: string): Promise<void> {
const entry = await kv.get<Order>(['orders', id]);
if (!entry.value) throw new Error('Order not found');
await kv.atomic()
.check(entry) // Optimistic concurrency — fails if updated since read
.set(['orders', id], { ...entry.value, status })
.commit();
}
Chronological range queries
// List all orders — UUID v7 lexicographic = chronological order
async function listAllOrders(): Promise<Order[]> {
const orders: Order[] = [];
const iter = kv.list<Order>({ prefix: ['orders'] });
for await (const entry of iter) {
orders.push(entry.value);
}
return orders;
}
// Time-range query using UUID v7 prefix
function uuidV7AtTime(ms: number): string {
// Build a UUID v7 prefix for a specific millisecond
const hexMs = ms.toString(16).padStart(12, '0');
return `${hexMs.slice(0, 8)}-${hexMs.slice(8, 12)}-7000-8000-000000000000`;
}
async function getOrdersInWindow(startMs: number, endMs: number): Promise<Order[]> {
const orders: Order[] = [];
const iter = kv.list<Order>({
start: ['orders', uuidV7AtTime(startMs)],
end: ['orders', uuidV7AtTime(endMs)],
});
for await (const entry of iter) {
orders.push(entry.value);
}
return orders;
}
// Example: orders from the last hour
const oneHourAgo = Date.now() - 3600_000;
const recentOrders = await getOrdersInWindow(oneHourAgo, Date.now());
Cursor pagination
interface PageResult {
orders: Order[];
nextCursor: string | null;
}
async function listOrdersPage(cursor?: string, limit = 20): Promise<PageResult> {
const selector = cursor
? { start: ['orders', cursor], end: ['orders', '\uffff'] } // After cursor
: { prefix: ['orders'] };
const orders: Order[] = [];
const iter = kv.list<Order>(selector, { limit });
for await (const entry of iter) {
// Skip the cursor entry itself
if (entry.value.id === cursor) continue;
orders.push(entry.value);
if (orders.length === limit) break;
}
const nextCursor = orders.length === limit ? orders[orders.length - 1].id : null;
return { orders, nextCursor };
}
See UUID v7 for Cursor Pagination.
Composite keys: per-user order history
// Composite key: ['orders', userId, orderId]
// Enables per-user scans in chronological order
async function createUserOrder(userId: string, total: number): Promise<Order> {
const orderId = uuidv7();
const order: Order = { id: orderId, customerId: userId, total, status: 'pending' };
await kv.atomic()
.set(['orders', userId, orderId], order) // Per-user namespace
.set(['orders_global', orderId], order) // Global index
.commit();
return order;
}
// List orders for a specific user — chronological via UUID v7
async function getUserOrders(userId: string): Promise<Order[]> {
const orders: Order[] = [];
const iter = kv.list<Order>({ prefix: ['orders', userId] });
for await (const entry of iter) {
orders.push(entry.value);
}
return orders;
}
Deno Deploy HTTP handler
import { v7 as uuidv7 } from 'npm:uuid';
const kv = await Deno.openKv();
Deno.serve(async (req) => {
const url = new URL(req.url);
const traceId = uuidv7(); // UUID v7 trace ID for every request
if (req.method === 'POST' && url.pathname === '/orders') {
const body = await req.json<{ customerId: string; total: number }>();
const id = uuidv7();
const order = { id, customerId: body.customerId, total: body.total, status: 'pending' };
await kv.set(['orders', id], order);
return Response.json(order, {
status: 201,
headers: { 'X-Trace-ID': traceId },
});
}
if (req.method === 'GET' && url.pathname === '/orders') {
const cursor = url.searchParams.get('cursor') ?? undefined;
const { orders, nextCursor } = await listOrdersPage(cursor);
return Response.json({ orders, nextCursor }, {
headers: { 'X-Trace-ID': traceId },
});
}
return new Response('Not found', { status: 404 });
});
See UUID in Edge Functions for the broader edge runtime context.
Further reading
- UUID v7 in Deno — Standard Library and Fresh
- UUID in Edge Functions
- UUID v7 for Cursor Pagination
- UUID v7 in Hono — Edge-First APIs
- Lexicographical Order — UUID v7 sort properties
External references
Frequently asked questions
Why is UUID v7 a good choice for Deno KV keys?
Deno KV stores keys in lexicographic order. UUID v7 strings sort lexicographically in the same order as their creation timestamps — so a Deno KV range scan with { start: olderUuid, end: newerUuid } retrieves records created within that time window. UUID v4 keys produce random scan results; UUID v7 keys produce chronological results. See UUID v7 in Deno.
How do I use UUID v7 in a Deno KV composite key?
Deno KV supports composite keys as arrays: ["orders", userId, uuidv7()]. The UUID v7 at the end of the composite key sorts entries within a user's namespace chronologically. A list scan with kv.list({ prefix: ["orders", userId] }) returns all orders for that user in creation order. See UUID v7 in Deno.
Can I use UUID v7 with Deno KV atomic transactions?
Yes. Generate UUID v7 before the atomic transaction and use it as the key in the .set() call. The UUID v7 value is determined before the transaction, so it can be returned to the caller even if the transaction needs to be retried. Deno KV's optimistic concurrency control (check-and-set) works with UUID v7 keys identically to any other key type.