AzureIntermediate

Azure Functions v4: The Complete Guide to Serverless Computing

DevHub Team
7 min read

TL;DR

Master Azure Functions v4 with this comprehensive guide covering new features, performance improvements, and best practices for serverless development

Azure Functions v4: The Complete Guide to Serverless Computing

Executive Summary

Azure Functions v4 is the current generation of Microsoft's serverless compute service. It runs event-driven code on triggers such as HTTP requests, timers, queues, and storage events, and it bills for execution rather than for idle servers. This guide covers the v4 programming model, hosting plan selection, security with managed identity and Key Vault, and observability with Application Insights. After reading it, you should be able to structure a production function app in the .NET isolated worker model, choose a hosting plan based on cold start and timeout requirements, and recognise the workloads that belong on a different service.

Why This Matters

Serverless removes server management, not architectural responsibility. Choosing the wrong hosting plan shows up as cold start latency on user-facing endpoints, executions killed by plan timeout limits, or a bill driven by a chatty trigger polling an empty queue. Treating function keys as your only security control leaves HTTP endpoints effectively public. Teams also underestimate the operational shift: a function app is a distributed system of triggers, bindings, and external stores, and it fails in distributed ways. Getting the model, plan, and security posture right at the start is far cheaper than retrofitting them after an incident or a surprise invoice.

Core Concepts

The v4 Programming Model

Version 4 standardised the programming model across languages. For .NET, the recommended approach is the isolated worker model: your code runs in a separate process from the host, you reference the worker SDK, and functions are declared with the Function attribute. This decouples your app from the runtime version and lets you use current .NET releases and full middleware support.

public class HttpExample
{
    private readonly ILogger<HttpExample> _logger;

    public HttpExample(ILogger<HttpExample> logger)
    {
        _logger = logger;
    }

    [Function("HttpExample")]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
    {
        _logger.LogInformation("C# HTTP trigger function processed a request.");

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

        await response.WriteStringAsync("Welcome to Azure Functions v4!");

        return response;
    }
}

Triggers, Bindings, and Dependency Injection

Every function has exactly one trigger; input and output bindings connect it to services such as Blob Storage, queues, Cosmos DB, and Event Hubs without hand-written plumbing code. Because the isolated worker is a standard .NET host, services are registered in Program.cs and injected through constructors, which keeps functions testable:

public class TimerExample
{
    private readonly IMyService _myService;
    private readonly ILogger<TimerExample> _logger;

    public TimerExample(IMyService myService, ILogger<TimerExample> logger)
    {
        _myService = myService;
        _logger = logger;
    }

    [Function("TimerExample")]
    public async Task Run(
        [TimerTrigger("0 */5 * * * *")] TimerInfo timer)
    {
        _logger.LogInformation($"Timer trigger executed at: {DateTime.Now}");
        await _myService.ProcessDataAsync();
    }
}

Design rules that hold up in production: keep functions small and single-purpose, make handlers idempotent because triggers such as queues deliver at least once, and push durable state into external stores rather than local variables or the local file system.

Hosting Plans and Cold Starts

The hosting plan is the most consequential decision in a Functions design. The Consumption plan scales to zero and bills per execution, but instances that scale to zero must cold start on the next request, and execution time is capped. The Premium plan keeps pre-warmed instances ready, removes the cold start problem for most workloads, supports VNET integration, and allows longer executions, at a standing cost. Dedicated (App Service) plans run your functions on reserved VMs and make sense when you already have underused App Service capacity. Durable Functions builds orchestrations, fan-out/fan-in, and long-running workflows on top of the same model when a single short execution is not enough.

Security

HTTP triggers support authorization levels (anonymous, function, admin). Function and admin keys are a coarse control, not an identity system: for production HTTP endpoints, put authentication in front of the app with Microsoft Entra ID through App Service Authentication, or validate tokens in middleware. Give the function app a managed identity and grant that identity access to the resources it needs, so no connection strings or passwords live in configuration. Where secrets are unavoidable, store them in Azure Key Vault and reference them from app settings rather than pasting values in. VNET integration (Premium or Dedicated) plus private endpoints keeps traffic to storage and databases off the public internet.

Observability and Deployment

Connect the app to Application Insights from day one. You get invocation counts, failure rates, durations, and dependency tracking, and you can trace a request across functions and downstream services. Configure sampling deliberately: unsampled telemetry on a high-volume app is a cost problem, while aggressive sampling hides rare failures. Deploy with CI/CD rather than portal edits; a typical GitHub Actions pipeline builds, publishes, and deploys the app:

name: Deploy Function App
on:
  push:
    branches: [ main ]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4

    - name: Setup .NET
      uses: actions/setup-dotnet@v4
      with:
        dotnet-version: '8.0.x'

    - name: Build
      run: |
        dotnet restore
        dotnet build --configuration Release
        dotnet publish -c Release -o ./publish

    - name: Deploy
      uses: Azure/functions-action@v1
      with:
        app-name: ${{ secrets.AZURE_FUNCTIONAPP_NAME }}
        package: './publish'
        publish-profile: ${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }}

Decision Framework

SituationRecommendation
Sporadic, event-driven work with idle gapsConsumption plan; accept cold starts
User-facing HTTP APIs sensitive to latencyPremium plan with pre-warmed instances
Workflows that wait on external events or run in stepsDurable Functions
Steady, predictable, high-volume loadPrice it against App Service or Container Apps; per-execution billing may lose
Function needs VNET access to private resourcesPremium or Dedicated plan
Runtime or library the built-in workers do not supportCustom handler, or a containerised app instead

Implementation Checklist

  • [ ] Function app uses the isolated worker model with services registered in Program.cs
  • [ ] Every handler is idempotent and safe under at-least-once delivery
  • [ ] Hosting plan chosen explicitly, with cold start and timeout behaviour accepted in writing
  • [ ] Managed identity enabled and granted least-privilege roles on downstream resources
  • [ ] Secrets held in Key Vault and referenced from app settings, never committed or pasted in plain text
  • [ ] Production HTTP endpoints authenticated with Entra ID, not function keys alone
  • [ ] Application Insights connected, sampling configured, and alerts set on failures and throttling
  • [ ] Deployment runs through CI/CD with a staging slot or equivalent rollback path
  • [ ] Retry and poison-message handling configured for queue and event triggers
  • Trade-offs

    Functions trades control for convenience. You give up control over the host, the scaling mechanics, and (on Consumption) execution duration. Cold starts are inherent to scale-to-zero economics. Bindings reduce boilerplate but couple your code to Azure-specific abstractions, which makes later migration a rewrite rather than a recompile. Debugging is harder than in a monolith: a single business transaction may span several functions, queues, and stores, so correlation through telemetry is not optional. Finally, per-execution pricing is excellent at low and spiky volumes and can quietly exceed the cost of reserved compute at sustained volume.

    When Not to Use

  • Long-running batch or ETL jobs: use Azure Batch, Container Apps jobs, or a data platform instead of fighting execution time limits.
  • Sustained high-throughput APIs: App Service or Azure Container Apps on reserved capacity is usually cheaper and more predictable.
  • Ultra-low-latency or streaming workloads: a long-lived service on AKS or Container Apps fits better than per-invocation compute.
  • Complex stateful processes with strict transactional needs: a conventional service with a database transaction boundary is simpler to reason about than orchestrated functions.
  • Conclusion

    Azure Functions v4 is a strong default for event-driven, spiky, and glue workloads, provided you choose the hosting plan deliberately and treat security and observability as design inputs, not afterthoughts. Use the isolated worker model, managed identity, and Application Insights from the start. When the workload becomes steady, long-running, or latency-critical, move it to a service built for that shape rather than forcing Functions to be one.

    References

  • Azure Functions Documentation
  • .NET 6 Documentation
  • Azure Functions Best Practices
  • Performance Considerations
  • Security Guidelines
  • Monitoring and Diagnostics
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.