Message queues decouple producers and consumers, but every message still needs a stable identity for deduplication, dead-letter analysis, and replay. UUID v7 as a message ID gives time-ordered identifiers that encode when a message was published — making stale messages in a DLQ immediately identifiable without parsing the message body. This guide covers UUID v7 in RabbitMQ and Amazon SQS using the uuid npm package, uuid6 Python package, and uuid-creator Java library.

RabbitMQ — publishing with UUID v7 message IDs

Node.js (amqplib)

import amqp from 'amqplib';
import { v7 as uuidv7 } from 'uuid';

const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();

await channel.assertQueue('orders', { durable: true });

const messageId = uuidv7();  // UUID v7 message ID
const payload = {
  orderId: uuidv7(),         // UUID v7 also used as database record ID
  customerId: 'a8098c1a-...',
  total: 99.99,
};

channel.sendToQueue('orders', Buffer.from(JSON.stringify(payload)), {
  messageId,                  // UUID v7 in RabbitMQ BasicProperties
  correlationId: uuidv7(),    // UUID v7 for request tracing
  persistent: true,
  timestamp: Date.now(),
});

The messageId property is stored in RabbitMQ’s message envelope and passed to consumers. Setting it to UUID v7 means consumers can determine message age without parsing the body: parseInt(messageId.replace(/-/g,'').slice(0,12), 16) gives Unix milliseconds.

Python (pika)

import pika
import uuid6
import json

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='orders', durable=True)

message_id = str(uuid6.uuid7())
payload = {
    'order_id': str(uuid6.uuid7()),
    'customer_id': 'a8098c1a-...',
    'total': 99.99,
}

channel.basic_publish(
    exchange='',
    routing_key='orders',
    body=json.dumps(payload),
    properties=pika.BasicProperties(
        message_id=message_id,
        delivery_mode=2,  # persistent
        content_type='application/json',
    )
)

The Pika RabbitMQ client documentation covers BasicProperties, connection parameters, and acknowledgement modes. The uuid6 package on PyPI provides uuid7() for Python.

Dead-letter queue analysis with UUID v7

When messages land in a DLQ, UUID v7 IDs reveal how old they are:

def analyse_dlq_message(message_id: str) -> dict:
    ts_ms = int(message_id.replace('-', '')[:12], 16)
    age_s = (time.time() * 1000 - ts_ms) / 1000

    return {
        'message_id': message_id,
        'published_at': datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc).isoformat(),
        'age_seconds': int(age_s),
        'stale': age_s > 3600,  # Flag messages older than 1 hour
    }

This immediately answers “how long has this message been stuck?” without checking the original publish timestamp in the message body — useful when the body is malformed (which is often why it ended in the DLQ).

Amazon SQS — FIFO queues with UUID v7

import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';
import { v7 as uuidv7 } from 'uuid';

const sqs = new SQSClient({ region: 'us-east-1' });

const messageId = uuidv7();

await sqs.send(new SendMessageCommand({
  QueueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789/orders.fifo',
  MessageBody: JSON.stringify({ orderId: uuidv7(), total: 99.99 }),
  MessageGroupId: customerId,        // Route related messages to same consumer
  MessageDeduplicationId: messageId, // UUID v7 deduplication within 5-min window
}));

The 5-minute SQS deduplication window means retrying with the same UUID v7 MessageDeduplicationId within 5 minutes is safe — SQS silently drops the duplicate. After 5 minutes, retrying with the same ID may result in a second delivery. For safe retry beyond 5 minutes, generate a new UUID v7. The Amazon SQS FIFO documentation covers message group IDs and deduplication semantics.

Correlation ID propagation

Propagate a UUID v7 correlation ID across the message chain:

// Producer — sets correlation ID at message origin
const correlationId = uuidv7();
channel.sendToQueue('orders', payload, {
  messageId: uuidv7(),
  correlationId,          // UUID v7 — traces through the entire chain
  headers: { 'x-service': 'order-api', 'x-version': '2' },
});

// Consumer — passes correlation ID to downstream messages and DB inserts
channel.consume('orders', async (msg) => {
  const { correlationId, messageId } = msg.properties;

  // Insert with same correlation ID
  await db.query(
    'INSERT INTO order_events (id, correlation_id, ...) VALUES ($1, $2, ...)',
    [messageId, correlationId, ...]
  );

  // Publish downstream event with same correlation ID
  channel.sendToQueue('invoices', invoicePayload, {
    messageId: uuidv7(),         // New message ID for this hop
    correlationId,               // Carried through unchanged
  });

  channel.ack(msg);
});

UUID v7 correlation IDs are time-ordered — sorting all database rows and queue messages by correlation_id prefix gives approximate chronological order of the entire request chain across services.

Java (Spring AMQP)

import org.springframework.amqp.core.*;
import com.github.f4b6a3.uuid.UuidCreator;

@Service
public class OrderPublisher {
    private final RabbitTemplate rabbitTemplate;

    public void publishOrder(Order order) {
        String messageId = UuidCreator.getTimeOrderedEpoch().toString();

        Message message = MessageBuilder
            .withBody(objectMapper.writeValueAsBytes(order))
            .setMessageId(messageId)
            .setCorrelationId(order.getCorrelationId())
            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
            .build();

        rabbitTemplate.send("orders", message);
    }
}

The Spring AMQP documentation covers RabbitTemplate, MessageBuilder, and listener container configuration.

Further reading

External references

Frequently asked questions

Should message IDs in RabbitMQ be UUID v4 or UUID v7?

UUID v7 is the better choice for message IDs in most cases. RabbitMQ stores the message ID in the BasicProperties.MessageId field and passes it through to consumers unchanged — either UUID version works. UUID v7 adds two operational benefits: the message ID encodes when the message was published (useful for debugging stale messages in a DLQ), and messages can be replayed in creation order by sorting message IDs lexicographically. The RabbitMQ publisher documentation covers message properties and delivery guarantees.

How do I use UUID v7 for SQS message deduplication?

Amazon SQS FIFO queues require a MessageDeduplicationId — the queue deduplicates messages with the same ID within a 5-minute window. UUID v7 works as a deduplication ID: each message gets a unique UUID v7 at publish time, and the 5-minute deduplication window can be monitored by comparing the UUID v7 timestamp prefix against the current time. If a retry occurs within 5 minutes (same deduplication ID), SQS silently drops it. See the Amazon SQS FIFO queue documentation for deduplication window details.

How do I correlate messages across RabbitMQ and a database with UUID v7?

Assign a UUID v7 as both the message ID and the primary key of the corresponding database record. The message ID in RabbitMQ and the row ID in the database are the same UUID v7 value — joining logs from both systems requires no additional correlation field. Use the uuid npm package or uuid6 on PyPI to generate the UUID v7 before publishing and before inserting the database row.