Search code examples
azureazure-api-managementretrypolicy

Retry request ends with "Content length mismatch"


My problem goes this way:

I have an Azure APIM, I have created an API and addeded the backend retry policy as below.

<backend>
    <retry condition="@("{{Transient-ErrorCode}}".Contains(Convert.ToString(context.Response.StatusCode)))" count="3" interval="5" first-fast-retry="false">
        <forward-request />
    </retry>
</backend>

The server return success(statuscode: 200) for the first time, When it initiate the retry it encountered the following(I am retrying at its success also, for testing the retry is working fine.).

forward-request (1.326 ms)
{
"messages": [
    "Content length mismatch",
    "Content length mismatch"
    ]
}

Please help with your thoughts/experience on the same.


Solution

  • This is because request sent by client is not cached in memory by default in APIM, instead it's streamed right from client to backend. So when needs come to retry the request request payload is not there. I assume that you have problems only with requests that have body.

    To resolve the issue you first need to cache request body:

    <inbound>
        <set-variable name="body" value="@(context.Request.Body.As<string>(preserveContent: true))" />
    </inbound>
    <backend>
        <retry condition="@("{{Transient-ErrorCode}}".Contains(Convert.ToString(context.Response.StatusCode)))" count="3" interval="5" first-fast-retry="false">
            <set-body>@((string)context.Variables["body"])</set-body>
            <forward-request />
        </retry>
    </backend>