Event sourcing stores every state change as an immutable event. Two properties are essential for event IDs: global uniqueness (no two events can share an ID across all streams) and chronological ordering (events should sort by when they occurred). UUID v7 satisfies both natively — its 128-bit width and random suffix prevent collisions, and its timestamp prefix imposes chronological sort order. See Time Precision for the 48-bit millisecond detail.
Event record structure
interface DomainEvent {
eventId: string; // UUID v7 — unique, time-ordered
aggregateId: string; // UUID v7 — the entity this event belongs to
streamName: string; // e.g. 'order-018fbe3a-4c5d-7b12-...'
eventType: string; // e.g. 'OrderPlaced'
payload: unknown;
occurredAt: number; // Unix ms — redundant with eventId but explicit
version: number; // position in the aggregate stream
}
import { v7 as uuidv7 } from 'uuid';
function createEvent(
aggregateId: string,
eventType: string,
payload: unknown,
version: number,
): DomainEvent {
return {
eventId: uuidv7(),
aggregateId,
streamName: `order-${aggregateId}`,
eventType,
payload,
occurredAt: Date.now(),
version,
};
}
Both eventId and aggregateId are UUID v7 — the aggregate ID is stable across all its events (assigned at creation time), while eventId is fresh for each event. See UUID as Idempotency Keys for using eventId to deduplicate handler re-runs.
PostgreSQL event store table
CREATE TABLE events (
event_id uuid PRIMARY KEY DEFAULT uuidv7(), -- PG 18+
aggregate_id uuid NOT NULL,
stream_name text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
occurred_at timestamptz NOT NULL DEFAULT now(),
version int NOT NULL,
UNIQUE (aggregate_id, version) -- optimistic concurrency
);
-- Time-range replay — uses the UUID v7 primary key index
SELECT * FROM events
WHERE event_id >= $lower_bound
AND event_id < $upper_bound
ORDER BY event_id;
-- Aggregate stream replay
SELECT * FROM events
WHERE aggregate_id = $1
ORDER BY version;
UNIQUE (aggregate_id, version) enforces optimistic concurrency — two concurrent writes at the same version fail with a unique constraint violation. The event ID primary key index serves all time-range queries without a secondary index on occurred_at. See UUID in Databases.
Idempotent event handler
async function handleEvent(event: DomainEvent): Promise<void> {
// Check if already processed using eventId as idempotency key
const processed = await db.query(
'SELECT 1 FROM processed_events WHERE event_id = $1',
[event.eventId]
);
if (processed.rowCount > 0) return; // already handled
// Process and mark as handled atomically
await db.transaction(async tx => {
await applyEvent(tx, event);
await tx.query(
'INSERT INTO processed_events (event_id) VALUES ($1)',
[event.eventId]
);
});
}
Using eventId as the idempotency key makes the handler safe to retry — at-least-once delivery from Kafka or EventStoreDB cannot cause duplicate state mutations. See UUID v7 in Kafka Event Streaming for the Kafka consumer pattern.
EventStoreDB stream naming
// Use aggregate UUID v7 as part of the stream name
const streamName = `Order-${aggregateId}`;
// Append event
await client.appendToStream(streamName, [
jsonEvent({
id: uuidv7(), // EventStoreDB uses this for idempotency
type: 'OrderPlaced',
data: { customerId, items },
})
]);
// Read stream from beginning
const events = client.readStream(streamName, { fromRevision: START });
EventStoreDB accepts a client-supplied id for each event — providing a UUID v7 enables server-side deduplication on retry. See Monotonic Counter for within-millisecond ordering when events are generated in a tight loop.
Further reading
- UUID v4 vs v7 — time-ordered keys
- UUID v7 in Kafka Event Streaming
- UUID as Idempotency Keys
- UUID in Databases — B-tree and ordering
- Time Precision — UUID v7 millisecond timestamp
- Monotonic Counter — within-ms ordering
- UUID v7 for Audit Logging
External references
Frequently asked questions
Why is UUID v7 better than UUID v4 for event IDs in event sourcing?
Event-sourced systems frequently need to replay, paginate, and compare events by time. UUID v4 is purely random — ORDER BY event_id returns events in no meaningful order, forcing a separate timestamp column and index for chronological queries. UUID v7 embeds a 48-bit Unix millisecond timestamp in the leading bits, so ORDER BY event_id is chronological order. This eliminates a secondary index and avoids the B-tree fragmentation that random UUID v4 keys cause. See UUID v4 vs v7.
How do I use UUID v7 as a Kafka event key in event sourcing?
Use the aggregate ID (e.g., order UUID v7) as the Kafka partition key — this guarantees all events for the same aggregate land in the same partition and are processed in order. Use a separate UUID v7 as the event ID for deduplication and idempotency. Do not use the event UUID v7 as the partition key — consecutive events for different aggregates would be routed to different partitions based on their random suffix, not their aggregate association. See UUID v7 in Kafka Event Streaming.