Azure Functions provides a serverless environment for executing background tasks, processing messages, and responding to events without managing application servers. It is also a useful platform for running AI agent workflows that need to execute asynchronously or respond to external events.

When an AI agent performs multiple operations, managing execution becomes more complicated. A workflow might call an LLM, retrieve information from a database, execute external tools, and save the final result. Some operations finish quickly, while others may require retries, delays, or human approval.

Building a custom scheduler for these workflows introduces additional responsibilities, including job tracking, retry management, failure recovery, and execution coordination.

Azure Functions, combined with Azure Durable Functions, provides a way to manage these requirements without building an entire scheduling system from scratch.

This article explains how to run AI agent workflows using Azure Functions, implement durable orchestration with C#, manage failures, and handle long-running operations in production environments.

Understanding Azure Durable Functions

Azure Functions supports different execution models depending on the type of workload.

For simple background operations, a normal Azure Function may be sufficient. However, when an AI workflow contains multiple dependent steps, Durable Functions provides additional orchestration capabilities.

Durable Functions extends Azure Functions with workflow management features such as:

  • Maintaining workflow execution history.
  • Managing multiple dependent operations.
  • Resuming interrupted workflows.
  • Supporting retry policies.
  • Waiting for external events.
  • Managing timers and delays.
  • Coordinating parallel operations.

The main advantage is that developers do not need to build their own workflow scheduler, checkpoint manager, and execution recovery mechanism.

Azure Functions vs. Durable Functions

FeatureAzure FunctionsDurable Functions
Event-driven executionYesYes
Background processingYesYes
Multi-step orchestrationRequires custom implementationBuilt-in
Workflow state managementRequires additional storage logicManaged by the durable runtime
Workflow recoveryRequires custom implementationSupported
Waiting for external eventsRequires custom implementationSupported
Long-running workflowsRequires additional coordinationDesigned for orchestration
Retry managementAvailable through additional implementation or extensionsSupports orchestration-level retries

For AI agent workflows involving multiple steps, Durable Functions is generally a better starting point than implementing everything inside a single Azure Function.

Understanding the Durable Functions Architecture

Durable Functions uses three important types of functions.

Client Function

The client function starts a new workflow instance.

It can be triggered by an HTTP request, a queue message, or another supported event.

For example, when a user submits a document for AI analysis, the client function creates a new orchestration instance.

Orchestrator Function

The orchestrator function controls the execution sequence.

It determines which operation should run next, manages dependencies between activities, and coordinates workflow execution.

The orchestrator should remain deterministic because Durable Functions can replay its execution history to reconstruct its current state.

Avoid directly calling external APIs, accessing databases, generating random values, or using the current system time inside an orchestrator. Put these operations inside activity functions instead.

Activity Function

Activity functions perform the actual business operations.

For an AI agent, activities can:

  • Retrieve information from databases.
  • Call an LLM provider.
  • Execute external tools.
  • Process documents.
  • Save generated results.
  • Send notifications.

The architecture looks like this:

Code
       User Request
            |
            v
      Client Function
            |
            v
    Durable Orchestrator
            |
            v
    Retrieve Application Data
            |
            v
        Call LLM
            |
            v
      Execute AI Tools
            |
            v
      Save AI Results
            |
            v
     Workflow Completed

The orchestrator coordinates the activities while Durable Functions manages the workflow execution history.

Creating an AI Workflow With Azure Functions

Let's implement a practical example.

Assume we are building an AI document analysis application. Whenever a user submits a document, the application should:

  1. Retrieve the document content.
  2. Send the content to an LLM.
  3. Generate a structured summary.
  4. Save the result.
  5. Return the workflow completion status.

Instead of implementing all these operations inside one function, we will create separate activities.

Step 1: Create an Azure Functions Project

Create a new Azure Functions project using the .NET isolated worker model.

Add the required Durable Functions extension package:

Bash
dotnet add package Microsoft.Azure.Functions.Worker.Extensions.DurableTask

Configure the application to use the Azure Functions isolated worker model and the appropriate Durable Functions extension version.

The isolated worker model allows developers to use modern .NET dependency injection and application configuration patterns.

Step 2: Create the Client Function

The client function receives a document identifier and starts the orchestration.

C#
public class AgentWorkflowStarter
{
    [Function("StartAgentWorkflow")]
    public async Task<HttpResponseData> StartAsync(
        [HttpTrigger(
            AuthorizationLevel.Function,
            "post")] HttpRequestData request,
        [DurableClient] DurableTaskClient client)
    {
        var input = await JsonSerializer
            .DeserializeAsync<DocumentRequest>(
                request.Body);

        if (input == null ||
            string.IsNullOrWhiteSpace(input.DocumentId))
        {
            var badResponse = request.CreateResponse(
                HttpStatusCode.BadRequest);

            return badResponse;
        }

        var instanceId =
            await client.ScheduleNewOrchestrationInstanceAsync(
                nameof(DocumentAgentOrchestrator.Run),
                input.DocumentId);

        return await client.CreateCheckStatusResponseAsync(
            request, instanceId);
    }
}

public class DocumentRequest
{
    public string DocumentId { get; set; } = string.Empty;
}

The client function creates a new orchestration instance and returns the standard Durable Functions status response.

This response includes URLs that can be used to check the workflow status.

The HTTP request does not need to remain open while the AI agent processes the document.

Step 3: Create the Orchestrator Function

The orchestrator controls the sequence of activities.

C#
public class DocumentAgentOrchestrator
{
    [Function(nameof(Run))]
    public async Task<string> Run(
        [OrchestrationTrigger]
        TaskOrchestrationContext context)
    {
        var documentId = context.GetInput<string>();

        var document = await context.CallActivityAsync<string>(
            "RetrieveDocument",
            documentId);

        var summary = await context.CallActivityAsync<string>(
            "AnalyzeDocumentWithAI",
            document);

        await context.CallActivityAsync(
            "SaveDocumentSummary",
            summary);

        return "Document processing completed";
    }
}

The orchestrator calls three activities in sequence.

First, it retrieves the document. Next, it sends the document content for AI analysis. Finally, it saves the generated summary.

Notice that the orchestrator does not directly call the LLM provider or database.

This separation is important because orchestrator execution can be replayed. Keeping external operations inside activities prevents those operations from being unnecessarily repeated during orchestration replay.

Step 4: Implement the LLM Activity

The LLM activity performs the actual model request.

C#
public class AIActivities
{
    private readonly IChatCompletionService _llm;

    public AIActivities(IChatCompletionService llm)
    {
        _llm = llm;
    }

    [Function("AnalyzeDocumentWithAI")]
    public async Task<string> AnalyzeAsync(
        [ActivityTrigger] string document)
    {
        var prompt = $"""
            Analyze the following document.

            Generate a summary containing:
            - Main purpose
            - Important findings
            - Potential risks
            - Recommended actions

            Document:
            {document}
            """;

        return await _llm.GenerateAsync(
            prompt,
            CancellationToken.None);
    }
}

The activity receives the document content and sends it to the configured LLM service.

The LLM integration remains independent of the orchestration logic. This makes it easier to replace providers, introduce structured output, or change prompt templates without redesigning the entire workflow.

In production, configure authentication through managed identity or secure application configuration where supported. Also introduce request timeouts, token limits, rate-limit handling, and appropriate logging.

Step 5: Save the Generated Result

After the LLM returns a summary, another activity can persist the result.

C#
public class DocumentStorageActivity
{
    private readonly IDocumentRepository _repository;

    public DocumentStorageActivity(
        IDocumentRepository repository)
    {
        _repository = repository;
    }

    [Function("SaveDocumentSummary")]
    public async Task SaveAsync(
        [ActivityTrigger] string summary)
    {
        await _repository.SaveSummaryAsync(summary);
    }
}

The repository can use Entity Framework Core, Dapper, or another supported persistence approach.

For a real application, include the document ID in the activity input so that the generated summary can be associated with the correct document.

Handling Failures and Retrying AI Operations

LLM providers can temporarily become unavailable because of network problems, rate limits, or service interruptions.

Durable Functions supports retry policies for activity execution.

For example, an orchestrator can configure a retry policy when calling an LLM activity.

C#
var retryOptions = TaskOptions.FromRetryPolicy(
    new RetryPolicy(
        maxNumberOfAttempts: 3,
        firstRetryInterval: TimeSpan.FromSeconds(5)));

var summary = await context.CallActivityAsync<string>(
    "AnalyzeDocumentWithAI",
    document,
    retryOptions);

This configures up to three activity attempts with an initial retry interval of five seconds.

Retry configuration should be selected according to the failure type and provider limits.

One important consideration is that an activity may complete an external operation before its completion is recorded. If the worker fails during that interval, the activity can execute again.

Therefore, activities that create external side effects should use idempotency keys or verify whether the operation has already completed.

LLM requests should also be handled carefully because repeating an unsuccessful request may generate a different response and incur additional costs.

Running Scheduled AI Workflows

Not every AI workflow needs to start from an HTTP request.

For example, a business application might need to analyze pending support tickets every morning.

Azure Functions supports timer triggers for scheduled execution.

C#
public class ScheduledAgent
{
    [Function("DailyAgentWorkflow")]
    public async Task Run(
        [TimerTrigger("0 0 8 * * *")] TimerInfo timer,
        [DurableClient] DurableTaskClient client)
    {
        await client.ScheduleNewOrchestrationInstanceAsync(
            nameof(DocumentAgentOrchestrator.Run),
            "daily-document-batch");
    }
}

This example starts an orchestration every day at 8:00 AM, using the configured timer schedule and time zone settings.

The timer trigger starts the workflow, while Durable Functions manages its execution.

For recurring jobs, consider duplicate prevention and overlapping executions. If a previous batch is still running, the application should decide whether to start another instance, wait, or reject the new execution.

Best Practices for Production AI Workflows

Keep Orchestrators Deterministic

Never perform direct LLM calls, database operations, or external HTTP requests inside an orchestrator.

Move those operations into activities so that replay does not repeat external side effects.

Keep Activity Inputs and Outputs Manageable

Durable Functions stores orchestration history. Passing large documents and complete LLM responses through the orchestration history can increase storage requirements.

Store large content in Blob Storage or another appropriate storage system and pass references between activities.

Configure Retry Policies Carefully

Do not retry every failure.

Use bounded retries for transient problems and handle permanent errors separately. Respect provider rate limits and retry-after instructions.

Use Managed Identity Where Possible

Avoid storing credentials directly in application code or configuration files.

Use managed identities and appropriate Azure permissions when accessing supported Azure services.

Monitor Workflow Execution

Use Application Insights and Azure Functions monitoring capabilities to track failures, execution duration, retries, and application exceptions.

Include workflow instance IDs in application logs to make individual executions easier to investigate.

Design Activities for Idempotency

An activity might execute more than once under failure conditions.

Use unique operation identifiers and verify previous execution results before performing external operations again.

Advantages and Disadvantages

Durable Functions offers several advantages for AI agent applications.

Advantages:

  • Reduces the need to build a custom workflow scheduler.
  • Supports long-running background operations.
  • Maintains workflow execution history.
  • Provides activity-level retry capabilities.
  • Supports event-driven and scheduled workflows.
  • Helps recover interrupted executions.
  • Integrates with the Azure Functions ecosystem.

Disadvantages:

  • Introduces additional orchestration concepts.
  • Requires careful handling of orchestration replay.
  • Large execution histories can increase storage requirements.
  • Activity operations still need idempotency.
  • Complex workflows require additional monitoring and debugging.
  • Creates a dependency on the Azure Functions and Durable Task infrastructure.

For applications already using Azure, these trade-offs are often reasonable when workflows involve multiple dependent operations.

Common Mistakes and Troubleshooting

ProblemPossible causeRecommended solution
LLM request executes more than onceExternal call placed inside an orchestratorMove the call into an activity
Workflow remains pendingWorker or orchestration infrastructure issueInspect instance status and execution history
Activity repeatedly failsInvalid input or permanent provider errorSeparate transient and permanent failures
Large orchestration historyPassing complete documents between activitiesStore large content externally
Duplicate scheduled workflowsPrevious execution overlaps with a new triggerImplement concurrency and duplicate prevention
Workflow cannot resume correctlyChanged workflow logic or incompatible stateMaintain workflow versioning and deployment compatibility

Summary

Azure Functions provides a serverless environment for running AI agent workloads, while Durable Functions adds orchestration capabilities for managing multi-step and long-running processes.

Instead of building a custom scheduler, developers can use client functions to start workflows, orchestrators to coordinate execution, and activities to perform LLM requests and external operations.

A reliable implementation should keep orchestrators deterministic, store large results outside orchestration history, configure retries carefully, and make external operations idempotent.

For developers building AI-powered applications on Azure, Durable Functions provides a practical foundation for managing asynchronous execution, workflow recovery, scheduled processing, and complex agent operations without maintaining an entire custom orchestration system.