Expert patterns for Azure Functions development including isolated worker model, Durable Functions orchestration, cold start optimization, and production patterns. Covers .NET, Python, and Node.js programming models. Use when: azure function, azure functions, durable functions, azure serverless, function app.
Expert patterns for Azure Functions development including isolated worker model,
Durable Functions orchestration, cold start optimization, and production patterns.
Covers .NET, Python, and Node.js programming models.
Patterns
Isolated Worker Model (.NET)
Modern .NET execution model with process isolation
When to use: Building new .NET Azure Functions apps
Template
// Program.cs - Isolated Worker Model
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
// Add Application Insights
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
When to use: Need sequential workflow with automatic retry
Template
// C# Isolated Worker - Function Chaining
using Microsoft.Azure.Functions.Worker;
using Microsoft.DurableTask;
using Microsoft.DurableTask.Client;
public class OrderWorkflow
{
[Function("OrderOrchestrator")]
public static async Task<OrderResult> RunOrchestrator(
[OrchestrationTrigger] TaskOrchestrationContext context)
{
var order = context.GetInput<Order>();
// Functions execute sequentially, state persisted between each
var validated = await context.CallActivityAsync<ValidatedOrder>(
"ValidateOrder", order);
var payment = await context.CallActivityAsync<PaymentResult>(
"ProcessPayment", validated);
var shipped = await context.CallActivityAsync<ShippingResult>(
"ShipOrder", new ShipRequest { Order = validated, Payment = payment });
var notification = await context.CallActivityAsync<bool>(
"SendNotification", shipped);
return new OrderResult
{
OrderId = order.Id,
Status = "Completed",
TrackingNumber = shipped.TrackingNumber
};
}
[Function("ValidateOrder")]
public static async Task<ValidatedOrder> ValidateOrder(
[ActivityTrigger] Order order, FunctionContext context)
{
var logger = context.GetLogger<OrderWorkflow>();
logger.LogInformation("Validating order {OrderId}", order.Id);
// Validation logic...
return new ValidatedOrder { /* ... */ };
}
[Function("ProcessPayment")]
public static async Task<PaymentResult> ProcessPayment(
[ActivityTrigger] ValidatedOrder order, FunctionContext context)
{
// Payment processing with built-in retry...
return new PaymentResult { /* ... */ };
}
[Function("OrderWorkflow_HttpStart")]
public static async Task<HttpResponseData> HttpStart(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
[DurableClient] DurableTaskClient client,
FunctionContext context)
{
var order = await req.ReadFromJsonAsync<Order>();
string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(
"OrderOrchestrator", order);
return client.CreateCheckStatusResponse(req, instanceId);
}
}
Notes
State automatically persisted between activities
Automatic retry on transient failures
Survives process restarts
Built-in status endpoint for monitoring
Durable Functions - Fan-Out/Fan-In
Parallel execution with result aggregation
When to use: Processing multiple items in parallel
Template
// C# Isolated Worker - Fan-Out/Fan-In
using Microsoft.Azure.Functions.Worker;
using Microsoft.DurableTask;
public class ParallelProcessing
{
[Function("ProcessImagesOrchestrator")]
public static async Task<ProcessingResult> RunOrchestrator(
[OrchestrationTrigger] TaskOrchestrationContext context)
{
var images = context.GetInput<List<string>>();
// Fan-out: Start all tasks in parallel
var tasks = images.Select(image =>
context.CallActivityAsync<ImageResult>("ProcessImage", image));
// Fan-in: Wait for all tasks to complete
var results = await Task.WhenAll(tasks);
// Aggregate results
var successful = results.Count(r => r.Success);
var failed = results.Count(r => !r.Success);
return new ProcessingResult
{
TotalProcessed = results.Length,
Successful = successful,
Failed = failed,
Results = results.ToList()
};
}
[Function("ProcessImage")]
public static async Task<ImageResult> ProcessImage(
[ActivityTrigger] string imageUrl, FunctionContext context)
{
var logger = context.GetLogger<ParallelProcessing>();
logger.LogInformation("Processing image: {Url}", imageUrl);
try
{
// Image processing logic...
await Task.Delay(1000); // Simulated work
return new ImageResult
{
Url = imageUrl,
Success = true,
ProcessedUrl = $"processed-{imageUrl}"
};
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to process {Url}", imageUrl);
return new ImageResult { Url = imageUrl, Success = false };
}
}
// Python equivalent
// @app.orchestration_trigger(context_name="context")
// def process_images_orchestrator(context: df.DurableOrchestrationContext):
// images = context.get_input()
//
// # Fan-out: Create parallel tasks
// tasks = [context.call_activity("ProcessImage", img) for img in images]
//
// # Fan-in: Wait for all
// results = yield context.task_all(tasks)
//
// return {"processed": len(results), "results": results}
}
Notes
Parallel execution for independent tasks
Results aggregated when all complete
Memory efficient - only stores task IDs
Up to thousands of parallel activities
Cold Start Optimization
Minimize cold start latency in production
When to use: Need fast response times in production
Template
// 1. Use Premium Plan with pre-warmed instances
// host.json
{
"version": "2.0",
"extensions": {
"durableTask": {
"hubName": "MyTaskHub"
}
},
"functionTimeout": "00:30:00"
}
// Pre-initialize expensive resources
// Database connections, HttpClients, etc.
}
// 3. Use static/singleton clients with DI
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// HttpClientFactory prevents socket exhaustion
services.AddHttpClient<IMyApiClient, MyApiClient>(client =>
{
client.BaseAddress = new Uri("https://api.example.com");
client.Timeout = TimeSpan.FromSeconds(30);
});
// Singleton for expensive initialization
services.AddSingleton<IExpensiveService>(sp =>
{
// Initialize once, reuse across invocations
return new ExpensiveService();
});
}
// Alternative: Queue-based pattern without Durable Functions
[Function("StartWork")]
[QueueOutput("work-queue")]
public static async Task<WorkItem> StartWork(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
FunctionContext context)
{
var input = await req.ReadFromJsonAsync<WorkRequest>();
var workId = Guid.NewGuid().ToString();
// Queue the work, return immediately
var workItem = new WorkItem
{
Id = workId,
Request = input
};
// Return work ID for status checking
var response = req.CreateResponse(HttpStatusCode.Accepted);
await response.WriteAsJsonAsync(new
{
workId = workId,
statusUrl = $"/api/status/{workId}"
});
return workItem;
}
[Function("ProcessWork")]
public static async Task ProcessWork(
[QueueTrigger("work-queue")] WorkItem work,
FunctionContext context)
{
// Long-running processing here
// Update status in storage for polling
}
Notes
HTTP timeout is 230 seconds regardless of plan
Use Durable Functions for async patterns
Return immediately with status endpoint
Client polls for completion
Sharp Edges
HTTP Timeout is 230 Seconds Regardless of Plan
Severity: HIGH
Situation: HTTP-triggered functions with long processing time
Symptoms:
504 Gateway Timeout after ~4 minutes.
Request terminates before function completes.
Client receives timeout even though function continues.
host.json timeout setting has no effect for HTTP.
Why this breaks:
The Azure Load Balancer has a hard-coded 230-second idle timeout for HTTP
requests. This applies regardless of your function app timeout setting.
Even if you set functionTimeout to 30 minutes in host.json, HTTP triggers
will timeout after 230 seconds from the client's perspective.
The function may continue running after timeout, but the client won't
receive the response.
Recommended fix:
Use async pattern with Durable Functions
[Function("StartLongProcess")]
public static async Task<HttpResponseData> Start(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
[DurableClient] DurableTaskClient client)
{
var input = await req.ReadFromJsonAsync<WorkRequest>();
// Start orchestration, returns immediately
string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(
"LongRunningOrchestrator", input);
// Returns status URLs for polling
return client.CreateCheckStatusResponse(req, instanceId);
}
// Client polls statusQueryGetUri until complete
Use queue-based async pattern
[Function("StartWork")]
public static async Task<HttpResponseData> StartWork(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
[QueueOutput("work-queue")] out WorkItem workItem)
{
var workId = Guid.NewGuid().ToString();
workItem = new WorkItem { Id = workId, /* ... */ };
var response = req.CreateResponse(HttpStatusCode.Accepted);
await response.WriteAsJsonAsync(new {
id = workId,
statusUrl = $"/api/status/{workId}"
});
return response;
}
Use webhook callback pattern
// Client provides callback URL
// Function queues work, returns 202 Accepted
// When done, POST result to callback URL
Socket Exhaustion from HttpClient Instantiation
Severity: HIGH
Situation: Creating HttpClient instances inside function code
Symptoms:
SocketException: "Unable to connect to remote server"
"An attempt was made to access a socket in a way forbidden"
Sporadic connection failures under load.
Works locally but fails in production.
Why this breaks:
Creating a new HttpClient for each request creates a new socket connection.
Sockets linger in TIME_WAIT state for 240 seconds after closing.
In a serverless environment with high throughput, you quickly exhaust
available sockets. This affects all network clients, not just HttpClient.
Azure Functions shares network resources among multiple customers,
making this even more critical.
Recommended fix:
Use IHttpClientFactory (Recommended)
// Program.cs
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
services.AddHttpClient<IMyApiClient, MyApiClient>(client =>
{
client.BaseAddress = new Uri("https://api.example.com");
client.Timeout = TimeSpan.FromSeconds(30);
});
})
.Build();
// MyApiClient.cs
public class MyApiClient : IMyApiClient
{
private readonly HttpClient _client;
public MyApiClient(HttpClient client)
{
_client = client; // Injected, managed by factory
}
public async Task<string> GetDataAsync()
{
return await _client.GetStringAsync("/data");
}
}
Use static client (Alternative)
public static class MyFunction
{
// Static HttpClient, reused across invocations
private static readonly HttpClient _httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
[Function("MyFunction")]
public static async Task Run(...)
{
var result = await _httpClient.GetAsync("...");
}
}
Same pattern for Azure SDK clients
// Also applies to:
// - BlobServiceClient
// - CosmosClient
// - ServiceBusClient
// Use DI or static instances
Blocking Async Calls Cause Thread Starvation
Severity: HIGH
Situation: Using .Result, .Wait(), or Thread.Sleep in async code
Symptoms:
Deadlocks under load.
Requests hang indefinitely.
"A task was canceled" exceptions.
Works with low concurrency, fails with high.
Why this breaks:
Azure Functions thread pool is limited. Blocking calls (.Result, .Wait())
hold a thread hostage while waiting, preventing other work.
Thread.Sleep blocks a thread that could be handling other requests.
With multiple concurrent executions, you quickly run out of threads,
causing deadlocks and timeouts.
Recommended fix:
Always use async/await
// BAD - blocks thread
var result = httpClient.GetAsync(url).Result;
someTask.Wait();
Thread.Sleep(5000);
// GOOD - yields thread
var result = await httpClient.GetAsync(url);
await someTask;
await Task.Delay(5000);
Fix synchronous method calls
// BAD - sync over async
public void ProcessData()
{
var data = GetDataAsync().Result; // Blocks!
}
// GOOD - async all the way
public async Task ProcessDataAsync()
{
var data = await GetDataAsync();
}
Configure async in console/startup
// If you must call async from sync context
public static void Main(string[] args)
{
// Use GetAwaiter().GetResult() at entry point only
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
// Async code here
}
Consumption Plan 10-Minute Timeout Limit
Severity: MEDIUM
Situation: Running long processes on Consumption plan
Symptoms:
Function terminates after 10 minutes.
"Function timed out" in logs.
Incomplete processing with no error caught.
Works in development (with longer timeout) but fails in production.
Why this breaks:
Consumption plan has a hard limit of 10 minutes execution time.
Default is 5 minutes if not configured.
This cannot be increased beyond 10 minutes on Consumption plan.
Long-running work requires Premium plan or different architecture.
Recommended fix:
Configure maximum timeout (Consumption)
// host.json
{
"version": "2.0",
"functionTimeout": "00:10:00" // Max for Consumption
}
Upgrade to Premium plan for longer timeouts
// Premium plan - 30 min default, unbounded available
{
"version": "2.0",
"functionTimeout": "00:30:00" // Or remove for unbounded
}
Use Durable Functions for long workflows
[Function("LongWorkflowOrchestrator")]
public static async Task<string> RunOrchestrator(
[OrchestrationTrigger] TaskOrchestrationContext context)
{
// Each activity has its own timeout
// Workflow can run for days
await context.CallActivityAsync("Step1", input);
await context.CallActivityAsync("Step2", input);
await context.CallActivityAsync("Step3", input);
return "Complete";
}
Break work into smaller chunks
// Queue-based chunking
[Function("ProcessChunk")]
[QueueOutput("work-queue")]
public static IEnumerable<WorkChunk> ProcessChunk(
[QueueTrigger("work-queue")] WorkChunk chunk)
{
var results = Process(chunk);
// Queue next chunks if more work
if (chunk.HasMore)
{
yield return chunk.Next();
}
}
.NET In-Process Model Deprecated November 2026
Severity: HIGH
Situation: Creating new .NET functions or maintaining existing
Symptoms:
Using in-process model in new projects.
Dependency conflicts with host runtime.
Cannot use latest .NET versions.
Future migration burden.
Why this breaks:
The in-process model runs your code in the same process as the
Azure Functions host. This causes:
Assembly version conflicts
Limited to LTS .NET versions
No access to latest .NET features
Tighter coupling with host runtime
Support ends November 10, 2026. After this date, in-process apps
may stop working or receive no security updates.
Recommended fix:
Use isolated worker for new projects
# Create new isolated worker project
func init MyFunctionApp --worker-runtime dotnet-isolated
# Or with .NET 8
dotnet new func --name MyFunctionApp --framework net8.0
Migrate existing in-process to isolated
// OLD - In-process (FunctionName attribute)
public class InProcessFunction
{
[FunctionName("MyFunction")]
public async Task<IActionResult> Run(
[HttpTrigger] HttpRequest req,
ILogger log)
{
log.LogInformation("Processing");
return new OkResult();
}
}
// NEW - Isolated worker (Function attribute)
public class IsolatedFunction
{
private readonly ILogger<IsolatedFunction> _logger;
public IsolatedFunction(ILogger<IsolatedFunction> logger)
{
_logger = logger;
}
[Function("MyFunction")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Function, "get")]
HttpRequestData req)
{
_logger.LogInformation("Processing");
return req.CreateResponse(HttpStatusCode.OK);
}
}
Key migration changes
FunctionName → Function attribute
HttpRequest → HttpRequestData
IActionResult → HttpResponseData
ILogger injection → constructor injection
Add Program.cs with HostBuilder
ILogger Not Outputting to Console or AppInsights
Severity: MEDIUM
Situation: Using dependency-injected ILogger in isolated worker
Symptoms:
Logs not appearing in local console.
Logs not appearing in Application Insights.
Logs work with context.GetLogger() but not injected ILogger.
Must pass logger through all method calls.
Why this breaks:
In isolated worker model, the dependency-injected ILogger may not
be properly connected to the Azure Functions logging pipeline.
Local development especially affected - logs may go nowhere.
Application Insights requires explicit configuration.
The ILogger from FunctionContext works differently than
the injected ILogger<T>.
Recommended fix:
Configure Application Insights properly
// Program.cs
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
// Add App Insights telemetry
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
})
.Build();
Situation: Using triggers/bindings without installing extensions
Symptoms:
Function not triggering on events.
"No job functions found" warning.
Bindings not working despite correct configuration.
Works after adding extension package.
Why this breaks:
Azure Functions v2+ uses extension bundles for triggers and bindings.
If extensions aren't properly configured or packages aren't installed,
the function host can't recognize the bindings.
In isolated worker, you need explicit NuGet packages.
In in-process, you need Microsoft.Azure.WebJobs.Extensions.*.
# Check registered functions
func host start --verbose
# Look for:
# "Found the following functions:"
# If empty, check extensions and attributes
Premium Plan Still Has Cold Start on New Instances
Severity: MEDIUM
Situation: Using Premium plan expecting zero cold start
Symptoms:
Still experiencing cold starts despite Premium plan.
First request to new instance is slow.
Latency spikes during scale-out events.
Pre-warmed instances not being used.
Why this breaks:
Premium plan provides pre-warmed instances, but:
Only one pre-warmed instance by default
Rapid scale-out still creates cold instances
Pre-warmed instances still run YOUR code initialization
Warmup trigger runs, but your code may still be slow
Pre-warmed means the runtime is ready, not your application.