Microservice architectures scatter a single user request across dozens of services. UUID v7 as a correlation ID solves two problems at once: global uniqueness across services and a built-in timestamp for ordering spans without clock synchronization. See UUID v7 in Distributed Systems for the broader context.
Correlation ID middleware — Node.js / Fastify
import Fastify from 'fastify';
import { v7 as uuidv7 } from 'uuid';
const app = Fastify({ logger: true });
app.addHook('onRequest', async (request, reply) => {
const correlationId =
(request.headers['x-correlation-id'] as string) ?? uuidv7();
// Attach to request context for downstream use
request.correlationId = correlationId;
// Echo back so clients can correlate responses
reply.header('x-correlation-id', correlationId);
// Bind to logger so every log line includes it
request.log = request.log.child({ correlationId });
});
declare module 'fastify' {
interface FastifyRequest {
correlationId: string;
}
}
Every inbound request either inherits the upstream correlation ID or gets a fresh UUID v7. The timestamp embedded in the ID lets you sort log lines by correlation ID prefix alone. See UUID in JavaScript for the uuid npm package setup.
Propagating to downstream services
import axios from 'axios';
async function callInventoryService(
orderId: string,
correlationId: string,
): Promise<InventoryResult> {
const { data } = await axios.get(
`${INVENTORY_URL}/stock/${orderId}`,
{ headers: { 'x-correlation-id': correlationId } },
);
return data;
}
Pass the correlation ID as a header to every downstream HTTP call. In message queue systems (Kafka, RabbitMQ, SQS), include it in the message envelope:
await producer.send({
topic: 'order-events',
messages: [{
key: orderId,
value: JSON.stringify({ orderId, status: 'created' }),
headers: { 'x-correlation-id': correlationId },
}],
});
See UUID v7 in Event Sourcing for the message ID pattern.
OpenTelemetry — UUID v7 as trace ID
OpenTelemetry’s TraceId is a 128-bit hex string. UUID v7 fits directly:
import { trace, context } from '@opentelemetry/api';
import { v7 as uuidv7 } from 'uuid';
// Generate a trace ID that encodes start time
const traceId = uuidv7().replace(/-/g, ''); // 32 hex chars, no hyphens
// '018fbe3a4c5d7b128abc0123456789ab'
// Inject into W3C traceparent header
// traceparent: 00-<traceId>-<spanId>-<flags>
const spanId = uuidv7().replace(/-/g, '').slice(0, 16); // 16 hex chars
const traceparent = `00-${traceId}-${spanId}-01`;
The 48-bit timestamp prefix means traceId.slice(0, 12) is the Unix millisecond the trace started — useful for log queries like “all traces from the last hour”. See UUID Epoch for the millisecond extraction.
Idempotency across service boundaries
UUID v7 works as an idempotency key for cross-service operations:
// Order service — generate idempotency key with request
const idempotencyKey = uuidv7();
// Payment service — deduplicate on this key
const payment = await paymentClient.charge({
amount: order.total,
idempotencyKey, // payment service stores this; retries are safe
});
// Idempotency window can be derived from the UUID v7 timestamp:
// keys older than 24h can be pruned without a separate createdAt column
const keyTimestamp = parseInt(idempotencyKey.replace(/-/g, '').slice(0, 12), 16);
const isExpired = Date.now() - keyTimestamp > 86_400_000;
See UUID as Idempotency Keys for the full deduplication pattern.
Python — FastAPI correlation ID middleware
from fastapi import FastAPI, Request
from fastapi.responses import Response
import uuid
app = FastAPI()
@app.middleware("http")
async def correlation_id_middleware(request: Request, call_next):
correlation_id = request.headers.get("x-correlation-id") or str(uuid.uuid7())
request.state.correlation_id = correlation_id
response: Response = await call_next(request)
response.headers["x-correlation-id"] = correlation_id
return response
See UUID in FastAPI for the full FastAPI integration pattern.
Further reading
- UUID v7 in Distributed Systems
- UUID as Idempotency Keys
- UUID v7 in Event Sourcing
- UUID in AWS Lambda — serverless patterns
- UUID Epoch — timestamp extraction
External references
- W3C Trace Context — traceparent header
- OpenTelemetry Trace API
- uuid npm package
- RFC 9562 — UUID standard
Frequently asked questions
Should I use UUID v4 or UUID v7 as a trace ID in OpenTelemetry?
UUID v7 is preferable for new systems. Its 48-bit Unix millisecond prefix means the trace ID itself encodes when the trace started — no separate startTime field needed for log correlation. OpenTelemetry's W3C Trace Context uses a 128-bit random trace-id, which UUID v7 satisfies. UUID v4 works but loses the timestamp. See UUID v7 in Distributed Systems.
How do I propagate a UUID v7 correlation ID across HTTP services?
Set the correlation ID as an HTTP header on every outbound request: X-Correlation-ID: 018fbe3a-4c5d-7b12-.... In Express/Fastify, read it from the inbound request or generate a new UUID v7 if absent. Log the correlation ID in every log line. Because UUID v7 is sortable, you can reconstruct call order from IDs alone. See UUID in AWS Lambda for serverless correlation ID patterns.