Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 57 ยท Compute

Azure Functions

Learn Azure Functions: triggers and bindings, HTTP, timer and queue functions, hosting plans, cold starts and a short overview of Durable Functions.

Some code only needs to run when something happens: a request arrives, a file is uploaded, a message lands in a queue, or the clock strikes five. Keeping a server running around the clock for that is wasteful. Azure Functions is Azure's serverless compute service for these small, event-driven pieces. You write a function, say what event starts it, and Azure runs it on demand, scales it with the number of events, and (on the consumption-style plans) bills you for what you use.

The two ideas that make Functions different from a plain web app are triggers (what starts a function) and bindings (declarative connections to data, so you rarely write storage or queue client code). This lesson explains both, shows HTTP, timer and queue functions, compares hosting plans, explains cold starts, and introduces Durable Functions. The real runtime needs an Azure account or the Functions Core Tools, so the function code is read-only. The runnable examples are Node.js stand-ins that dispatch events to functions the way the host does.

Triggers and bindings

Every function has exactly one trigger. The trigger defines the event and passes the event data to your code. Common triggers:

Trigger Starts when
HTTP A web request arrives
Timer A schedule fires
Queue Storage / Service Bus A message arrives in a queue or topic
Blob A blob is created or updated
Event Hubs / Event Grid Events arrive from a stream or topic
Cosmos DB Documents change in a container

Bindings are optional extra connections. An input binding hands your function data (a row, a blob's content) before it runs. An output binding takes the value you return or set and writes it somewhere (a queue message, a document) after it runs. The connection details live in app settings, not in code (see App Service and Web Apps, because Functions uses the same settings mechanism).

The value: a function that reads a queue message and writes a blob is a few lines, with no SDK setup, no connection handling and no retry code of your own.

An HTTP function

This is the Node.js v4 programming model. It is read-only here because it needs the Functions runtime to execute:

JavaScript
const { app } = require("@azure/functions");

app.http("hello", {
  methods: ["GET", "POST"],
  authLevel: "function",
  handler: async (request, context) => {
    const name = request.query.get("name") ?? (await request.text()) ?? "world";
    context.log(`Handling a request for ${name}`);
    return { status: 200, jsonBody: { greeting: `Hello, ${name}` } };
  },
});

authLevel controls the key required: anonymous (no key), function (a function key) or admin (the master key). Keys are a simple gate, not real user authentication; for users, put Entra ID sign-in in front of the app (see Microsoft Entra ID).

A timer function

A timer trigger uses an NCRONTAB expression, which has six fields: second, minute, hour, day of month, month, day of week.

JavaScript
app.timer("nightlyCleanup", {
  schedule: "0 30 2 * * *", // every day at 02:30:00 (UTC unless configured)
  handler: async (timer, context) => {
    context.log("Cleanup started");
    if (timer.isPastDue) context.log("The previous run was missed");
  },
});

0 */5 * * * * means every five minutes. Remember the extra seconds field; the five-field cron from Linux will not parse the same way.

A queue function with an output binding

Here a message in the orders queue triggers the function, and it writes a result to another queue through an output binding. The host handles the connection, the reading, and deleting the message after success:

JavaScript
const { app, output } = require("@azure/functions");

const receipts = output.storageQueue({
  queueName: "receipts",
  connection: "AzureWebJobsStorage",
});

app.storageQueue("processOrder", {
  queueName: "orders",
  connection: "AzureWebJobsStorage",
  extraOutputs: [receipts],
  handler: async (message, context) => {
    const order = typeof message === "string" ? JSON.parse(message) : message;
    context.log(`Processing order ${order.id}`);
    context.extraOutputs.set(receipts, { orderId: order.id, status: "done" });
  },
});

If the handler throws, the message becomes visible again and is retried. After a configurable number of attempts (five by default for Queue Storage) the message moves to a poison queue named orders-poison, so one bad message cannot block the rest. The mechanics of visibility timeouts are explained in Azure Files, Queues and Tables.

flowchart LR
    EVT["Event: HTTP request,<br/>timer tick, queue message"] --> HOST["Functions host"]
    HOST --> IN["Input bindings"]
    IN --> FN["Your function"]
    FN --> OUT["Output bindings"]
    OUT --> SVC["Queue, blob, database"]

The host turns an event into a call to your code and moves data in and out through bindings.

A local dispatcher: a stand-in

The real host is a process that polls queues, listens for HTTP and keeps time. The stand-in below keeps the essential idea in about forty lines: functions register with a trigger and optional output bindings; the host looks up the function for an event, runs it, and writes outputs to in-memory "queues". The names are invented.

Node.js Dispatch events to functions with bindings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The stand-in skips everything that makes the real host valuable: scaling to many instances, durable polling, keys, retries and monitoring. But it shows the shape of your code: small handlers, and a host that connects them to events.

Retries and poison messages: a stand-in

The second stand-in adds the failure path. A handler throws for one "bad" message; the host retries it up to a limit, then moves it to the poison queue, and the good messages continue unharmed. The limit of three is invented to keep the output short.

Node.js Retry and poison queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because functions can run more than once for the same message, make them idempotent: processing a message twice must not charge a customer twice. A common technique is to store the processed message id and skip repeats.

Hosting plans and cold starts

The hosting plan decides how your function app scales and what it costs:

Plan Behavior
Consumption Scales out automatically and down to zero; you pay per execution and resource use; has a free monthly grant; shorter maximum run time
Flex Consumption Newer serverless plan with faster scaling, optional always-ready instances and virtual network support
Premium Pre-warmed instances (no cold start), virtual network integration, longer runs, billed for reserved capacity
Dedicated (App Service plan) Runs on a plan you already pay for, predictable cost, always on

A cold start is the delay on the first request after the app has scaled to zero, because Azure must find a host, start the runtime and load your code. It can be a fraction of a second or several seconds depending on language, package size and plan. Reduce it by keeping deployments small, avoiding heavy initialization on startup, choosing a plan with always-ready or pre-warmed instances when latency matters, or accepting it for background work where nobody is waiting. Cost and capacity trade-offs across all compute options are summarized in Choosing a Compute Service.

Each function app also needs a storage account for internal state such as keys and trigger bookkeeping. Give the app a managed identity instead of a key where the binding supports it (see Managed Identities and Service Principals).

Durable Functions in brief

A normal function is short and stateless. Durable Functions is an extension for long-running, multi-step workflows written as ordinary code. An orchestrator function calls activity functions in order, in parallel, or after waiting for an event, and the framework saves progress so the workflow survives restarts and can wait for days. Typical patterns are function chaining, fan-out/fan-in (process 100 files in parallel, then combine), human approval with a timeout, and polling a job until it finishes. Orchestrator code must be deterministic because it is replayed from its history; do real work such as network calls inside activities. For a visual, low-code alternative see Logic Apps and API Management.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many triggers can a single Azure Function have?

    A function has exactly one trigger that defines what starts it. It can have any number of input and output bindings.
  2. 2. What does an output binding do?

    Output bindings send results to other services declaratively. The trigger starts the function; input bindings supply data.
  3. 3. A timer trigger has the schedule "0 */10 * * * *". How often does it run?

    NCRONTAB has six fields starting with seconds. Second 0 of every tenth minute means every 10 minutes.
  4. 4. Which plan avoids cold starts by keeping pre-warmed instances ready?

    Premium keeps pre-warmed instances. Flex Consumption can also keep always-ready instances. The classic Consumption plan scales to zero and can cold start.
  5. 5. Why should queue-triggered functions be idempotent?

    At-least-once delivery means duplicates are possible. Idempotent handlers make repeated processing harmless.

Summary

  • Azure Functions runs small pieces of code in response to events, on a serverless hosting model.
  • Each function has one trigger (HTTP, timer, queue, blob, event streams, Cosmos DB) and optional input and output bindings configured through app settings.
  • Timer schedules use six-field NCRONTAB; failed queue messages are retried and then moved to a poison queue.
  • Consumption scales to zero and may cold start; Flex Consumption and Premium offer ways to keep instances ready; Dedicated runs on an App Service plan.
  • Write idempotent handlers, keep deployments small, and prefer managed identities over keys.
  • Durable Functions adds stateful orchestration of long-running workflows.

Next: Scaling and Autoscale.