AWS Lambda functions are stateless and ephemeral — they generate IDs at the application layer rather than relying on database sequences. The Node.js Lambda runtime ships crypto.randomUUID() from Node 18, covering UUID v4 with no dependencies. For UUID v7, the uuid npm package adds under 5 KB to the bundle and has no native dependencies, making it safe in Lambda without any build configuration. See UUID in JavaScript for the full runtime context.

Basic Lambda handler with UUID v7

// handler.ts
import { APIGatewayProxyHandlerV2 } from 'aws-lambda';
import { v7 as uuidv7 } from 'uuid';
import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb';

const ddb = new DynamoDBClient({});

export const handler: APIGatewayProxyHandlerV2 = async (event) => {
  const orderId = uuidv7();  // time-sortable primary key

  await ddb.send(new PutItemCommand({
    TableName: 'orders',
    Item: {
      PK:        { S: `ORDER#${orderId}` },
      SK:        { S: 'METADATA' },
      orderId:   { S: orderId },
      createdAt: { N: String(Date.now()) },
    },
  }));

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

UUID v7’s timestamp prefix means ORDER# entries naturally sort by creation time within DynamoDB’s key space — enabling efficient begins_with and between range queries without a Global Secondary Index.

Idempotent Lambda with UUID as request key

import { v5 as uuidv5 } from 'uuid';

const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // URL namespace

export const handler: APIGatewayProxyHandlerV2 = async (event) => {
  // Derive a deterministic ID from the request — same input = same ID
  const requestBody = event.body ?? '';
  const idempotencyKey = uuidv5(requestBody, NAMESPACE);

  // Use as DynamoDB condition to prevent duplicate inserts
  // ConditionExpression: 'attribute_not_exists(PK)'
  // ...
};

UUID v5 (SHA-1 name-based) produces a deterministic UUID from a request body — the same payload always yields the same key, making it a reliable idempotency mechanism. See UUID as Idempotency Keys and UUID Namespace.

Cold start impact

The uuid package is pure JavaScript with no native add-ons — it adds no compilation step and loads in under 1ms. For Lambda functions where cold-start latency matters, crypto.randomUUID() (built-in, zero import cost) is the fastest option for UUID v4. UUID v7 requires the package because Node.js does not expose a v7 API natively (Python 3.13 and .NET 9 do — see Python 3.13 uuid.uuid7()).

// Lowest cold-start overhead — UUID v4 only
const id = crypto.randomUUID();

// UUID v7 — ~0.5ms extra import time, negligible for most functions
import { v7 as uuidv7 } from 'uuid';
const id = uuidv7();

RDS Proxy and Aurora — UUID v7 primary keys

For Lambda functions backed by Amazon RDS or Aurora, UUID v7 eliminates the B-tree page fragmentation that UUID v4 causes:

// aurora-handler.ts
import { RDSDataClient, ExecuteStatementCommand } from '@aws-sdk/client-rds-data';
import { v7 as uuidv7 } from 'uuid';

const rds = new RDSDataClient({});

async function createOrder(customerId: string) {
  const id = uuidv7();
  await rds.send(new ExecuteStatementCommand({
    resourceArn: process.env.CLUSTER_ARN!,
    secretArn:   process.env.SECRET_ARN!,
    database:    'app',
    sql:         'INSERT INTO orders (id, customer_id) VALUES (:id, :cid)',
    parameters:  [
      { name: 'id',  value: { stringValue: id } },
      { name: 'cid', value: { stringValue: customerId } },
    ],
  }));
  return id;
}

See UUID in Databases for the full B-tree index fragmentation analysis comparing UUID v4 and v7.

Further reading

External references

Frequently asked questions

Does crypto.randomUUID() work in AWS Lambda?

Yes. crypto.randomUUID() is available in all Lambda Node.js runtimes from Node 18 onwards (the current minimum recommended runtime). It uses the underlying OS CSPRNG — the same source used by crypto.getRandomValues() in browsers. No polyfill or extra package is needed for UUID v4. See crypto.randomUUID() runtime support.

What UUID version should I use for DynamoDB primary keys?

UUID v7 is preferred for DynamoDB because its timestamp-prefixed key distribution avoids the "hot partition" problem that plagues purely random UUID v4 keys. With UUID v4, many writes land on the same hash partition shard in quick succession because consecutive keys are clustered; UUID v7's sequential prefix spreads writes across time windows. For DynamoDB's sort key pattern, UUID v7 also enables efficient time-range scans without a secondary index. See UUID in Databases.