Cloud PlatformsComplete guide

Azure Functions & Serverless

Azure Functions runs event-driven code on managed, elastic compute and integrates .NET handlers with HTTP, schedules, queues, streams, storage, and other services.

Overview

A function app groups functions that share deployment, configuration, scaling, and hosting. Triggers start executions and bindings integrate data, while the .NET isolated worker uses the standard hosting and dependency-injection model outside the Functions host process. Hosting plan, scale behavior, cold starts, concurrency, retries, poison handling, idempotency, networking, identity, observability, package deployment, and execution duration all affect whether a serverless design meets its workload goals.

What you will learn

  • Explain function apps, triggers, bindings, isolated workers, hosting plans, scale, and deployment units.
  • Design reliable queue, stream, HTTP, timer, and durable workflow handlers.
  • Implement durable idempotency, retries, poison routing, cancellation, and correlation.
  • Tune batching, concurrency, connection reuse, and instance scale against dependencies.
  • Secure host storage, identities, endpoints, settings, packages, and networks.
  • Test and operate cold starts, replays, deployments, outages, recovery, and cost.

Prerequisites

  • C# async programming, dependency injection, configuration, and structured logging.
  • Queues, streams, HTTP, retries, idempotency, and distributed-system failure basics.
  • Azure Functions Core Tools and Azurite for the local sample; Azure is optional.

When to use Azure Functions & Serverless

Good fit

  • Work starts from HTTP, schedules, queues, streams, storage, or other events and benefits from managed elastic execution.
  • Handlers can be stateless between invocations or coordinate through durable external state.
  • The selected plan meets latency, networking, availability, duration, scale, and cost needs.

Choose another approach when

  • A continuously running service, unsupported protocol, specialized compute, or deep host control is required.
  • Predictable steady load is more economical and operationally clearer on another compute service.
  • The workload cannot tolerate the available cold-start, regional, networking, quota, or execution constraints.

Key concepts

Function app boundary

Functions in one app deploy, configure, secure, and usually scale together; group only handlers with compatible lifecycle, risk, and load.

Triggers and bindings

One trigger starts an invocation; bindings simplify supported data flow, while SDK clients are clearer for advanced transactions, batching, and control.

Isolated worker model

The .NET worker runs separately from the host and supports modern .NET, dependency injection, middleware, configuration, logging, and testable handler services.

Hosting plans

Flex Consumption, Premium, Dedicated, and container hosting differ in cold start, networking, scale, duration, availability, instance size, and price.

At-least-once processing

Queue and stream events may repeat after retries, locks, crashes, or checkpoint behavior, so durable idempotency and poison handling are mandatory.

Concurrency and scale

Trigger concurrency, batching, prefetch, instance scale, connections, and downstream capacity interact; higher parallelism can reduce reliability.

Durable workflows

Durable Functions persists orchestration history for timers, fan-out, compensation, and human interaction; orchestrator code must remain deterministic.

Operations and delivery

Package deployment, slots or rolling updates, host storage, telemetry, alerts, quotas, replay, and disaster recovery define production behavior.

Architecture

Events enter through Functions triggers, isolated .NET workers execute stateless handlers and call managed dependencies, while durable state, retries, and telemetry support reliable scale.

HTTP + events
Functions trigger
Isolated .NET worker
Services + telemetry

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The isolated order processor is a real .NET 10 Functions worker with a queue trigger, a host-independent processor, validated events, atomic idempotency receipts, bounded queue retries, poison routing, cancellation, structured logs, and local tests.

  1. 01
    Define event contracts

    Version schemas, choose stable event and correlation IDs, document ordering, retention, maximum size, and compatibility.

  2. 02
    Choose the app boundary

    Group functions by deployment, security, configuration, scaling, availability, and dependency profile.

  3. 03
    Create the isolated worker

    Pin runtime, worker SDK, and extensions; register services and keep trigger methods as thin adapters.

  4. 04
    Make effects idempotent

    Use a durable conditional write or state transition keyed by event ID in the same consistency boundary as the effect.

  5. 05
    Configure delivery behavior

    Set retry, backoff, lock or visibility, poison destination, timeout, cancellation, batching, and concurrency coherently.

  6. 06
    Secure connections

    Use managed identity and least privilege where supported; protect required host storage and remove public endpoints when justified.

  7. 07
    Instrument outcomes

    Correlate invocation, event, retry, dependency, business result, poison routing, lag, and cold-start signals.

  8. 08
    Deploy and prove

    Publish one immutable package, validate settings and infrastructure, load test, inject failures, rehearse replay, and verify regional recovery.

Code example

An isolated-worker HTTP function uses constructor injection, structured logging, cancellation, and an explicit response contract.

CreateOrderFunction.cs
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System.Net;

public sealed class CreateOrderFunction(
    OrderService orders, ILogger<CreateOrderFunction> logger)
{
    [Function(nameof(CreateOrder))]
    public async Task<HttpResponseData> CreateOrder(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "orders")]
        HttpRequestData request, CancellationToken ct)
    {
        var command = await request.ReadFromJsonAsync<CreateOrder>(ct);
        var orderId = await orders.CreateAsync(command!, ct);

        logger.LogInformation("Created order {OrderId}", orderId);
        var response = request.CreateResponse(HttpStatusCode.Created);
        await response.WriteAsJsonAsync(new { orderId }, ct);
        return response;
    }
}

Testing strategy

Separate fast domain tests from worker adapter, trigger integration, deployed platform, load, and recovery evidence.

  • Unit test handlers, validation, idempotency, retry classification, and cancellation without the Functions host.
  • Run worker integration tests with representative serialized events and local services.
  • Use isolated Azure resources to verify authoritative trigger, binding, identity, lock, retry, and poison semantics.
  • Load test cold and warm starts, batching, concurrency, instance scale, and downstream saturation.
  • Crash after the side effect and before acknowledgement to prove duplicate safety.
  • Deploy a package, validate telemetry and settings, replay poison events, and execute recovery procedures.

Security considerations

Secure each function endpoint, workload identity, host storage, binding connection, deployment package, network path, and telemetry stream.

  • Use managed identity and least-privilege data-plane roles where triggers and SDKs support it.
  • Protect the mandatory host storage account and understand its availability dependency.
  • Require appropriate HTTP authentication and authorization; never rely only on obscurity of a function key.
  • Keep secrets out of local settings, packages, logs, and source; rotate unavoidable credentials.
  • Restrict inbound and outbound networking with a complete DNS and dependency design.
  • Scan and pin worker, extensions, packages, and deployment artifacts.

Performance and scalability

Useful throughput depends on the complete trigger-to-dependency path, not invocation count alone.

  • Use async I/O and reuse SDK, HTTP, database, and messaging clients.
  • Tune batch, prefetch, and concurrency from downstream capacity and lock duration.
  • Measure event age, lag, useful completions, retries, throttles, connections, and percentile latency.
  • Use always-ready or Premium capacity when measured cold-start latency violates objectives.
  • Avoid large payloads; pass durable references when event size and repeated transfer are costly.
  • Set maximum scale and application backpressure before dependencies collapse.

Deployment and operations

The function app is the deployment unit; ship all its functions as one immutable, observable package.

  • Build, test, audit, and publish a run-from-package artifact.
  • Provision plan, app, host storage, identity, settings, networking, alerts, and dependencies through code.
  • Use federated deployment identity and keep application data access separate.
  • Use supported slots or Flex rolling updates and understand trigger behavior during overlap.
  • Run HTTP and event smoke tests, verify telemetry, and watch retry and poison signals.
  • Prefer forward repair; replay only after the defect is fixed and idempotency is proven.

Common problems and fixes

Function is not discovered

Likely cause: Worker SDK generation, target framework, Function attribute, extension, or deployment output is incorrect.

Fix: Inspect generated metadata and startup logs, pin compatible packages, clean and rebuild, and verify the deployed package layout.

Queue message repeats forever

Likely cause: The handler throws, exceeds visibility, loses a lock, crashes after an effect, or poison handling is absent.

Fix: Inspect delivery count and duration, fix idempotency, align timeout and visibility, bound retries, and monitor poison routing.

Scaling rises but event age grows

Likely cause: Per-instance concurrency or a downstream limit is reducing useful throughput.

Fix: Graph age, completions, retries, throttles, connections, and instances; reduce concurrency or increase the actual bottleneck safely.

Works locally but trigger is idle in Azure

Likely cause: Connection configuration, identity RBAC, network path, extension settings, or source name differs.

Fix: Check host logs, exact setting names, token audience, role scope, DNS, firewall, and trigger source configuration.

Telemetry is missing or duplicated

Likely cause: Host and worker pipelines, sampling, exporter configuration, or correlation propagation conflict.

Fix: Configure host and worker logging deliberately, retain errors, verify sampling, and trace one event end to end.

Deployment processes mixed versions

Likely cause: Old and new instances or slots consume the same trigger during rollout.

Fix: Design compatible schemas and idempotency, understand plan deployment behavior, and isolate consumers when strict version ownership is required.

Best practices

  • Use the .NET isolated worker and supported runtime and extension versions for new C# apps.
  • Keep functions thin and move business logic into host-independent services.
  • Make every event-driven side effect idempotent with a durable atomic receipt or state transition.
  • Configure bounded retries, visibility or lock duration, poison handling, timeout, and cancellation together.
  • Choose hosting from measured latency, networking, availability, duration, scale, and cost requirements.
  • Reuse clients and bound trigger concurrency to downstream capacity and connection limits.
  • Deploy immutable packages with infrastructure as code and production-shaped integration tests.
  • Alert on failures, retries, poison events, age or lag, saturation, cold starts, host health, and cost.

Production checklist

  • Function app boundaries match deployment, scale, security, availability, and dependency profiles.
  • Runtime, worker SDK, extensions, and hosting plan are supported and pinned.
  • Event contracts, idempotency, retries, poison routing, timeouts, cancellation, and correlation are tested.
  • Managed identity, host storage, endpoint authorization, secrets, network, and RBAC are verified.
  • Batching, concurrency, connections, maximum scale, and always-ready capacity come from load tests.
  • Immutable deployment and infrastructure automation include smoke and telemetry gates.
  • Alerts cover failures, retries, poison events, age, lag, cold starts, saturation, host health, and cost.
  • Replay, rollback or forward repair, backup, restore, and regional recovery are rehearsed.

Common interview questions

Why prefer isolated worker for new .NET functions?

It decouples the application process from the Functions host and provides modern framework targeting, dependency injection, middleware, configuration, and worker lifecycle control.

Why is exactly-once processing not assumed?

A crash after a side effect but before acknowledgement causes delivery to repeat; distributed acknowledgement and business state are not one atomic transaction.

How should functions be grouped into apps?

Group handlers that share deployment, configuration, scale profile, security boundary, availability needs, and blast radius; split conflicting workloads.

Flex Consumption versus Premium?

Flex targets dynamic scale with configurable memory, per-function scaling, networking, and always-ready options; Premium provides prewarmed instances and dedicated plan capacity for demanding workloads.

When use Durable Functions?

For stateful coordination such as fan-out, long timers, external events, and compensation where persisted orchestration and replay semantics fit.

Why can more concurrency make throughput worse?

It can exhaust connections, trigger throttling, extend lock times, amplify retries, and overload databases or APIs until useful throughput falls.

When is Functions the wrong choice?

When execution is a continuously running service, requires unsupported host control or protocols, has predictable steady economics elsewhere, or cannot fit hosting, duration, or networking constraints.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Functions Isolated Order Processor

A .NET 10 isolated-worker queue function with host-independent processing, event validation, idempotency receipts, bounded retries, poison routing, cancellation, and focused tests.

.NET 10Azure FunctionsIsolated WorkerAzure Queue Storage
dedicated-sampleserverlessidempotencypoison-queue
Run
func start --script-root src/FunctionsIsolatedOrderProcessor
Test
dotnet test FunctionsIsolatedOrderProcessor.slnx