How to use correlation IDs in ASP.Net Web API


When working with microservices that communicate over the HTTP protocol, you will want to use correlation IDs to track individual requests. Because requests might flow through many services that are spread across multiple systems, tracking them with correlation IDs will be your only hope of detecting and diagnosing errors that might creep into the middleware systems. This article discusses what correlation IDs are, why they are useful, and how they can be used in ASP.Net Web API.

What are correlation IDs?

Let’s assume you have implemented a microservices architecture. In an application comprised of microservices, different aspects of incoming requests will be handled by different microservices, all working asynchronously on their specific tasks and ultimately coming together to generate the response. Now, if something goes wrong, how would you determine by looking at the logs exactly where the request failed? Your logs might contain millions upon millions of log messages. It would be a daunting task to find the relevant log entries among so many messages.

The basic idea is that you may want to track every request. Because the request may be executed by different service components, you need a way to tie all of these service components to the request. Here’s exactly where a correlation ID comes to the rescue. A correlation ID is a unique identifier that provides a way to correlate all of the different micro tasks to the same macro operation. By ensuring that all of the responses contain the same unique identifier, you allow for the tracking and debugging of each request.

Using correlation IDs in Web API

ASP.Net Web API is a lightweight framework for building RESTful services that can run over HTTP. It has been the framework of choice for building RESTful services in ASP.Net for quite some time now. In this example, we will implement a message handler to store a correlation ID in the response header, so that we can send that ID back to the client.