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.

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

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

policy-fragment

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.

<policies>
    <inbound>
        <base />
        <!-- Call the Correlation Id fragment -->
        <include-fragment fragment-id="x-correlation-id-fragment" />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Testing the scenarios

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

APIM-Test

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:

policy-test-with-correlation-id

policy-test-with-correlation-id-result

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

policy-test-no-correlation-id

policy-test-no-correlation-id-result

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