Injecting Correlation Identifier with API Management Policy

2024, Feb 18

With the use of correlation identifiers, we can more easily identify and resolve issues in distributed applications. If you use Azure API Management for your APIs, you can control requests via policies, by injecting correlation IDs on requests, similar to how it was done in this previous article, but in this post, let's implement a policy to inject a correlation identifier in the request header via APIM Policy.

The policy fragment

In the context of the API request, the policy fragment is implemented to add a correlationId to the request header if not available on the request. The set-header policy is used to add a new header to the request. The choose policy is used to check if the header is already present in the request. If not, a new x-correlationId is generated and added to the request.

        <when condition="@(context.Request.Headers.ContainsKey("x-correlationId"))">
            <!-- Header is present, pass the request through -->
            <!-- Header is not present, generate GUID and assign to header -->
            <set-header name="x-correlationId" exists-action="override">
            <!-- Pass the request through -->

In API Management go to Policy fragments, create a new Fragment and provide the code above:


The policy

APIM policies can be added at different scopes1, in this example the policy is applied to all APIs. Always remember that you have different scope options to apply policies, such as product, operation, all APIs, etc. The policy is added to the inbound section of the API request, so it is executed before the request is processed by the backend service.

        <base />
        <!-- Call the Correlation Id fragment -->
        <include-fragment fragment-id="x-correlation-id-fragment" />
        <base />
        <base />
        <base />

Testing the scenarios

APIM provides an easy way to Trace requests and validate whether the policies are working or not.


In my example I created a mock API using this Microsoft Docs article

For when the correlationId is provided via header, the same x-correlationId is used:



When the correlationId is not provided via header, a new x-correlationId is provided:



The details provided via Trace show us that the policies are working as expected.