FullStack Engineering CourseLesson 14 of 20 20 min
Azure Services for .NET: App Service, Functions, Containers, APIM and Key Vault
Choosing where code runs
Azure offers several ways to run .NET code. They differ in how much you control and how much Azure manages for you:
| Service | What it is | Good for | Trade-offs |
|---|---|---|---|
| App Service | Managed hosting for web apps and APIs | Most web APIs and sites; quick to set up | Less control over the environment; you pay for the plan even when idle |
| Azure Functions | Event-driven functions that scale with the number of events | Event handlers, scheduled jobs, glue between services, spiky workloads | Cold starts on some plans; limits on run time; code shaped around triggers |
| Azure Container Apps | Managed containers on Kubernetes, without managing Kubernetes | Microservices and workers in containers, scaling on events (even to zero) | Less control than full Kubernetes |
| Azure Kubernetes Service (AKS) | Managed Kubernetes clusters | Large platforms that need full Kubernetes features and control | You run the cluster: upgrades, networking, security; needs real expertise |
| Logic Apps | Low-code workflows built from connectors | Integrations between SaaS systems and business workflows | Harder to version, test and review than code |
A sensible default for a new .NET API is App Service, or Container Apps if you already package everything as containers. Use Functions for event-driven and scheduled work, and AKS only when you need what only Kubernetes offers and have the people to run it.
App Service
App Service runs web apps on a plan: a set of virtual machines whose size and count you choose. Several apps can share one plan. The features you will use most:
- Deployment slots: extra copies of the app (such as staging) with their own URL. Deploy to staging, let it warm up, test it, then swap it into production. The swap is nearly instant, and swapping back is the rollback. Mark settings that belong to one slot (such as a staging database) as slot settings, so they do not move during a swap.
- Autoscale: add or remove instances by schedule or by metrics such as CPU or request count.
- Health check: App Service calls your health endpoint (lesson 7) and stops routing traffic to unhealthy instances.
- Always On: keeps the app loaded, so the first request after an idle period is not slow.
- VNet integration: lets the app reach private resources (databases and Key Vault behind private endpoints) through a virtual network.
- Managed identity: the app's own identity for calling other Azure services without secrets (lesson 12).
Configuration comes from app settings, which the app reads as environment variables. Secrets should not be stored there directly. Use a Key Vault reference instead: the setting holds a pointer, and App Service fetches the real value from Key Vault using the app's managed identity:
Name: ConnectionStrings__ClaimsDb
Value: @Microsoft.KeyVault(VaultName=kv-claims-prod;SecretName=ClaimsDbConnection)The double underscore maps to a colon in .NET configuration, so the code reads it with GetConnectionString("ClaimsDb") as usual. A reference without a version always picks up the latest secret, which makes rotation easy. Better still, connect to Azure SQL with the managed identity itself, so there is no password at all.
Azure Functions
A function runs when a trigger fires: an HTTP request, a message on a queue, a new blob, a timer. Bindings connect inputs and outputs (a blob to read, a queue to write) without writing client code. Azure adds and removes instances automatically based on the number of events.
New .NET functions use the isolated worker model, where your code runs in its own process with full control over .NET versions and dependency injection. The older in-process model reached the end of its support in November 2026, so existing in-process apps should be migrated.
// Program.cs
var builder = FunctionsApplication.CreateBuilder(args);
builder.ConfigureFunctionsWebApplication(); // ASP.NET Core integration for HTTP triggers
builder.Services.AddScoped<IClaimService, ClaimService>();
builder.Build().Run();
public sealed class ClaimFunctions(IClaimService claims, ILogger<ClaimFunctions> log)
{
[Function("GetClaim")]
public async Task<IActionResult> GetClaim(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "claims/{id:int}")] HttpRequest req, int id)
{
var claim = await claims.GetAsync(id, req.HttpContext.RequestAborted);
return claim is null ? new NotFoundResult() : new OkObjectResult(claim);
}
[Function("OnClaimSubmitted")]
public async Task OnClaimSubmitted(
[ServiceBusTrigger("claim-events", "billing", Connection = "ServiceBus")] ServiceBusReceivedMessage message,
CancellationToken ct)
{
var evt = message.Body.ToObjectFromJson<ClaimSubmitted>()!;
log.LogInformation("Billing claim {ClaimId}", evt.ClaimId);
await claims.StartBillingAsync(evt.ClaimId, ct); // an exception lets Service Bus retry, then dead-letter
}
[Function("NightlyCleanup")]
public Task Cleanup([TimerTrigger("0 0 2 * * *")] TimerInfo timer, CancellationToken ct) => // 02:00 every day
claims.ArchiveClosedAsync(ct);
}Hosting plans affect cost and start-up time:
- Flex Consumption: pay per use, scales to zero, with options to keep some instances ready and to connect to virtual networks. The default choice for most new event-driven apps.
- Premium: pre-warmed instances (no cold starts), longer run times, virtual network access, at a fixed minimum cost.
- Dedicated (an App Service plan): runs on a plan you already pay for; predictable cost, no scale to zero.
A cold start is the delay when a function app scales from zero and has to start up before handling the first event. It matters for HTTP APIs that users wait on, and much less for background processing.
Durable Functions
Durable Functions extend Azure Functions with orchestrations: workflows written as ordinary code that can run for minutes, days or months. The framework saves the workflow's progress after each step, so it survives restarts and failures. It has three kinds of function:
- Client function: starts an orchestration, for example from an HTTP request or a queue message.
- Orchestrator function: describes the workflow, calling activities in order or in parallel.
- Activity function: does one piece of real work, such as calling an API or writing to a database.
The orchestrator is replayed. After each step it is run again from the start, and completed steps return their saved results instead of running again. This is how it rebuilds its state, and it leads to one strict rule: orchestrator code must be deterministic (give the same result every time it replays). Do not use DateTime.Now, Guid.NewGuid(), random numbers or direct I/O in an orchestrator; use context.CurrentUtcDateTime and do all I/O in activities.
public static class ClaimFileOrchestration
{
[Function(nameof(ProcessClaimFile))]
public static async Task<int> ProcessClaimFile([OrchestrationTrigger] TaskOrchestrationContext context)
{
string fileUrl = context.GetInput<string>()!;
var retry = TaskOptions.FromRetryPolicy(new RetryPolicy(maxNumberOfAttempts: 3, firstRetryInterval: TimeSpan.FromSeconds(5)));
// Step 1: split the file into batches of claims.
List<string> batches = await context.CallActivityAsync<List<string>>(nameof(SplitFile), fileUrl, retry);
// Step 2: fan out: process all batches in parallel...
var tasks = batches.Select(b => context.CallActivityAsync<int>(nameof(ProcessBatch), b, retry)).ToList();
int[] processed = await Task.WhenAll(tasks);
// ...then fan in: combine the results.
int total = processed.Sum();
await context.CallActivityAsync(nameof(NotifyCompleted), new FileResult(fileUrl, total));
return total;
}
[Function(nameof(SplitFile))]
public static Task<List<string>> SplitFile([ActivityTrigger] string fileUrl) => /* read the blob, write batches */ Task.FromResult(new List<string>());
[Function(nameof(ProcessBatch))]
public static Task<int> ProcessBatch([ActivityTrigger] string batchUrl) => /* validate and save claims */ Task.FromResult(0);
[Function(nameof(NotifyCompleted))]
public static Task NotifyCompleted([ActivityTrigger] FileResult result) => Task.CompletedTask;
[Function("StartClaimFile")]
public static async Task<HttpResponseData> Start(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req, [DurableClient] DurableTaskClient client)
{
string fileUrl = await req.ReadAsStringAsync() ?? "";
string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(nameof(ProcessClaimFile), fileUrl);
return await client.CreateCheckStatusResponseAsync(req, instanceId); // 202 with status URLs
}
}
public sealed record FileResult(string FileUrl, int ClaimCount);Common orchestration patterns:
- Function chaining: run steps one after another, passing results along.
- Fan-out/fan-in: run many activities in parallel, then combine their results (the example above).
- Async HTTP API: the client gets 202 Accepted with a status URL and checks it until the work finishes (CreateCheckStatusResponseAsync does this for you).
- Monitor: check something periodically with durable timers, such as polling a payer for a claim decision.
- Human interaction: wait for an external event, such as a manager's approval, with a timeout (WaitForExternalEvent plus a durable timer).
Activities run at least once, so make them idempotent (lessons 5 and 9). For compensation in a saga, catch the failure in the orchestrator and call activities that undo earlier steps.
Logic Apps
Logic Apps build workflows from ready-made connectors (Outlook, SharePoint, Salesforce, SAP, SFTP, Service Bus and hundreds more) in a visual designer. They suit integrations where most of the work is moving data between existing systems, and where business analysts may maintain the workflow. When the logic is complex, needs unit tests or changes often, Functions or a normal service are easier to version, test and review. Logic Apps Standard can run in your own virtual network and be deployed through CI/CD like code.
Containers: Container Apps and AKS
Azure Container Apps runs containers on a managed Kubernetes platform, without exposing Kubernetes itself:
- Revisions: each deployment creates a new revision, and traffic can be split between revisions for blue-green and canary releases.
- Scaling with KEDA (Kubernetes Event-Driven Autoscaling): scale on HTTP traffic, queue length, Service Bus messages and more, including down to zero.
- Dapr (optional): building blocks for service calls, pub/sub, state and secrets.
- Jobs: containers that run to completion on a schedule or on events.
AKS gives you full Kubernetes: any workload, custom networking, service meshes, operators and fine-grained control. In return, your team is responsible for cluster upgrades, node pools, networking, security patching and capacity. The DevOps lesson covers Kubernetes concepts.
API Management
Azure API Management (APIM) is the API gateway described in lesson 4: one entry point for your APIs, with policies applied to every request. Policies are written in XML and run in the gateway before and after your backend:
<policies>
<inbound>
<base />
<validate-jwt header-name="Authorization" failed-validation-httpcode="401">
<openid-config url="https://login.microsoftonline.com/<tenant-id>/v2.0/.well-known/openid-configuration" />
<audiences><audience>api://claims-api</audience></audiences>
</validate-jwt>
<rate-limit-by-key calls="100" renewal-period="60" counter-key="@(context.Subscription.Id)" />
<set-header name="X-Correlation-ID" exists-action="skip">
<value>@(context.RequestId.ToString())</value>
</set-header>
</inbound>
<backend><base /></backend>
<outbound><base /></outbound>
<on-error><base /></on-error>
</policies>APIM also publishes a developer portal, groups APIs into products with subscription keys and quotas, supports versions and revisions, and can cache responses. Choose the tier by need: the Consumption and v2 tiers are cheaper and quicker to create, while Premium adds multi-region deployment and full virtual network isolation.
Key Vault
Key Vault stores three kinds of sensitive item: secrets (connection strings, API keys), keys (for encryption and signing, which can stay inside hardware security modules and never leave the vault) and certificates (with automatic renewal from supported certificate authorities). Good practice:
- Use Azure RBAC for access, and give each application only the role it needs, such as Key Vault Secrets User for reading secrets.
- Access it through managed identities and private endpoints.
- Keep soft delete and purge protection on, so a deleted vault or secret can be recovered and cannot be destroyed by mistake or by an attacker.
- Rotate secrets, and use references without a version so applications pick up new values.
- Use one vault per application and environment, so access and blast radius (how much is affected if something goes wrong) stay small.
// Reading secrets into .NET configuration at start-up (an alternative to Key Vault references).
builder.Configuration.AddAzureKeyVault(
new Uri("https://kv-claims-prod.vault.azure.net/"),
new DefaultAzureCredential());Storage
Azure Storage holds blobs (files), queues, tables and file shares. Blob Storage is the one most applications use, for documents such as claim files, attachments and exports:
- Access tiers: Hot (frequent access), Cool and Cold (rarely read, cheaper storage, higher read cost) and Archive (cheapest, but takes hours to read back). Lifecycle management rules move blobs between tiers and delete them automatically by age.
- Uploads from browsers: give the client a short-lived SAS (shared access signature) URL for one blob, so the file goes straight to storage instead of through your API. Prefer a user delegation SAS, which is signed with an Entra identity rather than the storage account key.
- Events: Event Grid can notify your code when a blob is created, to start processing.
- Protection: soft delete, versioning and immutability policies (write once, read many) for records that must not be changed.
Global entry points and load balancing
| Service | Works at | Scope | Use it for |
|---|---|---|---|
| Azure Front Door | HTTP (layer 7) | Global | A global entry point with CDN caching, a web application firewall (WAF), TLS and failover between regions |
| Application Gateway | HTTP (layer 7) | One region | Routing and WAF in front of apps inside a virtual network |
| Azure Load Balancer | TCP/UDP (layer 4) | One region | Spreading non-HTTP traffic, or traffic inside a network |
| Traffic Manager | DNS | Global | Sending users to a region by DNS, for any protocol |
A common setup for a public API is Front Door (global entry, WAF, caching of static content) in front of API Management, in front of App Service or Container Apps, with private endpoints for the databases behind them.
Networking basics
- Virtual network (VNet): a private network in Azure, divided into subnets.
- Network security group (NSG): firewall rules that allow or deny traffic to and from subnets.
- Private endpoint: gives a PaaS service (Azure SQL, Storage, Key Vault, Service Bus) a private IP address inside your VNet, so traffic never crosses the public internet. You can then switch off public access to the service entirely.
- Service endpoint: an older, simpler option that keeps traffic on the Azure backbone and lets the service allow your subnet, but the service keeps its public address. Prefer private endpoints for sensitive data.
- VNet integration (App Service, Functions, Container Apps): lets an app call resources inside a VNet, such as private endpoints.
- Private DNS zones: make the normal service names (claims.database.windows.net) resolve to the private endpoint addresses inside the VNet.
Check your understanding
| Question | Short answer |
|---|---|
| App Service, Functions, Container Apps or AKS? | App Service for most APIs; Functions for event-driven and scheduled work; Container Apps for containerised services; AKS when you need full Kubernetes and can run it. |
| What are deployment slots for? | Deploying to a staging copy, warming it up and swapping it into production, with swap-back as rollback. |
| What is a Key Vault reference? | An app setting that points to a Key Vault secret, resolved by the app's managed identity. |
| Isolated worker or in-process for Functions? | Isolated worker; the in-process model's support has ended. |
| What is a cold start? | The delay when a function app starts from zero instances before handling the first event. |
| Why must orchestrator code be deterministic? | Orchestrators are replayed to rebuild their state, so they must give the same result every time. |
| What is fan-out/fan-in? | Running many activities in parallel and then combining their results. |
| What does KEDA do? | Scales containers based on events such as queue length, including down to zero. |
| What does an APIM policy do? | Applies rules such as JWT validation, rate limits and header changes to requests in the gateway. |
| Private endpoint or service endpoint? | A private endpoint gives the service a private IP in your network and allows public access to be switched off; prefer it for sensitive data. |
| Front Door or Application Gateway? | Front Door is a global HTTP entry point with CDN and WAF; Application Gateway is regional and sits inside a virtual network. |
Summary
- Pick compute by need: App Service by default, Functions for events and schedules, Container Apps for containers, AKS only when justified.
- Use deployment slots, health checks, autoscale and managed identities on App Service, with Key Vault references for any remaining secrets.
- Write Functions in the isolated worker model and choose the hosting plan by cold-start and cost needs.
- Use Durable Functions for long-running workflows, with deterministic orchestrators and idempotent activities.
- Put APIs behind API Management, and Front Door in front for global entry, WAF and caching.
- Keep data services private with private endpoints, and secrets in Key Vault with RBAC, soft delete and purge protection.
The next lesson covers how this all gets built and deployed: Docker, Kubernetes and Helm, infrastructure as code with Terraform and Bicep, CI/CD with GitHub Actions and Azure DevOps, GitOps, trunk-based development, feature flags, blue-green and canary releases, and DORA metrics.
Comments