Correlation ID

Enterprise Integration Jan 6, 2025 JAVASCRIPT

Definition

Have you ever tracked a package online and watched it move from city to city? That tracking number follows your package through the entire delivery journey - from the moment it leaves the warehouse, through sorting facilities, onto trucks, and finally to your doorstep. A correlation ID works exactly the same way in the world of software: it’s a unique identifier that follows a request as it travels through multiple services and systems.

In modern applications, a single user action often triggers a chain of events across many different services. When you click “Buy Now” on an e-commerce site, your request might touch the shopping cart service, inventory service, payment service, fraud detection, shipping calculator, and email notification system. If something goes wrong somewhere in that chain, how do you figure out what happened? This is where correlation IDs become invaluable. By attaching the same unique identifier to every step of the process, you can trace exactly what happened, when, and where.

Think of it as giving every request a unique name tag that it wears throughout its entire journey. When you look at your logs later, you can search for that name tag and see the complete story of what happened - across every service, every database call, every API request. Without correlation IDs, you’d be looking at millions of log entries with no way to connect related events. With them, you can instantly reconstruct the entire sequence of events for any specific request.

Example

Real-World Scenario 1: Debugging a Failed Purchase A customer complains their order failed. Customer support enters the order ID, which includes a correlation ID. They can now see: the request hit the cart service (success), moved to payment (success), went to fraud detection (flagged as suspicious), was sent for manual review, and ultimately timed out. Without the correlation ID, finding these connected events across five different services would take hours instead of seconds.

Real-World Scenario 2: Netflix Streaming Issues When you press play on Netflix and the video won’t load, that play button triggers requests to dozens of services. Netflix uses correlation IDs to trace: your request to the content delivery network, authentication check, license validation, bandwidth estimation, and video encoding selection. Engineers can follow a single correlation ID to see exactly where the stream failed to start.

Real-World Scenario 3: Uber Ride Matching When you request an Uber, a correlation ID is generated. It follows your request through driver matching, ETA calculation, surge pricing, payment authorization, and driver notification. If a ride request fails, Uber can trace that specific request through all these services to find the bottleneck - maybe the payment service was slow, or driver matching timed out.

Real-World Scenario 4: Banking Transaction Audits When you transfer money between accounts, regulators may later ask the bank to prove exactly what happened. The correlation ID attached to your transaction lets the bank produce a complete audit trail: request received, fraud check passed, sender account debited, receiver account credited, confirmation sent. Every step is linked by that single ID.

Analogy

The Relay Race Baton: In a relay race, the baton passes from runner to runner, but it’s the same baton throughout. If you wanted to analyze the race later, you’d track that specific baton’s journey. The correlation ID is your digital baton - it passes from service to service, and you can trace its complete journey.

The Medical Record Number: When you visit a hospital, you get a medical record number. Whether you’re in the ER, getting an X-ray, visiting a specialist, or picking up prescriptions, that same number connects all your activities. Months later, your doctor can pull up that number and see everything that happened during your visit. Correlation IDs give your requests that same persistent identity.

The Case File Number: When you file an insurance claim, it gets a case number. Whether your claim is being processed by the initial reviewer, sent to an adjuster, reviewed by a manager, or handled by the payment department, that case number ties everything together. You can call and say “I’m calling about case #12345” and they can see the entire history.

The Tour Group Sticker: On a group tour, everyone wears the same colored sticker or follows the same numbered flag. If the tour guide needs to account for everyone, they look for that color or number. The correlation ID is like that sticker - it identifies which requests belong together as they move through the system.

Code Example


// Express.js middleware to generate/propagate correlation ID
const { v4: uuidv4 } = require('uuid');

app.use((req, res, next) => {
  // Get from header or generate new
  const correlationId = req.headers['x-correlation-id'] || uuidv4();

  // Attach to request
  req.correlationId = correlationId;

  // Return in response
  res.setHeader('X-Correlation-ID', correlationId);

  next();
});

// [Logging](https://reference.apios.info/terms/logging/) with correlation ID
app.get('/api/orders/:id', async (req, res) => {
  logger.info('Fetching order', {
    correlationId: req.correlationId,
    orderId: req.params.id
  });

  // Pass to downstream services
  const payment = await fetch('https://payment-service/check', {
    headers: {
      'X-Correlation-ID': req.correlationId
    }
  });

  logger.info('Payment checked', {
    correlationId: req.correlationId
  });
});

// Example log output
// [2024-01-15 10:30:00] INFO correlationId=abc-123 service=api-gateway path=/orders/456
// [2024-01-15 10:30:01] INFO correlationId=abc-123 service=order-service action=fetch
// [2024-01-15 10:30:02] INFO correlationId=abc-123 service=payment-service action=check

Standards & RFCs