Azure Functions Intermediate

Errors, retries and idempotency

Things fail in the cloud: a database times out, an API returns 503, a message has bad data. Good function apps decide which failures to retry, which to give up on, and make sure a retry never does the work twice.

Deciding what to do with a failure
  1. StartException thrownYour code catches or lets it bubble up.
  2. Step 2Transient?Timeouts and 503s are retried with backoff.
  3. Step 3Permanent?Bad data is logged and dead-lettered at once.
  4. Step 4Retries used upThe message moves to the poison queue.
  5. EndAlert and replayFix the cause, then resend the messages.

Retries are only safe when the handler is idempotent.

Who retries what

  • Storage queue and Service Bus triggers retry by themselves: throw an exception and the message is delivered again, up to maxDequeueCount or the max delivery count.
  • Timer, Event Hubs, Kafka and Cosmos DB triggers can use a function-level retry policy (fixed delay or exponential backoff).
  • HTTP triggers do not retry; the caller sees the error and decides.
  • Inside your code, retry quick transient faults (a 503, a timeout) with a resilience pipeline before giving up.

A retry policy on a trigger

C#
[Function("ProcessTelemetry")]
[ExponentialBackoffRetry(5, "00:00:04", "00:05:00")]
public async Task Run(
    [EventHubTrigger("telemetry", Connection = "EventHubs")] string[] events,
    CancellationToken ct)
{
    await _store.SaveBatchAsync(events, ct);
}

Transient faults in your own calls

Use Microsoft.Extensions.Http.Resilience on typed HttpClients. The standard handler adds retries with backoff, a circuit breaker and timeouts.

C#
builder.Services.AddHttpClient<IRatesClient, RatesClient>(c =>
        c.BaseAddress = new Uri("https://rates.example.com/"))
    .AddStandardResilienceHandler();

Make retries safe

A message can be delivered twice, and a retry can run after half the work was done. Design for it: store a processed id before or with the change, use upserts instead of inserts, and pass idempotency keys to payment and email APIs.

Do not retry errors that will never succeed, such as validation failures. Log them clearly and dead-letter or reject the message right away.

Alert on poison and dead-letter queues so failed work is noticed and replayed after a fix.

Interview question

How do you make an Azure Function safe to retry?

I make it idempotent: processing the same message twice gives the same result. I record message or business ids that were already handled, use upserts, and pass idempotency keys to external APIs. I retry only transient errors, send permanent failures to the poison or dead-letter queue, and alert on those queues.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.