Home / AI & GenAI

AI & GenAITroubleshootingBeginner

Azure Document Intelligence analyze calls fail: 429, InvalidContent, unreadable blobs and expired results

RAG ingestion stops at the document parsing step. Read the inner error code, then fix throttling, file limits, blob access, sign-in and polling.

Deepak Bhardwaj9 min read

Applies toAzure AI Document Intelligence v4.0 REST API (2024-11-30), S0 and F0 tiers, prebuilt-layout and prebuilt-read models

Your ingestion job calls Document Intelligence and some documents never reach the index. The job log says 400, 403, 404 or 429 and little else. The useful part is the inner error code, and for many failures it only appears when you poll for the result.

Start with one failing document and get that code.

Symptom, cause and fix

What you see Likely cause Fix
401 Wrong key, wrong endpoint or token problem Check access
403 on POST Missing role or network rule Check access
429 Too many POSTs, or too much polling Fix throttling
InvalidContent Corrupt, unsupported or not really that format Fix the file
InvalidContentLength File over the tier's size limit Fix the file
InvalidContentDimensions Image too small or too large Fix the file
ContentSourceNotAccessible, InvalidSasToken The service can't fetch the URL Fix blob access
OutboundAccessForbidden Outbound URL restrictions on the resource Fix blob access
OperationNotFound Wrong operation ID, or the result has expired Fix polling
Only two pages returned F0 (free) tier Move to S0

Get the inner error code

Set the basics. Use the resource's own custom-domain endpoint:

RG=rg-ai-prod
ACCOUNT=di-prod-01

az cognitiveservices account show -g $RG -n $ACCOUNT \
  --query "{kind:kind, sku:sku.name, endpoint:properties.endpoint, domain:properties.customSubDomainName, public:properties.publicNetworkAccess, localAuthOff:properties.disableLocalAuth}" \
  -o yaml

ENDPOINT=$(az cognitiveservices account show -g $RG -n $ACCOUNT --query properties.endpoint -o tsv)
ENDPOINT=${ENDPOINT%/}
TOKEN=$(az account get-access-token --resource https://cognitiveservices.azure.com --query accessToken -o tsv)

Send the document as raw bytes. This removes blob access from the picture:

curl -sS -D headers.txt -o body.json -X POST \
  "$ENDPOINT/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&outputContentFormat=markdown" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/octet-stream" \
  --data-binary @failing.pdf

cat headers.txt body.json

A good submission returns 202 with an Operation-Location header. That only means the job was accepted. Poll it:

OP=$(grep -i '^operation-location:' headers.txt | cut -d' ' -f2- | tr -d '\r')
sleep 5
curl -sS "$OP" -H "Authorization: Bearer $TOKEN" | jq '{status, error}'

Status moves through notStarted and running to succeeded or failed. Read error.code, error.innererror.code and error.details on a failure.

Tip

If raw bytes work but the same file fails with urlSource, the document is fine. Go straight to blob access.

Check access: 401 and 403

Token sign-in needs three things: a custom subdomain on the resource, a data-plane role, and the right token audience. Owner or Contributor alone doesn't grant data-plane calls.

ID=$(az cognitiveservices account show -g $RG -n $ACCOUNT --query id -o tsv)

az role assignment list --scope $ID --include-inherited \
  --query "[].{who:principalName, role:roleDefinitionName}" -o table

az role assignment create --assignee-object-id <APP_OBJECT_ID> \
  --assignee-principal-type ServicePrincipal \
  --role "Cognitive Services User" --scope $ID

Role changes can take several minutes to apply. If you use keys, confirm disableLocalAuth isn't true, and that the key belongs to this resource. Send it as Ocp-Apim-Subscription-Key.

For a 403 that mentions networking, check the rules and resolve the name from the machine that fails:

az cognitiveservices account network-rule list -g $RG -n $ACCOUNT -o yaml
az network private-endpoint-connection list --id $ID -o table
nslookup $ACCOUNT.cognitiveservices.azure.com

Fix throttling: 429

Submitting and polling have separate limits. The documented defaults for S0 are 15 analyze POSTs and 50 get-result calls per second. F0 allows 1 of each. Check the current limits for your resource.

Work out which call is throttled before changing anything:

Throttled call Usual reason Fix
POST :analyze Parallel workers start together Cap concurrency and ramp up gradually
GET result Tight loops, many open operations Poll each operation no more than once every 2 seconds

Find the pattern in metrics:

az monitor metrics list-definitions --resource $ID --query "[].name.value" -o tsv

az monitor metrics list --resource $ID --metric ClientErrors TotalCalls \
  --interval PT1M --offset 2h --aggregation Total -o table

If diagnostic settings send logs to a Log Analytics workspace, check response codes per operation:

AzureDiagnostics
| where ResourceProvider == "MICROSOFT.COGNITIVESERVICES"
| where TimeGenerated > ago(6h)
| summarize calls = count() by OperationName, ResultSignature, bin(TimeGenerated, 5m)
| order by TimeGenerated desc

This worker honours Retry-After, backs off on throttling and caps parallel work:

import time
from concurrent.futures import ThreadPoolExecutor
import requests
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

ENDPOINT = "https://di-prod-01.cognitiveservices.azure.com"
get_token = get_bearer_token_provider(
    DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")

def wait_seconds(resp, default):
    try:
        return max(2, int(resp.headers.get("Retry-After", default)))
    except ValueError:
        return default

def call(method, url, **kw):
    headers = kw.pop("headers", {})
    for delay in (2, 5, 13, 34, None):
        headers["Authorization"] = f"Bearer {get_token()}"
        r = requests.request(method, url, headers=headers, timeout=120, **kw)
        if r.status_code in (429, 503) and delay is not None:
            time.sleep(max(delay, wait_seconds(r, delay)))
            continue
        if not r.ok:
            raise RuntimeError(f"{r.status_code} {r.text[:500]}")
        return r

def analyze(path, max_wait=900):
    with open(path, "rb") as f:
        data = f.read()
    r = call("POST",
             f"{ENDPOINT}/documentintelligence/documentModels/prebuilt-layout:analyze",
             params={"api-version": "2024-11-30", "outputContentFormat": "markdown"},
             headers={"Content-Type": "application/octet-stream"}, data=data)
    op = r.headers["Operation-Location"]
    deadline = time.monotonic() + max_wait
    while time.monotonic() < deadline:
        time.sleep(wait_seconds(r, 3))
        r = call("GET", op)
        body = r.json()
        if body["status"] == "succeeded":
            return body["analyzeResult"]["content"]
        if body["status"] == "failed":
            raise RuntimeError(f"{path}: {body.get('error')}")
    raise TimeoutError(f"{path}: still running, operation {op}")

def safe(path):
    try:
        return path, analyze(path), None
    except Exception as e:
        return path, None, str(e)

with ThreadPoolExecutor(max_workers=4) as pool:
    for path, text, err in pool.map(safe, ["a.pdf", "b.pdf"]):
        print(path, "FAILED " + err if err else f"{len(text)} chars")

If steady demand is above the limit, the S0 analyze quota can be raised with a support request. Make sure the client behaves well first; more quota won't fix a tight polling loop.

Fix the file: InvalidContent and limits

Check what the file really is. An HTML login page saved as .pdf is a common cause of InvalidContent:

file failing.pdf
stat -c '%s bytes' failing.pdf
head -c 8 failing.pdf | xxd
pdfinfo failing.pdf | egrep 'Pages|Encrypted|Page size'

Documented limits for the layout model:

Limit F0 S0
File size 4 MB 500 MB
Pages per document First 2 2,000
Image dimensions 50 x 50 to 10,000 x 10,000 pixels Same

Practical fixes:

  • Password-protected PDF: get an unlocked copy from the owner. The service doesn't take a locked PDF.
  • Damaged PDF: rewrite it, for example with qpdf failing.pdf fixed.pdf, and compare page counts before using it.
  • Very long PDF: process page ranges with the pages query parameter, such as pages=1-200.
  • Oversized scan: downsample the image. Keep the text readable.
  • Two pages only: check the SKU from the first command. F0 isn't suitable for ingestion.

Fix blob access: urlSource failures

With urlSource the service fetches the file itself, so it needs its own path to storage. You have two choices.

Use a SAS URL

Test the exact URL the job sends, including its encoding:

curl -sS -o /dev/null -w '%{http_code}\n' -r 0-99 "<BLOB_URL_WITH_SAS>"

A 403 points to an expired SAS, a missing read permission, or a storage firewall. A 200 or 206 from your machine only proves the SAS is valid; the storage firewall may still block the service.

Use the resource's managed identity

Document Intelligence uses its system-assigned identity for this. Enable it and grant read access:

az cognitiveservices account identity assign -g $RG -n $ACCOUNT
PID=$(az cognitiveservices account identity show -g $RG -n $ACCOUNT --query principalId -o tsv)
SA=$(az storage account show -g $RG -n <STORAGE_ACCOUNT> --query id -o tsv)

az role assignment create --assignee-object-id $PID \
  --assignee-principal-type ServicePrincipal \
  --role "Storage Blob Data Reader" --scope $SA

az storage account show --ids $SA \
  --query "{default:networkRuleSet.defaultAction, bypass:networkRuleSet.bypass}"

Microsoft says the role can take up to 30 minutes to work. With a storage firewall, bypass must include AzureServices.

Warning

az storage account update --bypass sets the whole bypass list. Include the values that are already there, such as Logging Metrics AzureServices.

For OutboundAccessForbidden, look at the resource's outbound rules:

az cognitiveservices account show --ids $ID \
  --query "{restrict:properties.restrictOutboundNetworkAccess, allowed:properties.allowedFqdnList}"

Add the storage host to the allowed list, or send bytes instead.

Fix polling: OperationNotFound

Results are kept for a limited time; check the current retention in the documentation. A job that submits thousands of files and collects results the next day can lose them. Other causes:

  • The worker builds its own polling URL. Use Operation-Location exactly as returned.
  • The GET goes to another resource behind a load balancer. Operations belong to the resource that accepted them, so pin polling to it.
  • A retry submits the file again and overwrites the stored operation ID.

Resubmit expired documents. Each resubmission is a new analysis and is charged again, so save results to storage as soon as they succeed.

Prevent it next time

  • Validate type, size, page count and encryption before submitting, and quarantine bad files with a reason.
  • Store file hash, operation URL, status and inner error code for every document.
  • Retry only 429 and 5xx. Send 400 errors to a review queue.
  • Alert when client errors rise, and when the number of submitted documents differs from the number parsed.
  • Use S0 in every environment that runs real ingestion.
  • Test one urlSource call after any storage firewall, role or private endpoint change.