In this lesson, you will learn how to maintain user identity across asynchronous message queues and microservice boundaries to ensure your distributed traces tell a complete, authenticated story.
The Challenge of Identity Loss
When a user triggers an action in a distributed system, that request might hop through several services and even sit in a message queue (like RabbitMQ or Kafka) before final processing. If your system only tracks the "machine" identity (like a service-to-service token), you lose visibility into which user initiated the operation. Distributed tracing allows us to stitch these disparate logs together, but without explicit Identity Propagation, your traces will lack the context of the end-user.
Propagating the Context
To preserve identity, you must inject the user's authentication context into the metadata of your distributed trace. In Node.js, we typically use the AsyncLocalStorage pattern or a trace header to carry the user_id or claims alongside the trace_id.
When publishing a message to a queue, you attach the identity to the message attributes:
// Producer: Sending a message with identity context
const message = {
payload: { orderId: 123 },
metadata: {
traceId: currentTraceId,
userId: req.user.id, // Propagating identity
userRole: req.user.role
}
};
channel.sendToQueue('orders', Buffer.from(JSON.stringify(message)));
On the receiving end, your worker service extracts these headers and restores the context before execution:
// Consumer: Extracting identity context
channel.consume('orders', (msg) => {
const { userId, traceId } = JSON.parse(msg.properties.headers);
// Re-attach to local context for the duration of this task
context.run({ userId, traceId }, () => {
processOrder(); // Auth checks now have access to 'userId'
});
});
Why This Matters
By propagating identity into your trace spans, you bridge the gap between technical monitoring and user experience. If a background job fails, you no longer have to guess which user was impacted; you can search your observability platform by userId and see the full, authenticated journey of that specific request across every service it touched.
Key Takeaway: Identity propagation bridges the gap between infrastructure observability and business logic by carrying user context headers through asynchronous boundaries to ensure every trace is linked to the authenticated actor.