Serverless functions are stateless, short-lived, and may run concurrently across many instances. UUID generation in serverless environments has two constraints: bundle size affects cold start time, and the system clock on a fresh Lambda invocation is always accurate (AWS, GCP, and Cloudflare synchronise clocks at the infrastructure level). UUID v7 works naturally in serverless — no coordination needed between concurrent invocations, and the embedded timestamp is reliable. This guide covers AWS Lambda, Cloudflare Workers, Vercel Edge Functions, and DynamoDB key design, using the uuid npm package and the uuid6 Python package.

AWS Lambda — Node.js

// handler.js
import { v7 as uuidv7 } from 'uuid';

export const handler = async (event) => {
  const requestId = uuidv7(); // Time-ordered request ID for CloudWatch logs

  console.log(JSON.stringify({
    requestId,
    event: event.httpMethod,
    path: event.path,
  }));

  const order = {
    id: uuidv7(),
    customerId: event.body.customerId,
    total: event.body.total,
    createdAt: new Date().toISOString(),
  };

  await dynamoDB.put({ TableName: 'Orders', Item: order }).promise();

  return {
    statusCode: 201,
    headers: { 'X-Request-Id': requestId },
    body: JSON.stringify(order),
  };
};

UUID v7 request IDs in CloudWatch logs are naturally time-sorted. Searching logs for a time window is as simple as filtering by the UUID v7 prefix for that timestamp range. The AWS Lambda Node.js handler documentation covers the event object structure.

AWS Lambda — Python 3.13

import uuid  # Python 3.13: uuid.uuid7() built-in

def handler(event, context):
    request_id = str(uuid.uuid7())  # UUID v7, no package needed in Python 3.13

    order = {
        'id': str(uuid.uuid7()),
        'customer_id': event['body']['customer_id'],
        'total': event['body']['total'],
    }

    table.put_item(Item=order)

    return {
        'statusCode': 201,
        'headers': {'X-Request-Id': request_id},
        'body': json.dumps(order),
    }

Python 3.13 adds uuid.uuid7() to the standard library — no uuid6 package required on the python3.13 Lambda runtime.

DynamoDB key design with UUID v7

A composite key pattern for time-series data:

// Partition by tenant, sort by event creation time
const params = {
  TableName: 'Events',
  Item: {
    tenantId: 'a8098c1a-f86e-4da4-bd1a-00112444be1e', // UUID v4 partition key
    eventId: uuidv7(),    // UUID v7 sort key — lexicographic = chronological
    eventType: 'ORDER_PLACED',
    payload: { ... },
  }
};

// Query all events for a tenant in the last hour
const sinceMs = Date.now() - 3_600_000;
const sinceUuid = `${sinceMs.toString(16).padStart(12,'0').slice(0,8)}-${sinceMs.toString(16).padStart(12,'0').slice(8,12)}-7000-8000-000000000000`;

const query = {
  TableName: 'Events',
  KeyConditionExpression: 'tenantId = :tid AND eventId >= :since',
  ExpressionAttributeValues: {
    ':tid': 'a8098c1a-f86e-4da4-bd1a-00112444be1e',
    ':since': sinceUuid,
  }
};

The DynamoDB Query documentation covers sort key range expressions. UUID v7 sort keys avoid a created_at secondary index for simple time-range queries.

Cloudflare Workers

// worker.js
import { v7 as uuidv7 } from 'uuid';

export default {
  async fetch(request, env) {
    const requestId = uuidv7();

    const { pathname } = new URL(request.url);

    if (request.method === 'POST' && pathname === '/orders') {
      const body = await request.json();
      const order = { id: uuidv7(), ...body };

      // Store in Cloudflare D1 (SQLite-compatible)
      await env.DB.prepare(
        'INSERT INTO orders (id, customer_id, total) VALUES (?, ?, ?)'
      ).bind(order.id, order.customerId, order.total).run();

      return Response.json(order, {
        status: 201,
        headers: { 'X-Request-Id': requestId }
      });
    }

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

Cloudflare D1 (SQLite) stores UUID strings as TEXT. UUID v7 strings sort correctly in SQLite ORDER BY id because SQLite text comparison is lexicographic. The Cloudflare D1 documentation covers schema management and binding configuration.

Idempotency keys with UUID v7

Serverless functions may be retried on failure. UUID v7 idempotency keys combine a unique request identity with a creation timestamp:

// API Gateway → Lambda with idempotency
export const handler = async (event) => {
  const idempotencyKey = event.headers['Idempotency-Key'];

  if (!idempotencyKey || !validate(idempotencyKey)) {
    return { statusCode: 400, body: 'Missing or invalid Idempotency-Key header' };
  }

  // Check if this key was already processed
  const cached = await dynamoDB.get({
    TableName: 'IdempotencyKeys',
    Key: { key: idempotencyKey }
  }).promise();

  if (cached.Item) {
    return { statusCode: 200, body: cached.Item.response }; // Return cached result
  }

  // Process and cache
  const result = await processOrder(event.body);
  await dynamoDB.put({
    TableName: 'IdempotencyKeys',
    Item: { key: idempotencyKey, response: JSON.stringify(result), ttl: ... },
  }).promise();

  return { statusCode: 201, body: JSON.stringify(result) };
};

UUID v7 idempotency keys are time-ordered, enabling TTL-based cleanup of the idempotency cache (delete keys older than 24 hours by comparing the UUID v7 timestamp prefix). The UUID Idempotency Keys page covers this pattern in full.

Vercel Edge Functions

// api/orders/route.ts (Next.js App Router edge runtime)
import { v7 as uuidv7 } from 'uuid';

export const runtime = 'edge';

export async function POST(request: Request) {
  const body = await request.json();
  const order = {
    id: uuidv7(),
    ...body,
    createdAt: new Date().toISOString(),
  };

  // Store via edge-compatible database (PlanetScale, Neon, Turso)
  const result = await db.execute({
    sql: 'INSERT INTO orders (id, customer_id, total) VALUES (?, ?, ?)',
    args: [order.id, order.customerId, order.total],
  });

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

The Vercel Edge Functions documentation covers the supported Web APIs and database connection patterns for edge-compatible databases.

Further reading

External references

Frequently asked questions

Does UUID v7 generation work in AWS Lambda without additional packages?

Node.js Lambda functions (runtime nodejs20.x and later) include crypto.randomUUID() for UUID v4 but not UUID v7. For UUID v7, include the uuid npm package in your Lambda deployment bundle — it adds ~5KB to the bundle size, negligible for cold start performance. Python Lambda functions (python3.13) have uuid.uuid7() in the standard library — no additional package needed. The AWS Lambda runtimes documentation covers available standard library versions per runtime.

How do I use UUID v7 as a DynamoDB partition key?

DynamoDB partition keys determine the physical shard that stores an item. UUID v7 distributes items across shards because the random bits (74 bits in rand_a + rand_b) provide sufficient entropy for even distribution despite the shared timestamp prefix. For time-series data, a composite key pattern works well: partition key = tenant ID (UUID v4), sort key = event ID (UUID v7). The sort key's lexicographic order matches creation time, enabling efficient range queries. The DynamoDB partition key best practices documentation covers even distribution strategies.

Does Cloudflare Workers support UUID v7 natively?

Cloudflare Workers expose the Web Crypto API including crypto.randomUUID() (UUID v4 only). For UUID v7, import the uuid npm package — Cloudflare's bundler (esbuild) tree-shakes it to ~2KB. UUID v7 generation uses Date.now() and crypto.getRandomValues(), both available in the Workers runtime. The Cloudflare Workers Web Crypto documentation lists all available crypto APIs.