📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do Azure Functions work for a .NET 10 team? Explain the isolated worker model, triggers and bindings, the hosting plans (Flex Consumption, Premium, Dedicated), cold starts and how you reduce them, and when you would use Durable Functions.

Azure Functions for .NET 10: the isolated worker model, triggers and bindings, Flex Consumption vs Premium vs Dedicated plans, cold starts and timeouts, and Durable Functions orchestrations.

Mid-Level Theory Intermediate azure azure-functions devops durable-functions isolated-worker serverless

🎯 Key points

  • Isolated worker: separate .NET process, own Program.cs, middleware, full DI
  • In-process model has been out of support since 10 November 2026; migrate to isolated on .NET 10
  • Triggers start a function; bindings move data in and out (Blob input, Service Bus or Cosmos DB output)
  • Flex Consumption is the serverless default; Linux Consumption gets no new features and retires 30 September 2028
  • Cold starts add seconds to the first request and can break partner SLAs; fix with always-ready or pre-warmed instances and lean startup
  • HTTP response limit about 230 seconds; queue the work instead
  • Durable Functions: orchestrator replay, deterministic code, activities, fan-out/fan-in
  • Triggers are at-least-once, so functions must be idempotent

⏱ 30-second answer

Azure Functions runs small pieces of code in response to triggers (HTTP, Service Bus, Blob, Timer, Event Grid). For .NET 10 you use the isolated worker model: your code runs in its own process with a normal Program.cs, DI and middleware, and talks to the Functions host over gRPC. The in-process model reached end of support in November 2026.

  • Hosting: Flex Consumption (scale to zero, VNet, always-ready instances), Premium (pre-warmed, no cold start), or Dedicated (App Service plan).
  • Cold starts come from starting a new instance; reduce them with always-ready instances and lean startup.
  • Durable Functions handles long-running, stateful workflows through replayed orchestrations.

The trade-off: very little infrastructure work and per-event scaling, in exchange for the platform's execution limits and an at-least-once programming model.

🗣 Full answer (senior)

How I would answer this in an interview

"A function app is a host process that listens to triggers and runs my code when one fires: an HTTP request, a Service Bus message, a new blob, a timer. Bindings let me declare inputs and outputs, for example returning a message to a queue, instead of writing SDK code. For .NET 10 the only supported model is the isolated worker: my code runs in a separate .NET process that talks to the Functions host over gRPC. That gives me my own Program.cs, normal dependency injection, middleware and any .NET version the worker supports, and it decouples me from the host's assemblies. The old in-process model reached end of support on 10 November 2026, so anything still on it needs migrating.

For hosting, Flex Consumption is my default for serverless now. It scales per event and to zero, supports VNet integration, and lets me keep a few always-ready instances so the first request doesn't pay a cold start. Linux Consumption gets no new features and retires in 2028. Premium keeps pre-warmed instances and suits steady, latency-sensitive work. Dedicated runs on an App Service plan I already pay for. Cold starts come from allocating an instance, starting the host and worker, and running my startup code, so I keep startup lean, avoid heavy work in constructors, and use ReadyToRun where it helps.

Durable Functions is for workflows: an order process that waits for payment, calls three services and compensates on failure. The orchestrator is replayed from history, so its code must be deterministic. The mistake I see is people forgetting that triggers are at-least-once: a Service Bus-triggered function can run twice for the same message, so the handler must be idempotent. Functions are cheap to run but not free of design work."


Triggers and bindings

Trigger Typical use Delivery and duplicates
HTTP Webhooks, small APIs Client retries can duplicate; use idempotency keys
Service Bus Business messages At-least-once (peek-lock); dedupe on message id
Blob (Event Grid source) Process uploads At-least-once; check if already processed
Timer Scheduled jobs Singleton lock by default, but can still overlap on failure
Event Hubs Telemetry streams At-least-once per partition checkpoint

Hosting plans

Plan Scale to zero Cold start VNet Max execution Billing
Flex Consumption Yes Reduced with always-ready Yes Unbounded (default 30 min) Per execution + always-ready
Premium No (min 1) None (pre-warmed) Yes Unbounded (default 30 min) Per instance
Dedicated No None if Always On Yes Unbounded App Service plan
Consumption (legacy) Yes Yes No 10 min Per execution

When not to use Functions

  • Large, chatty HTTP APIs with many endpoints: App Service or Container Apps is simpler.
  • Work needing custom native dependencies or containers on Flex: Flex is code-only; use Container Apps.
  • Constant high load: a plan or containers may be cheaper than per-execution billing.

Production example

A team processing supplier invoice PDFs moved from a Windows service polling a share to a blob-triggered function on Flex Consumption with two always-ready instances. Median processing time dropped from about 5 minutes (poll interval) to under 10 seconds, and monthly compute cost fell to under A$60 because the app was idle most of the night.

🔍 What the interviewer is checking

Checks that the candidate understands the Functions execution model and its current hosting options, not just how to write a trigger.

Green flags

  • Knows the isolated worker model and that in-process is out of support
  • Explains cold starts and the real fixes (always-ready, pre-warmed, lean startup)
  • Knows Durable orchestrators replay and must be deterministic
  • Mentions at-least-once triggers and idempotency

Red flags

  • Thinks Functions are only for tiny scripts, or uses them for everything
  • Puts long-running work in HTTP triggers
  • Unaware of plan differences or timeouts

📚 Learn in depth

1. Host and worker

  Trigger source (Service Bus, HTTP...)
          │
          ▼
  Functions host (runtime v4) ── gRPC ──▶ Isolated worker (your .NET 10 process)
   - listens to triggers                    - Program.cs, DI, middleware
   - manages bindings and scale             - your function classes

The host owns trigger listeners, bindings and scale signals. The worker runs your code. Because they are separate processes, your app can use its own package versions without clashing with the host. With ConfigureFunctionsWebApplication() the HTTP trigger can use ASP.NET Core types (HttpRequest, IActionResult) through the ASP.NET Core integration.

2. Bindings in practice

A trigger is the one binding that starts the function. Input bindings load data before your code runs; output bindings write data after it returns.

Binding Direction Example
[BlobInput("templates/{name}")] Input Load an email template by name from the route
[ServiceBusOutput("invoices")] Output Return an object and the host sends it as a message
[CosmosDBOutput(...)] Output Return a document to upsert
[SqlInput(...)] Input Run a query and pass rows to the function

Bindings remove SDK boilerplate, but they hide retry and error behaviour. For anything needing transactions, custom retries or batching, inject the SDK client instead.

3. How scaling works

A scale controller watches trigger sources: queue length, Event Hubs backlog, HTTP concurrency. It adds instances when the backlog grows and removes them when it shrinks. Flex Consumption scales HTTP, Blob (Event Grid) and Durable triggers in their own groups, and each instance handles a configurable number of concurrent executions.

4. Anatomy of a cold start, and why it matters

  1. Allocate an instance (worker VM or sandbox).
  2. Mount the deployment package.
  3. Start the host and the isolated worker process.
  4. Run your Program.cs (DI container build, configuration, Key Vault calls).
  5. JIT the first call path.

Steps 1–3 are the platform's job; always-ready (Flex) or pre-warmed (Premium) instances skip them. Steps 4–5 are yours: avoid network calls at startup, keep DI registrations cheap, consider ReadyToRun to cut JIT time.

The impact is on the tail: median latency looks fine, but p99 includes requests that waited several seconds. For a webhook with a 5-second partner timeout, or a user-facing API with a 1-second SLO, those requests are failures, and the caller's retries can create duplicate work. That is why cold start is an SLA decision, not a tuning detail.

5. Monitoring and troubleshooting

  • Application Insights: request duration by cloud_RoleInstance, plus the FunctionExecutionCount and execution duration metrics. A KQL query joining the first request per instance to its duration shows cold-start cost directly.
  • Live Metrics: watch instance count change as a queue backlog grows.
  • Host logs: host.json log levels for Host.Results and Function; keep Host.Aggregator on for summary counts.
  • Common bottlenecks: synchronous Key Vault or database calls in startup, a new HttpClient per invocation, too-high per-instance concurrency starving the thread pool, and Service Bus lock expiry on long handlers (visible as rising DeliveryCount).

6. Durable Functions replay

Orchestrator starts ─▶ schedules Activity A ─▶ awaits ─▶ (process unloads)
A completes ─▶ history updated ─▶ orchestrator REPLAYS from start
   replay sees A already done in history ─▶ returns stored result ─▶ schedules B

The orchestrator's state is rebuilt by replaying its code against an event history in the storage provider (Azure Storage, MSSQL, Netherite or the managed Durable Task Scheduler). So the code must be deterministic: no DateTime.UtcNow (use context.CurrentUtcDateTime), no direct I/O, no random GUIDs (use context.NewGuid()). I/O goes in activities, which are at-least-once and must be idempotent.

Patterns: function chaining, fan-out/fan-in, async HTTP APIs (status endpoint), monitors, human interaction with external events and timeouts.

7. Limits that matter

  • HTTP response timeout is about 230 seconds because of the front-end load balancer, on every plan.
  • Flex Consumption is Linux-only and code-only (no custom containers), with one app per plan.
  • Service Bus message lock duration still applies; long handlers need lock renewal (the host does it up to maxAutoLockRenewalDuration).

Try it yourself

  1. func init --worker-runtime dotnet-isolated --target-framework net10.0 and add a Service Bus trigger; run it locally with Azurite and a dev namespace.
  2. Throw an exception on the first delivery and watch the message come back with DeliveryCount = 2.
  3. Deploy to Flex Consumption with and without one always-ready instance; compare first-request latency in Application Insights.
  4. Write a Durable fan-out/fan-in orchestration over 50 items and look at the history table to see replay.

💻 Code

An isolated worker function app on .NET 10: Program.cs, an idempotent Service Bus trigger, and a small Durable orchestration.

// Program.cs
using Microsoft.Azure.Functions.Worker.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = FunctionsApplication.CreateBuilder(args);
builder.ConfigureFunctionsWebApplication(); // ASP.NET Core integration for HTTP triggers

builder.Services
    .AddApplicationInsightsTelemetryWorkerService()
    .ConfigureFunctionsApplicationInsights();
builder.Services.AddSingleton<IProcessedMessageStore, SqlProcessedMessageStore>();

builder.Build().Run();
namespace Invoices.Functions;

using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Functions.Worker;
using Microsoft.DurableTask;
using Microsoft.DurableTask.Client;
using Microsoft.Extensions.Logging;

public sealed record InvoiceReceived(Guid InvoiceId, string BlobName);

public sealed class InvoiceFunctions(IProcessedMessageStore store, ILogger<InvoiceFunctions> logger)
{
    // Service Bus delivery is at-least-once: the same message can arrive twice,
    // so we record the MessageId and skip duplicates.
    [Function(nameof(OnInvoiceReceived))]
    public async Task OnInvoiceReceived(
        [ServiceBusTrigger("invoices", Connection = "ServiceBus")] ServiceBusReceivedMessage message,
        [DurableClient] DurableTaskClient durable,
        CancellationToken ct)
    {
        if (!await store.TryMarkProcessedAsync(message.MessageId, ct))
        {
            logger.LogInformation("Duplicate message {MessageId} skipped", message.MessageId);
            return;
        }

        var invoice = message.Body.ToObjectFromJson<InvoiceReceived>()!;
        // Instance id = invoice id, so a second start for the same invoice is rejected.
        await durable.ScheduleNewOrchestrationInstanceAsync(
            nameof(ProcessInvoice), invoice,
            new StartOrchestrationOptions(InstanceId: invoice.InvoiceId.ToString()), ct);
    }

    // Orchestrator: deterministic code only; all I/O happens in activities.
    [Function(nameof(ProcessInvoice))]
    public static async Task ProcessInvoice([OrchestrationTrigger] TaskOrchestrationContext context)
    {
        var invoice = context.GetInput<InvoiceReceived>()!;
        var text = await context.CallActivityAsync<string>(nameof(ExtractText), invoice.BlobName);
        await context.CallActivityAsync(nameof(SaveInvoice), text);
    }

    [Function(nameof(ExtractText))]
    public static Task<string> ExtractText([ActivityTrigger] string blobName) =>
        Task.FromResult($"text of {blobName}");

    [Function(nameof(SaveInvoice))]
    public static Task SaveInvoice([ActivityTrigger] string text) => Task.CompletedTask;
}

public interface IProcessedMessageStore
{
    Task<bool> TryMarkProcessedAsync(string messageId, CancellationToken ct);
}

The ServiceBus connection uses managed identity, not a connection string:

{
  "ServiceBus__fullyQualifiedNamespace": "sb-invoices-prod-aue.servicebus.windows.net"
}

⚠ Common mistakes

  • Mistake: Starting or keeping .NET function apps on the in-process model. Why it is wrong: It has been out of support since 10 November 2026 and tops out at .NET 8. Instead: Migrate to the isolated worker model on .NET 10.
  • Mistake: Assuming each trigger runs exactly once. Why it is wrong: Service Bus, Blob and Event Hubs triggers are at-least-once; retries and lock expiry cause duplicates. Instead: Make handlers idempotent with a processed-message store or natural keys.
  • Mistake: Doing long work inside an HTTP trigger. Why it is wrong: The front end cuts the response at about 230 seconds. Instead: Return 202 and continue in a queue-triggered function or a Durable orchestration.
  • Mistake: Calling DateTime.UtcNow, Guid.NewGuid() or HTTP inside an orchestrator. Why it is wrong: Replay produces different values and corrupts the orchestration. Instead: Use context.CurrentUtcDateTime, context.NewGuid() and activities.
  • Mistake: Using connection strings in app settings for triggers. Why it is wrong: Secrets in configuration, manual rotation. Instead: Use identity-based connections (__fullyQualifiedNamespace) with RBAC roles.
  • Mistake: Creating a new HttpClient or SDK client per invocation. Why it is wrong: Socket exhaustion and slower executions. Instead: Register clients as singletons in DI.
  • Mistake: Choosing Flex Consumption for an app that needs a custom container. Why it is wrong: Flex is code-only. Instead: Use Premium, Dedicated or Container Apps hosting.

🏛 Senior insight: trade-offs

Functions shine when the trigger model matches the work: one message in, one unit of work out. They get awkward when you fight them with long HTTP calls, shared in-memory state or very high constant load. I treat a function app like any other service: same observability, same IaC, same idempotency rules, and I check the always-ready cost against Premium once traffic is steady.

Option When it fits Cost When not to
Flex Consumption Spiky, event-driven, VNet needed Per execution + always-ready Custom containers, constant heavy load
Premium Steady load, no cold start allowed Always-on instances Mostly idle apps
Durable Functions Multi-step workflows with waits and compensation Storage transactions, replay overhead Simple one-step handlers
BackgroundService in a container Long-running consumers you fully control Always-on container Scale to zero needed with no effort

I measure cold start with Application Insights request duration by cloud_RoleInstance age, execution counts and cost per million executions in Cost Management.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Service Bus triggers Why: Checks they know how to write the same consumer as a hosted service with ServiceBusProcessor and when that beats a function
    How to answer

    I host a ServiceBusProcessor in a BackgroundService, with ServiceBusClient as a singleton using DefaultAzureCredential. I set AutoCompleteMessages = false and settle explicitly:

    • Complete after the database commit, which gives at-least-once delivery.
    • Abandon (or just throw) on transient errors so DeliveryCount rises and the broker redelivers; after MaxDeliveryCount it dead-letters automatically.
    • Dead-letter immediately on permanent errors such as an unparseable body, with a reason.

    MaxConcurrentCalls is sized to the downstream, PrefetchCount is kept small, and MaxAutoLockRenewalDuration is longer than the slowest handler. On shutdown I call StopProcessingAsync and honour args.CancellationToken. Because duplicates still happen, the handler is idempotent on MessageId. The trade-off: more concurrency means more throughput but more pressure on the database.

  2. When: Candidate says triggers are at-least-once Why: Checks they understand delivery guarantees and how to get effectively-once processing
    How to answer

    At-most-once means settle first, then process: a crash loses the message. At-least-once means process first, then settle: a crash or lock expiry redelivers, so you get duplicates. Almost every real system chooses at-least-once.

    Exactly-once delivery is a myth because the acknowledgement itself can be lost after the work is done; the broker can't tell "not processed" from "processed but ack lost".

    • Kafka transactions give exactly-once only for read-process-write within Kafka.
    • Service Bus duplicate detection and SQS FIFO dedup only drop producer resends within a window.

    What you build is effectively-once processing: at-least-once delivery plus an idempotent consumer, using a natural idempotent write or an inbox row committed in the same transaction. The trade-off is extra storage and a unique-key check per message.

🛠 Real-world problems: how you handle them

Cold starts made a Function-based webhook miss the partner's 5-second timeout
Situation
A payments partner calls our webhook, hosted as an HTTP-triggered function on the Linux Consumption plan, and gives up after 5 seconds. Traffic was low overnight, about [20] calls an hour, so instances were often scaled to zero. Missed webhooks meant [orders stuck in Pending].
Signals
Partner dashboard showed [8%] of webhooks timing out, all between [midnight and 6 am]. Application Insights showed request durations of 6–9 seconds for the first call after idle and under 150 ms otherwise. The partner retried, causing duplicate notifications.
Investigation
Grouped requests in Application Insights (KQL) by `cloud_RoleInstance` and time since the previous request, which confirmed the slow calls were the first on a new instance. Checked startup: `Program.cs` read [six] Key Vault secrets synchronously and built an EF Core model on first use. Reviewed the plan: Linux Consumption has no always-ready option and is retiring.
Resolution
Immediate: returned 202 straight away and moved processing to a Service Bus queue, so the webhook itself did almost nothing. Real fix: migrated to Flex Consumption with one always-ready instance for the HTTP group, moved Key Vault loading to the configuration provider with caching, and made the queue handler idempotent on the partner's event id so retries were harmless.
Prevention
Added an availability test and an alert on webhook p99 over 2 seconds, a load test after idle in the pipeline, and an ADR that partner-facing endpoints never run on a plan without warm instances.

How to tell it (STAR)

**S:** Our payments partner calls a webhook that ran as a function on Linux Consumption, and they give up after 5 seconds. Overnight, about [8%] of calls were timing out. **T:** I had to find out why and stop orders getting stuck. **A:** In Application Insights I saw the slow calls were always the first on a new instance, 6 to 9 seconds, because of cold start plus [six] Key Vault reads at startup. I changed the webhook to return 202 immediately and queue the work, moved us to Flex Consumption with one always-ready instance, and made the handler idempotent on the partner's event id. **R:** Webhook p99 dropped from [9 seconds] to [180 ms], timeouts went to [zero], and the partner's retries stopped creating duplicates.

↩ Usually asked after

More in Azure

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me