Redis Streams is a log data structure for event-driven architectures. UUID v7 values as message payload IDs — rather than Redis’s native millisecond-sequence IDs — give globally portable correlation identifiers that survive cross-cluster replication, database joins, and multi-service tracing. See UUID v7 in Redis for the full Redis context.

Appending messages with UUID v7 correlation IDs

import { createClient } from 'redis';
import { v7 as uuidv7 } from 'uuid';

const redis = createClient({ url: 'redis://localhost:6379' });
await redis.connect();

interface OrderEvent {
  orderId: string;    // UUID v7 — correlates with database row
  customerId: string;
  total: string;
  status: string;
  correlationId: string; // UUID v7 — trace across services
}

async function publishOrderEvent(event: Omit<OrderEvent, 'correlationId'>) {
  const correlationId = uuidv7(); // New UUID v7 for this specific event

  // XADD with Redis auto-generated stream ID (ms-seq)
  // UUID v7 stored as field in the message payload
  const streamId = await redis.xAdd('orders:events', '*', {
    order_id:       event.orderId,
    customer_id:    event.customerId,
    total:          event.total,
    status:         event.status,
    correlation_id: correlationId, // UUID v7 for cross-service tracing
  });

  console.log(`Published event: stream_id=${streamId} correlation_id=${correlationId}`);
  return { streamId, correlationId };
}

Consumer group with UUID v7 deduplication

// Create consumer group
await redis.xGroupCreate('orders:events', 'order-processor', '$', { MKSTREAM: true });

async function processEvents(consumerId: string) {
  while (true) {
    const messages = await redis.xReadGroup(
      'order-processor',
      consumerId,
      [{ key: 'orders:events', id: '>' }],
      { COUNT: 10, BLOCK: 5000 }
    );

    if (!messages) continue;

    for (const { messages: msgs } of messages) {
      for (const msg of msgs) {
        const { correlation_id, order_id, status } = msg.message;

        // Deduplication: check if this correlation ID was already processed
        const key = `dedup:${correlation_id}`;
        const isNew = await redis.setNX(key, '1');
        if (!isNew) {
          console.log(`Skipping duplicate: ${correlation_id}`);
          await redis.xAck('orders:events', 'order-processor', msg.id);
          continue;
        }

        // Set expiry on dedup key (UUID v7 timestamp tells us when to expire)
        const createdMs = parseInt(correlation_id.replace(/-/g, '').slice(0, 12), 16);
        const ageMs = Date.now() - createdMs;
        const ttlSeconds = Math.max(3600 - Math.floor(ageMs / 1000), 60);
        await redis.expire(key, ttlSeconds);

        // Process the event
        console.log(`Processing order ${order_id}: ${status} [trace: ${correlation_id}]`);
        await redis.xAck('orders:events', 'order-processor', msg.id);
      }
    }
  }
}

See UUID as Idempotency Keys.

Time-range queries with UUID v7 correlation IDs

function uuidV7AtMs(ms: number): string {
  const hex = ms.toString(16).padStart(12, '0');
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7000-8000-000000000000`;
}

async function getEventsInWindow(startMs: number, endMs: number) {
  // Read events from the stream in the time window
  const messages = await redis.xRange('orders:events', '-', '+');

  // Filter by UUID v7 correlation_id timestamp
  const startUuid = uuidV7AtMs(startMs);
  const endUuid = uuidV7AtMs(endMs);

  return messages.filter(msg => {
    const cid = msg.message.correlation_id;
    return cid >= startUuid && cid < endUuid;
  });
}

// Example: events from the last hour
const oneHourAgo = Date.now() - 3600_000;
const recentEvents = await getEventsInWindow(oneHourAgo, Date.now());

Linking stream messages to database records

import { v7 as uuidv7 } from 'uuid';

async function createOrderWithEvent(customerId: string, total: number) {
  // Generate UUID v7 ONCE — used in both DB and stream
  const orderId = uuidv7();

  // Write to database
  await db.execute(
    'INSERT INTO orders (id, customer_id, total) VALUES (?, ?, ?)',
    [orderId, customerId, total]
  );

  // Publish event to Redis Streams with the same UUID v7
  await redis.xAdd('orders:events', '*', {
    order_id: orderId,    // Same UUID v7 as database primary key
    event:    'created',
    customer_id: customerId,
    total:    String(total),
  });

  return orderId;
}

See UUID v7 in Event Sourcing for the broader event streaming pattern.

Further reading

External references

Frequently asked questions

Can I use UUID v7 as a Redis Streams message ID?

Redis Streams require message IDs in the format milliseconds-sequence (e.g. 1700000000000-0) by default. You can use a custom string ID only if it is lexicographically greater than the last ID and follows Redis's ID format rules. A better approach is to store UUID v7 as a field in the message payload, using Redis's auto-generated ID as the stream ID. See UUID v7 in Redis.

How does UUID v7 help with Redis Streams consumer group deduplication?

Include a UUID v7 correlation_id field in every stream message. Consumers check this field against a deduplication set (a Redis SET with TTL) before processing. SETNX correlation_id "1" EX 3600 returns 0 if already processed. UUID v7's timestamp means old correlation IDs expire naturally as the TTL covers their time window. See UUID as Idempotency Keys.

How do I correlate Redis Stream messages with database records using UUID v7?

Generate UUID v7 before writing to both the database and the stream: const id = uuidv7(), then INSERT INTO orders (id, ...) VALUES ($id, ...) and XADD orders_stream * order_id $id status pending. The same UUID v7 appears in both the database row and the stream message — enabling zero-join correlation between the event log and the database state. See UUID v7 in Event Sourcing.