AlgoViz

Azure Functions

medium 31 min

Azure Functions runs small pieces of code when something happens: a request, a message, a timer, a stored file.

Video lesson · Chapter 1 of 5

A customer gets a receipt before the order finishes

0:00 / 4:14

Azure Functions in 85 seconds

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A function as a service runs your code on demand and looks after the machines. Azure Functions is Microsoft's. The unit you deploy is a function app: one project with one or more functions that share settings and a plan. Each function has exactly one trigger, the event that starts it.

Two things set it apart from AWS Lambda and Cloud Run functions. Bindings declare inputs and outputs, so that the platform reads a document or writes a message for you. And Durable Functions lets one function coordinate others over minutes or months, with its progress stored.

Why it exists

Glue code is everywhere: resize, validate, notify, import. It is small, uneven, and needs a connection to a queue or a database. A function with bindings is a few lines, and it costs nothing in computing while idle on a plan that goes to zero.

Processes with several steps are harder: pay, then reserve, then ship, with retries and a wait for a person. Writing the state by hand in tables and queues is slow and easy to get wrong. Durable Functions keeps the state and lets the code read from top to bottom.

A short history

  1. 2016, March

    Microsoft presents Azure Functions on 31 March.

  2. 2016, November

    General availability is announced on 15 November.

  3. 2024, November

    The Flex Consumption plan becomes generally available on 19 November: scale to zero together with private networks, a choice of memory and always-ready instances.

  4. 2026, September

    Support for runtime version 1.x ends on 14 September. Only version 4.x is supported.

  5. 2026, November

    Support for the .NET in-process model ends on 10 November. C# functions use the isolated worker model.

  6. 2028, September

    Announced: the Linux option of the old Consumption plan retires on 30 September 2028.

Words to know

Function app
The unit you deploy and configure: functions that share settings, identity and a plan.
Trigger
What starts a function. Each function has exactly one.
Binding
A declared connection that reads input or writes output for you.
Host
The Functions runtime in an instance. Your language runs in a worker process beside it.
Plan
Where it runs: Flex Consumption, Premium, Dedicated, Container Apps, or the older Consumption.
Orchestrator
A durable function that says which steps follow which. It is replayed, so it must be deterministic.
Activity
A durable function that does one real step, such as charging a card.
Poison message
A message that fails every time.

How it works

Step through the idea, or press Play.

Step 1 of 3

Trigger. A request, message, timer or file

Understand it

Start here

A shelf of music boxes

Picture a shelf with music boxes. Each has its own key, and only that key starts it. A box knows one tune.

One key, one tune

The boxes remember nothing. The notebook does.

The model

Triggers and bindings

TriggerStarts whenTypical use
HTTPA request arrivesAPI, webhook
TimerA schedule of six fields, seconds firstClean-up, reports
Queue StorageA message is in a storage queueSimple background work
Service BusA message in a queue or topicOrders, sessions, dead letters
Event Hubs, KafkaBatches from a streamTelemetry
Blob Storage, through Event GridA file is storedPictures, imports
Cosmos DBDocuments changeKeep a second view up to date
Event GridAn event from many Azure servicesReact to changes
One trigger per function. Bindings may be many: for example an HTTP trigger with a queue output.
Python
import jsonimport azure.functions as funcapp = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)@app.route(route="orders", methods=["POST"])@app.queue_output(arg_name="msg", queue_name="orders", connection="OrdersStorage")def accept(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:    order = req.get_json()    msg.set(json.dumps(order))                     # the binding sends it    return func.HttpResponse(status_code=202)@app.queue_trigger(arg_name="msg", queue_name="orders", connection="OrdersStorage")def work(msg: func.QueueMessage) -> None:    order = json.loads(msg.get_body())    print("order", order["id"], "try", msg.dequeue_count)
Two functions in one app. The connection name points to settings, which can use a managed identity instead of a secret.

Accept fast, work later

Users send orders to a function app on Azure. The accept function writes a message to a storage queue. The work function is started by the queue and writes to Cosmos DB. Messages that fail five times go to a poison queue.
The accept function answers 202 at once. The queue absorbs the peak.

Plans

Where it runs decides how it scales

Hosting plans

PlanZero?Most instancesTime limit: default, mostChoose it when
Flex ConsumptionYes100 by default, up to 1,00030 min, unboundedThe default choice for new serverless apps
PremiumNo, at least one20 to 10030 min, unboundedNearly always busy; no cold start wanted
Dedicated (App Service)No10 to 3030 min, unbounded with Always OnSpare capacity on existing machines
Container AppsYes300 to 1,00030 min, unboundedOwn container, next to other containers
Consumption (legacy)Yes200 on Windows, 100 on Linux5 min, 10 minOnly Windows needs; move otherwise
Unbounded does not mean safe: scale-in and updates give running work a limited grace period, for example 60 minutes at scale-in on Flex Consumption and Premium.

Which plan?

Long work

The 230-second rule

Answer now, work later

The durable client builds the status addresses for you. Nothing waits inside the HTTP function.

Scale

How instances are added

A scale controller watches each trigger. For queues and streams it uses target-based scaling: the backlog divided by how much one instance should hold. On Flex Consumption each function scales on its own, except that HTTP functions form one group, Event Grid blob functions another, and durable functions a third. On the other plans the whole app scales together.

Target-based scaling

n=⌈messages waitingtarget per instance⌉⌈120024⌉=50n = \left\lceil \frac{\text{messages waiting}}{\text{target per instance}} \right\rceil \qquad \left\lceil \frac{1200}{24} \right\rceil = 50
Example for a storage queue: an instance with one vCPU takes batches of 16 and fetches more when 8 are left, so it works on up to 24. 1,200 waiting messages ask for 50 instances. If your database takes 10 workers, lower the batch or the instance limit.

HTTP instances on Flex Consumption

n=⌈r×tc⌉c=16: ⌈600×0.216⌉=8c=1: 120n = \left\lceil \frac{r \times t}{c} \right\rceil \qquad c = 16:\ \left\lceil \tfrac{600 \times 0.2}{16} \right\rceil = 8 \qquad c = 1:\ 120
Assumptions: 200 requests per second on average, peak 3x so r = 600, t = 0.2 s. The default is 16 at once for 2,048 MB, but 1 for Python, whatever the size. 120 passes the default limit of 100 instances, so set the Python value on purpose.

Four settings to know

  • Instance memory

    512, 2,048 or 4,096 MB on Flex Consumption. Default HTTP concurrency is 4, 16 and 32.

  • Always-ready instances

    Kept warm per scale group. They do not count towards the maximum.

  • Maximum instances

    Counted per scale group, not for the whole app. Protects the systems behind.

  • Concurrency

    Fixed per trigger by default. Dynamic concurrency can tune some triggers if you turn it on.

Errors

Retries and poison messages

A storage queue message that fails

The default wait between tries is zero. Set visibilityTimeout so that a short outage does not use up all five tries in a second.

Who retries?

TriggerRetried byWhen it gives up
HTTPNobody: the caller decidesThe caller sees the error
Queue StorageThe queue, 5 tries by defaultCopy in the poison queue
Service BusThe queue's own rulesDead-letter queue
Event Hubs, Kafka, Cosmos DB, TimerA retry policy that you set on the functionEvent Hubs: the position moves on and the batch is gone
Event GridThe event subscriptionDead-letter storage, if set
In every case a function can run twice for one event. Make it safe to repeat; see idempotency.

Durable

Long processes as code

Durable Functions has three roles. A client starts a flow. An orchestrator says what happens in which order. Activities do the work. The runtime saves a history event for each step. When a step finishes, the orchestrator runs again from the top, but steps that are in the history return their saved result at once. This is called replay.

One flow, three activities

A client function starts an orchestrator. The orchestrator calls the activities reserve, charge and ship, and keeps its history in a durable store.
The orchestrator holds no state of its own. The store holds the history.

Replay after a crash

An activity runs at least once. If it finished but the result was not saved, it runs again, so use a key such as the order number.

Six patterns

PatternShapeExample
ChainingOne after anotherReserve, charge, ship
Fan-out and fan-inMany at once, then combineResize 100 pictures; see fan-out, fan-in
Async HTTPAnswer 202 and a status addressA long export
MonitorLook, wait, look againUntil a job is finished
Human interactionWait for an event or a time limitApproval within three days
AggregatorAn entity that collectsA counter per device

In an orchestrator, do

  • Use the context's clock and new IDs
  • Call activities for every network or disk access
  • Use durable timers to wait
  • Start a fresh history with continue-as-new in endless loops

In an orchestrator, never

  • Read the real clock or a random number
  • Call an API or a database directly
  • Sleep in a thread or start threads of your own
  • Read settings that may change between replays

The state lives in a storage provider. Microsoft recommends the managed Durable Task Scheduler; Azure Storage and SQL Server are the ones you bring yourself. The pattern behind compensation, undoing step one when step two fails, is the saga.

Operate

Security, releases and cost

Before production

  1. 1

    Who may call

    Function keys are a light barrier. For real protection put authentication in front, with Microsoft Entra ID or API Management.

  2. 2

    What it may do

    A managed identity with few rights, also for the bindings. Secrets belong in Key Vault.

  3. 3

    Network

    Flex Consumption, Premium and Dedicated can join a virtual network.

  4. 4

    Storage account

    The host needs one for its own work. Give each app its own, or a busy neighbour slows you.

  5. 5

    Releases

    Deployment slots on Premium and Dedicated. Flex Consumption has no slots; rolling updates are in preview there.

  6. 6

    Watching

    Application Insights: failures, run time, queue age, poison queue length, instance count.

Cost. On Flex Consumption you pay for running time by memory size and for the number of runs, and for always-ready instances while they wait. Premium and Dedicated are billed by the instance, busy or not. Storage, Application Insights and outgoing traffic are separate, and logs are often a surprise: sample them. The runtime itself is open source under the MIT licence, so it also runs in your own container.

Failure

What happens if

FailureResultPrepare
An instance dies during a runQueue message comes back after its hidden time (10 minutes if the host itself died)Repeatable work
The database slowsMore instances make it worseLimit instances and concurrency
A poison messageFive tries, then asideAlert on the poison queue
The host's storage is unreachableTriggers and keys stop workingOwn account, right redundancy
A Region is lostThe app is goneA second app, and a plan for the data

Decide

When to choose it, and when not

Choose Azure Functions

  • Work that reacts to Azure services
  • Uneven load
  • Processes with steps, written as code
  • C#, Python, Java, JavaScript, PowerShell or Go teams
  • Small APIs and webhooks

Choose something else

  • Steady heavy traffic: containers
  • Hours of computing: Azure Batch or container jobs
  • A flow drawn by non-programmers: Logic Apps
  • Very short, very near the user: an edge platform
  • No Azure in sight

Neighbours

OptionSameDifferentChoose it when
AWS LambdaFunction per eventStep Functions for flows, no bindingsOn AWS
Cloud Run functionsFunction per eventA container service underneathOn Google Cloud
Logic AppsSteps and connectorsDesigned in a picture, little codeConnecting business systems
Azure Container AppsScale to zeroAny container, long-running servicesWhole services
Task schedulersRun work laterYou build and run itSpecial rules

Summary

The whole topic in one minute.

A function app holds functions, each with one trigger and any bindings. The plan decides scale: Flex Consumption is the recommended serverless plan, and Premium keeps copies warm. Events are retried by the trigger's own rules, and messages that keep failing end in a poison queue.

Durable Functions stores each finished step and replays the orchestrator to continue. Keep orchestrators deterministic and activities safe to repeat, and use it when steps depend on each other or take long.

  • One trigger per function; bindings move data without client code.
  • Flex Consumption is the default; Premium stays warm; the old Consumption plan is legacy.
  • HTTP answers within 230 seconds, whatever the plan.
  • Queue messages get five tries, with no wait by default, then go to the poison queue.
  • Orchestrators are replayed and must be deterministic; activities run at least once.
  • Python on Flex Consumption serves one HTTP request per instance unless you change it.

Sources