Azure Functions Tutorial: Event-Driven Serverless
On this page
Learning Objective
Build event-driven functions on the isolated worker model with triggers and bindings, choose a hosting plan and control concurrency and cost, use Durable Functions for workflows, connect with managed identity, and secure HTTP triggers and avoid runaway loops.
Concept Explanation
Serverless functions let you write a small piece of code that runs in response to an event, with the platform providing the servers, scaling, and pay-per-use pricing. Azure Functions supplies triggers, which start a function, and bindings, which read or write data with little code. The common triggers are an HTTP request, a timer on a schedule, a message on a Service Bus queue or topic, an Event Hubs event, a blob created in storage, an Event Grid notification, and a change in a Cosmos DB container. They suit the background work of Days 65 and 66, scheduled jobs, webhook receivers, and glue between services, where the workload is spiky or event-driven and you do not want to run a server continuously.
Two practical choices come first. The programming model: the isolated worker model runs your function in its own process, uses your own dependency injection and middleware setup like an ordinary .NET host, and is the model for current and future .NET versions. The older in-process model shares a process with the runtime and reaches end of support on 10 November 2026, so new work should use the isolated worker. The hosting plan: the Consumption model scales to zero and charges per execution, with cold starts after idle periods; the Flex Consumption plan offers faster scaling and networking options; Premium keeps warm instances and supports virtual network integration; and a dedicated plan runs functions on App Service instances you already pay for. Choose by latency tolerance, networking needs, and cost profile, and remember that a background service in a container, or Container Apps with KEDA scaling, is often a good alternative when logic is complex or long-running.
Reliability follows the patterns of Day 122. Queue and event triggers give at least once delivery, so functions must be idempotent, with retries configured and poison messages moving to a dead-letter queue. Control concurrency in host settings, so a burst of messages does not overwhelm a database or a downstream API, since scale-out multiplies the load you place on everything behind the function. For workflows that span multiple steps or wait for people, Durable Functions provides orchestrations written as ordinary code that call activity functions, with state saved automatically, supporting sequences, fan-out and fan-in, timers, and waiting for an external event, and it replaces fragile hand-built state machines. Orchestrator code must be deterministic, so it must not read the clock, generate random values, or do input and output directly.
Security and cost need attention because functions are easy to expose and easy to run away. An HTTP trigger with anonymous authorization is a public endpoint, and function keys are shared secrets meant for simple protection, not user authentication, and they appear in URLs that end up in logs. For user-facing or partner endpoints, put Entra authentication in front of the function app and validate tokens as in Day 131. Connect to storage, Service Bus, and other services with identity-based connections, so the app uses its managed identity and holds no connection strings. Keep secrets in Key Vault references. On the cost side, a function that writes to the same container or queue that triggers it can create an infinite loop that runs up a large bill, and an unauthenticated endpoint can be hammered to inflate charges, so set budgets, alerts, and limits on maximum scale-out.
| Choice | Options | Guidance |
|---|---|---|
| Programming model | Isolated worker or in-process | Isolated worker for all new work, in-process support ends 10 November 2026 |
| Hosting plan | Consumption, Flex Consumption, Premium, Dedicated | Trade cold start, networking, and cost |
| Triggers | HTTP, Timer, Service Bus, Event Hubs, Blob, Event Grid, Cosmos | Pick by the event source, expect at-least-once |
| Workflows | Durable Functions orchestrations | Deterministic orchestrator code, activities do the work |
| Connections | Identity-based with managed identity | No connection strings to leak |
| Cost control | Concurrency limits, max scale-out, budgets, alerts | Prevent runaway loops and denial of wallet |
Worked Example: A Queue Function, a Timer, a Durable Workflow and Safe Configuration
The isolated worker program configures services, and the functions show triggers, idempotency, and orchestration.
// Program.cs (isolated worker): a normal .NET host with dependency injection.
var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureServices(s =>
{
s.AddApplicationInsightsTelemetryWorkerService().ConfigureFunctionsApplicationInsights();
s.AddDbContext<AppDb>(o => o.UseSqlServer(Environment.GetEnvironmentVariable("SqlConnection"), sql => sql.EnableRetryOnFailure()));
})
.Build();
host.Run();public sealed class InvoiceFunctions(AppDb db, ILogger<InvoiceFunctions> log)
{
// Service Bus trigger with an identity-based connection (ServiceBus__fullyQualifiedNamespace is set, there is no connection string).
[Function("ProcessInvoice")]
public async Task ProcessInvoice(
[ServiceBusTrigger("invoices", Connection = "ServiceBus")] ServiceBusReceivedMessage message,
ServiceBusMessageActions actions, CancellationToken ct)
{
if (await db.Inbox.AnyAsync(i => i.MessageId == message.MessageId, ct)) { await actions.CompleteMessageAsync(message, ct); return; } // idempotent
var request = JsonSerializer.Deserialize<InvoiceRequested>(message.Body)
?? throw new InvalidDataException("Empty message"); // retried, then dead-lettered
db.Inbox.Add(new InboxRecord(message.MessageId, DateTimeOffset.UtcNow));
db.Invoices.Add(Invoice.From(request));
await db.SaveChangesAsync(ct);
await actions.CompleteMessageAsync(message, ct);
log.LogInformation("Invoice created for order {OrderId}", request.OrderId);
}
// Timer trigger: NCRONTAB format, seconds first. Runs once per schedule even with several instances.
[Function("NightlyRetention")]
public async Task NightlyRetention([TimerTrigger("0 0 2 * * *")] TimerInfo timer, CancellationToken ct) => await retention.RunAsync(ct);
}// Durable Functions: a workflow written as ordinary code. State is saved at each await, and it survives restarts.
public static class OnboardingWorkflow
{
[Function("Onboarding")]
public static async Task Run([OrchestrationTrigger] TaskOrchestrationContext ctx)
{
var input = ctx.GetInput<OnboardingRequest>()!;
var accountId = await ctx.CallActivityAsync<Guid>("CreateAccount", input);
// Fan out and wait for all of them.
await Task.WhenAll(input.Modules.Select(m => ctx.CallActivityAsync("ProvisionModule", new { accountId, module = m })));
// Wait up to 3 days for the customer to confirm, then continue or time out. No thread is blocked while waiting.
using var cts = new CancellationTokenSource();
var confirmed = ctx.WaitForExternalEvent<bool>("Confirmed");
var timeout = ctx.CreateTimer(ctx.CurrentUtcDateTime.AddDays(3), cts.Token); // the orchestrator clock is deterministic, never DateTime.UtcNow
if (await Task.WhenAny(confirmed, timeout) == confirmed) { cts.Cancel(); await ctx.CallActivityAsync("ActivateAccount", accountId); }
else await ctx.CallActivityAsync("SendReminderAndClose", accountId);
}
}// host.json: concurrency and retry limits so a burst cannot overwhelm what the function calls.
{
"version": "2.0",
"extensions": {
"serviceBus": { "maxConcurrentCalls": 16, "maxAutoLockRenewalDuration": "00:05:00" }
},
"retry": { "strategy": "exponentialBackoff", "maxRetryCount": 4, "minimumInterval": "00:00:05", "maximumInterval": "00:05:00" }
}Security and cost checklist for a function app
HTTP triggers: Entra authentication (Easy Auth) in front, JWT validated in code. Function keys are not user authentication.
Connections: identity-based (ServiceBus__fullyQualifiedNamespace, AzureWebJobsStorage__accountName), roles granted to the managed identity.
Secrets: Key Vault references in app settings, none in source control.
Network: private endpoints and virtual network integration on Premium or Flex Consumption where data is sensitive.
Loops: no function writes to the resource that triggers it without a guard. Set functionAppScaleLimit and a budget alert.Test the idempotency the same way as on Day 122: deliver the same message twice, and assert that only one invoice exists.
Real-World Examples
- Microsoft announced that support for the in-process model for .NET functions ends on 10 November 2026, and recommends migrating to the isolated worker model, which decouples the function code from the host runtime and its dependencies. Teams with older function apps are therefore planning migrations, which the isolated model makes easier by using a standard .NET host.
- Serverless billing has produced well-known surprises: developers have reported large charges when a function accidentally triggered itself in a loop or when a public endpoint was flooded with requests, leading to the term denial of wallet. Cloud providers recommend budgets and alerts, scale limits, authentication on endpoints, and guards against recursive triggers as standard protections.
Review Questions & Answers
Delivery is at least once, so a crash or timeout after the work is done causes the same message to be delivered again. Recording processed message ids, or making the operation naturally repeatable, prevents duplicate effects.
It is a shared secret that identifies no one, is easily copied, and often appears in URLs and logs. Real user or client authentication needs Entra ID or another token-based mechanism validated in front of or inside the function.
It must be deterministic because the framework replays it from history, so it must not use the current time, random values, or direct input and output. Those operations belong in activity functions, and the orchestrator uses the deterministic clock and durable timers.
A function that writes to the container or queue that triggers it can loop indefinitely, and an unauthenticated public endpoint can be flooded with requests. Guards, authentication, scale limits, and budget alerts prevent it.