Event-driven systems replace synchronous request-response chains with asynchronous message flows across multiple services. Without a correlation ID threading through every hop, debugging a failed order that touched five services requires manually stitching together logs by timestamp — an error-prone process. UUID v7 as a correlation ID solves this: the same identifier appears in every event, every database row, and every log line for the entire causal chain, and the embedded timestamp makes the chain sortable. This guide covers correlation ID patterns for Apache Kafka, RabbitMQ, and NATS.
The Event Envelope Pattern
All events in a well-designed event-driven system share a common envelope structure:
interface EventEnvelope<T = unknown> {
// Tracing
eventId: string; // UUID v7 — this specific event
correlationId: string; // UUID v7 — the originating request (same throughout the chain)
causationId: string; // UUID v7 — the event that directly caused this one
// Metadata
eventType: string; // e.g., "order.placed", "inventory.reserved"
eventVersion: number; // schema version for consumer compatibility
occurredAt: string; // ISO 8601 — redundant with UUID v7 ts, kept for readability
producerService: string;
// Payload
payload: T;
}
import { v7 as uuidv7 } from 'uuid';
function createEvent<T>(
eventType: string,
payload: T,
options: { correlationId: string; causationId: string },
): EventEnvelope<T> {
return {
eventId: uuidv7(), // new UUID v7 for each event
correlationId: options.correlationId, // propagated unchanged
causationId: options.causationId, // ID of the triggering event
eventType,
eventVersion: 1,
occurredAt: new Date().toISOString(),
producerService: process.env.SERVICE_NAME ?? 'unknown',
payload,
};
}
Apache Kafka
Producing with UUID v7 Event Headers
import { Kafka, CompressionTypes } from 'kafkajs';
import { v7 as uuidv7 } from 'uuid';
const kafka = new Kafka({ brokers: ['localhost:9092'] });
const producer = kafka.producer({ idempotent: true });
interface OrderPlacedPayload {
orderId: string;
customerId: string;
total: number;
items: Array<{ sku: string; qty: number }>;
}
async function publishOrderPlaced(
order: OrderPlacedPayload,
correlationId: string,
): Promise<string> {
const event = createEvent<OrderPlacedPayload>(
'order.placed',
order,
{ correlationId, causationId: correlationId }, // command is its own causation
);
await producer.send({
topic: 'orders',
compression: CompressionTypes.GZIP,
messages: [{
// Entity ID as Kafka key — ensures same order always goes to same partition
key: order.orderId,
value: JSON.stringify(event),
headers: {
'event-id': event.eventId,
'correlation-id': correlationId,
'event-type': event.eventType,
},
timestamp: String(Date.now()),
}],
});
return event.eventId;
}
Consuming with Idempotency
const consumer = kafka.consumer({ groupId: 'inventory-service' });
await consumer.subscribe({ topics: ['orders'], fromBeginning: false });
// Track processed event IDs to handle duplicate delivery
const processedEvents = new Set<string>(); // In production: Redis or Postgres
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
const eventId = message.headers?.['event-id']?.toString();
const correlationId = message.headers?.['correlation-id']?.toString();
if (!eventId) {
console.warn('Message missing event-id header — skipping');
return;
}
// Idempotency check — UUID v7 ensures each event has a stable, unique ID
if (processedEvents.has(eventId)) {
console.log(JSON.stringify({ correlationId, event: 'duplicate.skipped', eventId }));
return;
}
const envelope: EventEnvelope<OrderPlacedPayload> = JSON.parse(message.value!.toString());
// Reserve inventory and publish downstream event
const reservationId = await reserveInventory(envelope.payload);
const inventoryEvent = createEvent(
'inventory.reserved',
{ reservationId, orderId: envelope.payload.orderId },
{
correlationId: envelope.correlationId, // propagate unchanged
causationId: envelope.eventId, // caused by OrderPlaced
},
);
await producer.send({
topic: 'inventory',
messages: [{
key: envelope.payload.orderId,
value: JSON.stringify(inventoryEvent),
headers: {
'event-id': inventoryEvent.eventId,
'correlation-id': inventoryEvent.correlationId,
'causation-id': inventoryEvent.causationId,
},
}],
});
processedEvents.add(eventId);
console.log(JSON.stringify({
correlationId,
causationId: envelope.eventId,
event: 'inventory.reserved',
reservationId,
}));
},
});
Time-Based Event Replay
function uuidV7ToTimestamp(uuidV7: string): number {
return parseInt(uuidV7.replace(/-/g, '').slice(0, 12), 16);
}
// Find all events for a correlation ID within a time window
async function replayCorrelationChain(
correlationId: string,
sinceMs: number,
) {
const admin = kafka.admin();
const offsets = await admin.fetchTopicOffsetsByTimestamp('orders', sinceMs);
// Start consumer from the calculated offset and filter by correlation ID
const replayConsumer = kafka.consumer({ groupId: `replay-${uuidv7()}` });
await replayConsumer.subscribe({ topics: ['orders'], fromBeginning: false });
// Seek to timestamp-based offsets
replayConsumer.on('consumer.connect', async () => {
for (const { partition, offset } of offsets) {
await replayConsumer.seek({ topic: 'orders', partition, offset });
}
});
const chain: EventEnvelope[] = [];
await replayConsumer.run({
eachMessage: async ({ message }) => {
const headerCorrelationId = message.headers?.['correlation-id']?.toString();
if (headerCorrelationId === correlationId) {
chain.push(JSON.parse(message.value!.toString()));
}
},
});
// Sort by eventId — UUID v7 lexicographic = chronological
return chain.sort((a, b) => a.eventId.localeCompare(b.eventId));
}
RabbitMQ
Publishing with Correlation ID
import amqp from 'amqplib';
import { v7 as uuidv7 } from 'uuid';
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createConfirmChannel();
await channel.assertExchange('domain-events', 'topic', { durable: true });
async function publishEvent<T>(
routingKey: string,
payload: T,
options: { correlationId: string; causationId: string },
) {
const event = createEvent(routingKey, payload, options);
return new Promise<void>((resolve, reject) => {
channel.publish(
'domain-events',
routingKey,
Buffer.from(JSON.stringify(event)),
{
messageId: event.eventId, // UUID v7 for this message
correlationId: event.correlationId, // UUID v7 propagated through chain
headers: {
'causation-id': event.causationId,
'event-version': event.eventVersion,
'producer': event.producerService,
},
persistent: true,
contentType: 'application/json',
timestamp: Math.floor(Date.now() / 1000),
},
(err) => (err ? reject(err) : resolve()),
);
});
}
// HTTP handler — originating request
async function handleCreateOrder(req: Request) {
const correlationId = req.headers.get('x-correlation-id') ?? uuidv7();
const body = await req.json();
const orderId = uuidv7();
await saveOrder({ id: orderId, ...body, correlationId });
await publishEvent(
'order.placed',
{ orderId, customerId: body.customerId, total: body.total },
{ correlationId, causationId: correlationId },
);
return Response.json({ orderId }, { status: 201 });
}
Dead-Letter Queue Analysis
async function analyseDlq(dlqName: string): Promise<void> {
const dlqChannel = await connection.createChannel();
await dlqChannel.assertQueue(dlqName, { durable: true });
dlqChannel.consume(dlqName, (msg) => {
if (!msg) return;
const { messageId, correlationId, headers: msgHeaders } = msg.properties;
const ageMs = messageId
? Date.now() - parseInt(messageId.replace(/-/g, '').slice(0, 12), 16)
: null;
console.log(JSON.stringify({
messageId,
correlationId,
causationId: msgHeaders?.['causation-id'],
ageSeconds: ageMs != null ? Math.floor(ageMs / 1000) : null,
stale: ageMs != null && ageMs > 3_600_000,
deathReason: msgHeaders?.['x-death']?.[0]?.reason,
deathCount: msgHeaders?.['x-death']?.[0]?.count,
}));
// Acknowledge to remove from DLQ after analysis
dlqChannel.ack(msg);
}, { noAck: false });
}
NATS JetStream
NATS JetStream provides persistent messaging with message headers:
import { connect, headers as natsHeaders, StringCodec } from 'nats';
import { v7 as uuidv7 } from 'uuid';
const nc = await connect({ servers: 'nats://localhost:4222' });
const js = nc.jetstream();
const sc = StringCodec();
// Create a stream for domain events
const jsm = await nc.jetstreamManager();
await jsm.streams.add({
name: 'DOMAIN_EVENTS',
subjects: ['events.>'],
retention: 'limits',
max_age: 7 * 24 * 60 * 60 * 1e9, // 7 days in nanoseconds
});
async function publishNatsEvent<T>(
subject: string,
payload: T,
options: { correlationId: string; causationId: string },
) {
const event = createEvent(subject, payload, options);
const hdrs = natsHeaders();
hdrs.append('event-id', event.eventId);
hdrs.append('correlation-id', event.correlationId);
hdrs.append('causation-id', event.causationId);
hdrs.append('event-type', event.eventType);
const ack = await js.publish(
subject,
sc.encode(JSON.stringify(event)),
{ headers: hdrs, msgID: event.eventId }, // msgID = JetStream deduplication key
);
return { eventId: event.eventId, seq: ack.seq };
}
// Consumer
const consumer = await js.consumers.get('DOMAIN_EVENTS', 'inventory-service');
const messages = await consumer.consume({ max_messages: 100 });
for await (const msg of messages) {
const correlationId = msg.headers?.get('correlation-id');
const eventId = msg.headers?.get('event-id');
if (!correlationId || !eventId) {
msg.nak();
continue;
}
const event: EventEnvelope = JSON.parse(sc.decode(msg.data));
// Process...
console.log(JSON.stringify({
correlationId,
event: 'event.processed',
eventId,
subject: msg.subject,
}));
msg.ack();
}
Event Store — Persisting the Full Chain
Store every event in an append-only event store table with the correlation and causation IDs:
CREATE TABLE event_store (
event_id UUID PRIMARY KEY, -- UUID v7
correlation_id UUID NOT NULL, -- UUID v7 — spans the full chain
causation_id UUID NOT NULL, -- UUID v7 — direct parent event
event_type TEXT NOT NULL,
event_version INT NOT NULL DEFAULT 1,
aggregate_id UUID, -- UUID v7 of the entity this event belongs to
aggregate_type TEXT,
payload JSONB NOT NULL,
metadata JSONB DEFAULT '{}',
producer_service TEXT NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Indexes for common query patterns
CREATE INDEX ON event_store (correlation_id); -- Reconstruct full chains
CREATE INDEX ON event_store (causation_id); -- Find direct children
CREATE INDEX ON event_store (aggregate_id); -- Rebuild aggregate state
CREATE INDEX ON event_store (event_type, event_id); -- Type-scoped time queries
-- Reconstruct the full event chain for a correlation ID (sorted by UUID v7 = time order)
SELECT event_id, event_type, causation_id, producer_service, occurred_at
FROM event_store
WHERE correlation_id = '018fbe3a-4c5d-7000-8abc-0123456789ab'
ORDER BY event_id; -- UUID v7 lexicographic = chronological
Distributed Tracing Integration
UUID v7 correlation IDs integrate naturally with OpenTelemetry:
import { trace, context, propagation } from '@opentelemetry/api';
import { v7 as uuidv7 } from 'uuid';
// Use the correlation ID as the OpenTelemetry trace ID (hex, no hyphens)
function correlationIdToTraceId(correlationId: string): string {
return correlationId.replace(/-/g, ''); // 32 hex chars = 16 bytes = OTel trace ID
}
async function publishWithOtelContext<T>(
topic: string,
payload: T,
correlationId: string,
) {
const span = trace.getActiveSpan();
const traceId = correlationIdToTraceId(correlationId);
const event = createEvent(topic, payload, {
correlationId,
causationId: correlationId,
});
// Inject W3C traceparent header
const carrier: Record<string, string> = {};
propagation.inject(context.active(), carrier);
await producer.send({
topic,
messages: [{
value: JSON.stringify(event),
headers: {
...carrier, // W3C traceparent
'correlation-id': correlationId, // UUID v7 domain correlation ID
'trace-id': traceId, // Raw hex for OTel backends
},
}],
});
}
Best Practices Summary
| Practice | Reason |
|---|---|
| Assign UUID v7 correlation ID at the API gateway or first service | Single source of truth for the chain |
| Propagate unchanged to every downstream event and log | Enables single-query chain reconstruction |
| Use UUID v7 (not v4) for correlation IDs | Embedded timestamp makes chains time-sortable |
| Set causation ID to the direct parent event ID | Enables causal graph reconstruction |
| Use entity ID (not event ID) as Kafka partition key | Preserves per-entity ordering |
Use event ID as Kafka msgID / SQS MessageDeduplicationId | Prevents duplicate processing |
| Store full event envelope in an append-only event store | Enables replay and audit |
Further Reading
- UUID in Message Queues — RabbitMQ and SQS patterns
- UUID in Kubernetes — cloud-native correlation IDs
- UUID in Serverless — Lambda and Edge patterns
- UUID Versions — v4 vs v7 comparison
External References
- Apache Kafka documentation: producer idempotency, message headers, and consumer group semantics
- RabbitMQ publisher documentation: BasicProperties, confirmations, and dead-letter queues
- NATS JetStream documentation: persistent messaging, message headers, and deduplication
- OpenTelemetry Trace API: trace ID format and W3C traceparent propagation
- uuid npm package: UUID v7 generation for Node.js producers and consumers
- RFC 9562 — UUID standard: authoritative UUID v7 specification
Frequently asked questions
What is a correlation ID in event-driven architecture?
A correlation ID is a unique identifier assigned to an originating request or command and propagated through every downstream event, message, and log entry that results from it. When an HTTP request to POST /orders triggers an OrderPlaced event, which triggers an InventoryReserved event, which triggers a NotificationSent event — all four carry the same correlation ID. Searching logs or the event store for that ID reconstructs the full causal chain. UUID v7 is ideal because the embedded timestamp makes correlation IDs time-sortable across services.
What is the difference between a correlation ID and a causation ID?
A correlation ID is the same throughout an entire request chain — it connects all events back to the originating command. A causation ID identifies the specific event or command that directly caused the current event. For example, if OrderPlaced (causation) causes InventoryReserved, the causation ID of InventoryReserved is the ID of OrderPlaced. Both IDs should be UUID v7 so that event chains are navigable by time as well as by cause.
Should Kafka message keys be UUID v7?
Kafka message keys control which partition a message goes to — all messages with the same key go to the same partition (preserving order). UUID v7 as a Kafka message key routes messages randomly across partitions (because the random bits outweigh the timestamp prefix for hashing purposes) — which is good for even load distribution but breaks per-entity ordering. A better pattern is to use the entity ID (e.g., orderId) as the Kafka key for ordering guarantees, and UUID v7 as the message ID in the message headers for deduplication and tracing.
How does UUID v7 help with event replay in Kafka?
When replaying events from a Kafka topic for debugging or rebuilding a read model, UUID v7 event IDs allow you to resume from a specific point in time without knowing the Kafka offset. Extract the millisecond timestamp from the UUID v7, convert it to a Kafka timestamp filter, and replay from that point. Additionally, idempotent consumers can use the UUID v7 event ID in a processed_events table to skip already-applied events during replay.
How do I propagate a correlation ID across NATS subjects?
NATS messages do not have built-in headers in core NATS, but NATS JetStream supports message headers. Set Nats-Correlation-Id (or a custom header) to the UUID v7 correlation ID when publishing. Consumers read the header and include it in their own published messages and log entries. In core NATS, embed the correlation ID in the message payload envelope.