Skip to content

Serverless Computing

Note: This article is written using a view from an Azure perspective.

What Serverless Computing Means

Serverless computing is a cloud execution model in which the platform provisions, runs, scales, and retires compute capacity for an application workload. The name is slightly misleading: servers still exist, but the application team does not select, patch, or keep individual servers alive. The unit of concern becomes code, events, configuration, and outcomes rather than virtual machines.

In Azure, "serverless" is best understood as a collection of managed services that can scale with demand and reduce operational ownership. Azure Functions is the primary function-as-a-service offering, but a production solution commonly combines it with Azure Event Grid, Azure Service Bus, Azure Cosmos DB, Azure Logic Apps, Azure Container Apps, Azure Storage, and Azure Monitor.

The 2017 Visual Studio blog post that introduced many .NET developers to Azure Functions made the still-useful point that serverless is a productivity model: write a small piece of code, bind it to an event, and let the cloud handle infrastructure and scale. Modern Azure broadens that idea with managed identity, private networking, observability, durable workflows, and more deliberate hosting choices. Why you should care about serverless computing

The Azure Serverless Building Blocks

Need Azure service How it fits a serverless design
Run event-driven code Azure Functions Executes a function in response to HTTP requests, timers, queues, blobs, Event Grid events, Service Bus messages, and more.
Route lightweight notifications Azure Event Grid A publish-subscribe event router for state-change notifications, with filtering and push or pull delivery.
Reliably process business commands Azure Service Bus Queue and topic broker with dead-lettering, sessions, transactions, and competing consumers.
Ingest high-volume streams Azure Event Hubs Partitioned event streaming for telemetry, logs, and device data.
Coordinate workflows Durable Functions or Logic Apps Durable Functions is code-first orchestration; Logic Apps is a managed workflow and connector service.
Host a containerized API or worker Azure Container Apps Runs containers with revisions, KEDA-based scaling rules, and scale-to-zero where appropriate.
Store application state Azure Cosmos DB, Azure Storage, Azure SQL Database Managed data services; Cosmos DB change feed is especially useful for event-driven processing.
Secure service-to-service calls Microsoft Entra ID, managed identities, Azure Key Vault Prefer token-based access through managed identities instead of embedded credentials.
Observe the system Application Insights, Azure Monitor, Log Analytics Captures traces, metrics, dependencies, failures, dashboards, and alerting.

The services are complementary, not interchangeable. Event Grid is for distributing facts that something happened; Service Bus is for dependable command and work-queue processing; Event Hubs is for an ordered, high-throughput event stream. Azure's messaging-service comparison is the authoritative decision aid.


A Typical Event-Driven Architecture

An online retailer may upload an order document to Blob Storage. Storage publishes a BlobCreated event, Event Grid routes it, and a Function validates the file and places durable work on Service Bus. Independent consumers then process payment, inventory, and notifications. The uploader does not need to know who consumes the event, and each consumer can scale independently.

flowchart LR
    Client[Client or back-office app] --> API[HTTP-triggered Azure Function]
    API --> DB[(Azure Cosmos DB)]
    API --> SB[Azure Service Bus queue]
    Blob[Azure Blob Storage] -->|BlobCreated| EG[Azure Event Grid]
    EG --> SB
    SB --> Worker[Service Bus-triggered Function]
    Worker --> Ext[Payment or ERP API]
    Worker --> DB
    Worker --> AI[Application Insights]
    API --> AI

This is asynchronous by design. The HTTP endpoint should validate and accept an order quickly, returning 202 Accepted plus an operation or order identifier when the work will complete later. A queue buffers short bursts and isolates a caller from downstream slowness. It does not make processing exactly-once: consumers must assume a message can be retried and make side effects idempotent.

Event notification, command, or stream?

flowchart TD
    Start[What are you moving?] --> Q{Need durable business work\nwith a single successful consumer?}
    Q -->|Yes| SB[Azure Service Bus queue or topic]
    Q -->|No| E{Is it high-volume ordered telemetry\nor a retained event stream?}
    E -->|Yes| EH[Azure Event Hubs]
    E -->|No| EG[Azure Event Grid]

Use Event Grid when a producer announces an occurrence such as Microsoft.Storage.BlobCreated; use Service Bus when a producer asks a worker to do something such as GenerateInvoice; use Event Hubs when many producers append telemetry that several consumers read at their own pace. Azure Event Grid overview and Azure Event Hubs overview explain these distinctions.


Azure Functions: Triggers, Bindings, and Scale

An Azure Function is a named entry point activated by a trigger. Common triggers are HTTP, Timer, Service Bus, Event Grid, Event Hubs, Blob Storage, Azure Queue Storage, Cosmos DB change feed, and Durable Functions orchestration triggers. An Azure Function app is the deployment and configuration boundary that contains one or more functions.

Bindings let a function declare input and output connections to Azure resources. They reduce boilerplate for simple integrations, but they are not a replacement for a domain model or for the Azure SDK when the application needs richer control, batching, retries, or diagnostics.

Hosting choices

For new event-driven function apps, Azure recommends the Flex Consumption plan. It is Linux-based, keeps execution-based billing, supports virtual-network integration, offers configurable memory and concurrency, and can use always-ready instances to reduce cold-start exposure. It also uses per-function scaling for most trigger types. The older Consumption plan is now legacy; it remains relevant for existing Windows workloads but is not the default choice for new applications. Azure Functions hosting options and Flex Consumption guidance

Option Choose it when Key trade-off
Flex Consumption Workload is intermittent or bursty; you want serverless billing, VNet integration, and rapid scale-out. Linux-only; cold-start and regional quota behaviour still need design attention.
Premium plan You need prewarmed instances, more predictable latency, longer-running work, or supported Linux containers. You pay for provisioned capacity rather than only executions.
Dedicated App Service plan Functions share an existing App Service plan or a steady workload already justifies reserved capacity. You manage capacity and autoscale settings more directly.
Functions on Azure Container Apps You need a container image and the Container Apps operational model, revisions, or KEDA scaling. Different deployment and platform characteristics from a standard Function App.
Azure Container Apps You need a long-running HTTP service, background container, or sidecar—not necessarily the Functions programming model. You own the container image and its lifecycle.

Do not choose solely on headline price. Model request duration, memory, concurrency, execution volume, always-ready or prewarmed capacity, dependent-service cost, and the business cost of tail latency. Test a representative cold start and a burst, not only a warm single request.


Practical .NET / C# Example

For new C# function apps, use the .NET isolated worker model. It runs application code in a separate process from the Functions host, giving normal .NET dependency injection, middleware, startup control, and independent .NET versioning. The in-process model reaches end of support on 10 November 2026. C# isolated-worker guide

The following example accepts an order, creates a small command, and sends it to Service Bus. It deliberately does not perform slow downstream work in the request path.

using System.Net;
using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

public sealed class SubmitOrder
{
    private readonly ServiceBusSender _sender;
    private readonly ILogger<SubmitOrder> _logger;

    public SubmitOrder(ServiceBusClient serviceBusClient, ILogger<SubmitOrder> logger)
    {
        _sender = serviceBusClient.CreateSender("order-commands");
        _logger = logger;
    }

    [Function(nameof(SubmitOrder))]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "orders")] HttpRequestData request,
        CancellationToken cancellationToken)
    {
        var order = await request.ReadFromJsonAsync<OrderSubmitted>(cancellationToken);
        if (order is null || order.OrderId == Guid.Empty)
        {
            var badRequest = request.CreateResponse(HttpStatusCode.BadRequest);
            await badRequest.WriteStringAsync("A valid order is required.", cancellationToken);
            return badRequest;
        }

        var message = new ServiceBusMessage(BinaryData.FromObjectAsJson(order))
        {
            MessageId = order.OrderId.ToString(),
            ContentType = "application/json",
            Subject = "OrderSubmitted"
        };

        await _sender.SendMessageAsync(message, cancellationToken);
        _logger.LogInformation("Queued order {OrderId}", order.OrderId);

        var accepted = request.CreateResponse(HttpStatusCode.Accepted);
        await accepted.WriteAsJsonAsync(new { order.OrderId, status = "queued" }, cancellationToken);
        return accepted;
    }
}

public sealed record OrderSubmitted(Guid OrderId, string CustomerId, decimal Total);

Register ServiceBusClient as a singleton through dependency injection and authenticate it with DefaultAzureCredential; in Azure, the Function App's managed identity should receive the least-privileged Service Bus data-plane role. Locally, DefaultAzureCredential can use a developer's Azure CLI or Visual Studio sign-in. Put non-secret configuration in application settings and secrets in Key Vault, rather than committing either to local.settings.json.

Durable Functions for stateful work

Serverless functions are intentionally short-lived and stateless between invocations. A multi-step workflow—approval, payment capture, delivery scheduling, timeout, and compensation—needs durable state and reliable recovery. Durable Functions persists orchestration state and replays deterministic orchestrator code after failures. Keep I/O in activity functions, make orchestrators deterministic, and design activities to be safe on retry.

sequenceDiagram
    participant H as HTTP Function
    participant O as Durable Orchestrator
    participant P as Payment Activity
    participant I as Inventory Activity
    participant N as Notification Activity
    H->>O: Start instance(orderId)
    O->>P: Capture payment
    P-->>O: Payment result
    O->>I: Reserve stock
    I-->>O: Reservation result
    O->>N: Send confirmation
    N-->>O: Complete

Reliability: Design for At-Least-Once Delivery

Most Azure event and message integrations are at-least-once. A function can finish its business operation but lose its acknowledgement before the broker records it, causing redelivery. Duplicates are normal operational input, not an exceptional edge case.

Use these practices:

  • Make consumers idempotent. Store a processed message or business operation key and make repeated delivery a no-op.
  • Use MessageId and Service Bus duplicate detection where it fits, but do not treat broker-level detection as the whole correctness strategy.
  • Set a finite retry policy for transient failures, then dead-letter poison messages with enough context to investigate and replay safely.
  • Keep messages small. Put the payload in durable storage and send an identifier or secure pointer when payloads are large.
  • Use the transactional outbox pattern when a database update and a published event must not diverge.
  • Separate commands from domain events; a command has an intended handler, while an event records a fact and can have multiple subscribers.
  • Treat ordering as an explicit requirement. Service Bus sessions can preserve ordered processing for a chosen session key; partitioned streams and parallel consumers otherwise change ordering guarantees.

For an HTTP-facing function, use a bounded timeout and hand long-running work to a queue or durable orchestration. A function app scaling out cannot compensate for a downstream API that is throttling; apply concurrency limits, backoff, circuit breaking, and back-pressure deliberately.


Security and Operations

Security baseline

  1. Assign a system-assigned or user-assigned managed identity to compute resources; grant Azure RBAC roles to that identity instead of copying connection strings.
  2. Use Microsoft Entra ID authentication for service-to-service access where supported. Use Key Vault for the limited secrets that cannot be removed.
  3. Place private dependencies behind private endpoints where required, and use Function App virtual-network integration for outbound private access. Validate DNS and data exfiltration paths as part of the design.
  4. Keep HTTP endpoints behind the appropriate authentication and authorization boundary—such as API Management, Entra ID, or an application-specific policy. A function key is not a general-purpose end-user identity system.
  5. Use separate identities, topics, queues, resource groups, and subscriptions to keep business domains and blast radii clear.

Observability baseline

Use Application Insights with distributed tracing from the ingress request through queue producers and consumers. Log structured properties such as OrderId, MessageId, CorrelationId, FunctionName, and outcome; do not log secrets or unnecessary personal data. Alert on failed invocations, dead-letter count, retry exhaustion, dependency duration, saturation/concurrency, and business-level lag—not merely CPU.

The most useful dashboard answers: What is waiting? How old is it? Is it failing or being retried? Which dependency is slow? Can an operator identify and safely replay a failed unit of work?


Advantages and Disadvantages

Advantages

  • Reduced operational work: Azure owns host patching, baseline availability, and much of capacity management.
  • Elasticity: Trigger-driven scaling can absorb irregular demand without permanently running peak infrastructure.
  • Fast integration: Bindings, managed messaging, and event routing make it practical to connect managed services.
  • Cost alignment for intermittent work: Execution-based plans can be economical when idle periods are real and frequent.
  • Smaller deployment units: A focused function can be deployed and evolved independently when boundaries are well chosen.

Disadvantages and constraints

  • Cold starts and latency variance: Scale-to-zero is valuable but can conflict with strict first-request latency requirements.
  • Distributed-systems complexity: Retries, duplicates, eventual consistency, ordering, and partial failure do not disappear.
  • Cost can be less obvious: High invocation volume, chatty designs, observability ingestion, networking, and dependent services can exceed a simple always-on host.
  • Execution and platform limits: Timeouts, connection limits, quotas, memory choices, and networking features vary by plan and region.
  • Debugging is asynchronous: A request may traverse several services and complete much later, so correlation and operational tooling are mandatory.
  • Vendor coupling: Triggers, bindings, identity models, and managed integrations accelerate delivery but require an intentional portability strategy.

Serverless Compared with Alternatives

Approach Best fit Prefer it over serverless when
Azure Functions Discrete event handlers, webhooks, scheduled jobs, background processing, integration glue. The unit of work is naturally event-triggered and can scale independently.
Azure Container Apps Containerized APIs, workers, and microservices with scale rules and revisions. You need a continuously running process, custom runtime, sidecar, or container-level control.
Azure App Service Conventional web apps and APIs with predictable, steady traffic. You want simple web hosting and a stable always-on capacity model.
AKS Complex multi-service platforms requiring Kubernetes APIs and deep scheduling/networking control. You genuinely need Kubernetes control-plane capabilities and can operate them.
Virtual machines Legacy software, unusual OS dependencies, or specialized long-running host control. The workload cannot fit managed platform constraints.
Logic Apps Connector-heavy business process automation and low-code integration. Visual workflow, governance, and SaaS connectors matter more than code-first domain logic.

Serverless is therefore not a synonym for "small" or "cheap." It is a good fit when event-driven scale and managed operations materially simplify the workload. A steady API with high baseline utilization may be simpler and more economical on App Service or Container Apps; a deeply stateful transactional core may keep its synchronous path in an API and use serverless only for asynchronous edges.


Practical Design Checklist

Before approving an Azure serverless design, confirm the following:

  • What trigger starts each operation, and is the work request, event, or stream clearly classified?
  • What is the delivery guarantee, retry policy, dead-letter process, and replay procedure?
  • Is every externally visible side effect idempotent?
  • What is the maximum acceptable cold-start and end-to-end latency under burst load?
  • Which hosting plan, memory size, concurrency level, networking mode, and quota model apply?
  • How does the workload authenticate with managed identity, and what are the minimal RBAC assignments?
  • What correlation identifier crosses HTTP, storage, Event Grid, Service Bus, and Functions?
  • How are schema versions introduced, validated, and retired?
  • What data is durable, what can be recomputed, and how are retention and recovery handled?
  • Which failures require an automated retry, a compensation workflow, or an operator decision?

Interview-Ready Summary

Serverless computing moves server provisioning and elastic scaling to the cloud platform so teams focus on event-driven code and managed services. In Azure, Azure Functions is the common compute primitive; Event Grid routes notifications, Service Bus handles durable business messaging, Event Hubs carries high-volume streams, and Durable Functions coordinates reliable long-running workflows.

For a new Azure Functions workload, start by evaluating Flex Consumption, then validate latency, networking, concurrency, and cost against real traffic. For new C# development, use the .NET isolated worker model. Production quality comes from the surrounding engineering: managed identities, least-privilege RBAC, idempotent consumers, explicit retries and dead-letter handling, distributed tracing, and a clear operational replay path.


Further Reading