Cloudflare D1 is a serverless SQLite database replicated globally across Cloudflare’s edge network. UUID v7 generated in Cloudflare Workers fits D1’s append-heavy workload: the timestamp prefix keeps rows chronologically ordered in the B-tree without manual timestamp management. See UUID v7 in Serverless for the broader edge context.

D1 table schema

-- D1 uses SQLite — TEXT column for UUID v7 (36-char canonical format)
CREATE TABLE messages (
    id         TEXT    NOT NULL PRIMARY KEY,
    channel_id TEXT    NOT NULL,
    content    TEXT    NOT NULL,
    user_id    TEXT    NOT NULL
);

-- Index for cursor pagination (optional — PRIMARY KEY index covers id)
CREATE INDEX messages_channel ON messages (channel_id, id);

Worker bindings (wrangler.toml)

name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-09-23"

[[d1_databases]]
binding = "DB"
database_name = "messages-db"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

Worker with UUID v7 insert

// src/index.ts
import { v7 as uuidv7 } from 'uuid';

interface Env {
  DB: D1Database;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (request.method === 'POST' && url.pathname === '/messages') {
      const { channelId, content, userId } = await request.json<{
        channelId: string;
        content: string;
        userId: string;
      }>();

      const id = uuidv7(); // UUID v7 — encodes message creation time

      await env.DB.prepare(
        'INSERT INTO messages (id, channel_id, content, user_id) VALUES (?, ?, ?, ?)'
      )
        .bind(id, channelId, content, userId)
        .run();

      return Response.json({ id }, { status: 201 });
    }

    return new Response('Not found', { status: 404 });
  },
};

Cursor pagination in D1

interface ListResult {
  data: { id: string; content: string; user_id: string }[];
  nextCursor: string | null;
}

async function listMessages(
  db: D1Database,
  channelId: string,
  cursor?: string,
  limit = 20,
): Promise<ListResult> {
  const query = cursor
    ? 'SELECT id, content, user_id FROM messages WHERE channel_id = ? AND id > ? ORDER BY id LIMIT ?'
    : 'SELECT id, content, user_id FROM messages WHERE channel_id = ? ORDER BY id LIMIT ?';
  const args = cursor ? [channelId, cursor, limit + 1] : [channelId, limit + 1];

  const { results } = await db.prepare(query).bind(...args).all();
  const hasMore = results.length > limit;
  const data = hasMore ? results.slice(0, limit) : results;
  const nextCursor = hasMore ? (data.at(-1) as { id: string }).id : null;

  return { data: data as ListResult['data'], nextCursor };
}

Drizzle ORM with D1

// schema.ts
import { sqliteTable, text } from 'drizzle-orm/sqlite-core';

export const messages = sqliteTable('messages', {
  id:        text('id').primaryKey(),     // UUID v7 as TEXT
  channelId: text('channel_id').notNull(),
  content:   text('content').notNull(),
  userId:    text('user_id').notNull(),
});

// db.ts
import { drizzle } from 'drizzle-orm/d1';

export function createDb(d1: D1Database) {
  return drizzle(d1);
}

// Worker handler using Drizzle
import { gt, eq, asc, and } from 'drizzle-orm';
import { v7 as uuidv7 } from 'uuid';
import { messages } from './schema';

async function insertMessage(db: ReturnType<typeof createDb>, data: {
  channelId: string; content: string; userId: string;
}) {
  const id = uuidv7();
  await db.insert(messages).values({ id, ...data });
  return id;
}

async function paginateMessages(
  db: ReturnType<typeof createDb>,
  channelId: string,
  cursor?: string,
  limit = 20,
) {
  const condition = cursor
    ? and(eq(messages.channelId, channelId), gt(messages.id, cursor))
    : eq(messages.channelId, channelId);

  const rows = await db.select().from(messages)
    .where(condition)
    .orderBy(asc(messages.id))
    .limit(limit + 1);

  const hasMore = rows.length > limit;
  const data = hasMore ? rows.slice(0, limit) : rows;
  return { data, nextCursor: hasMore ? data.at(-1)!.id : null };
}

Extract creation time from UUID v7 in a Worker

function extractTimestamp(uuidV7: string): Date {
  const hex = uuidV7.replace(/-/g, '').slice(0, 12);
  return new Date(parseInt(hex, 16));
}

// Example: check message age
const msgId = '018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f';
const createdAt = extractTimestamp(msgId);
const ageMs = Date.now() - createdAt.getTime();
console.log(`Message age: ${Math.round(ageMs / 1000)}s`);

Further reading

External references

Frequently asked questions

Does Cloudflare D1 support UUID v7 natively?

D1 uses SQLite, which has no built-in UUID function. UUID v7 values are stored as TEXT in the canonical 36-character hyphenated format. Generate them in the Worker using the uuid npm package: import { v7 as uuidv7 } from 'uuid'. Since UUID v7 is lexicographically ordered, ORDER BY id on a TEXT column is chronological. See UUID in Databases for SQLite storage details.

How do I use UUID v7 with Drizzle ORM and Cloudflare D1?

Use text('id').primaryKey() in Drizzle's SQLite schema (D1 is SQLite-compatible). Generate UUID v7 on the Worker side with the uuid npm package before inserting. Drizzle's D1 adapter accepts the same Drizzle schema and query builder as other SQLite targets. See UUID v7 in Drizzle + PostgreSQL for the PostgreSQL variant.

How does UUID v7 help with cursor pagination in Cloudflare D1?

D1's read replicas serve requests from the nearest edge location. Cursor pagination using UUID v7 is consistent across replicas because the sort key is the UUID itself — no timestamp tie-breaking needed. Query WHERE id > cursor ORDER BY id LIMIT n. UUID v7 string comparison is lexicographic, which equals chronological for v7 UUIDs. See UUID v7 for Cursor Pagination.