Microsoft AZ-204: Azure Functions and Serverless Computing — Study Guide
Part of the Microsoft Azure Developer Associate AZ-204 — Study Guide. Practice with verified answers in the Microsoft exam hub, or take timed practice tests on ExamRoll.io.
Overview
Azure Functions is a serverless compute service optimized for event-driven and short-lived workloads. It abstracts infrastructure so you focus on code that responds to events from HTTP endpoints, queues, blobs, data change feeds, and streaming services. You select a hosting plan that governs scaling, pricing, and cold-start behavior; bind your code to triggers and data sources with declarative bindings; and optionally compose long-running, reliable workflows using Durable Functions. Robust configuration, repeatable deployment, and deep observability with Application Insights round out the platform for production-grade systems.
Hosting Plans, Scaling, and Cold Starts
Selecting a hosting plan drives execution characteristics and cost.
Consumption plan:
- Scale and pricing: Pay per execution and resource consumption. The platform scales out automatically based on events. Instance count scales to zero when idle.
- Execution limits: Function timeout is configurable up to 10 minutes for non-HTTP functions; HTTP functions have shorter practical timeouts due to client connectivity.
- Cold start: Cold starts occur after idle periods or scale-out when new instances initialize. Startup time depends on language, dependencies, and app size.
- Networking/features: Supports public networking by default. Limited feature set compared to Premium (for example, no VNET integration). Deployment slots are not available.
Premium plan:
- Scale and pricing: Scales based on events but maintains “pre-warmed” instances to eliminate cold starts. Billed by core seconds and memory allocated for active and pre-warmed instances.
- Execution limits: Practically unlimited execution duration (subject to HTTP client constraints). Recommended for latency-sensitive or heavier workloads.
- Cold start mitigation: Pre-warmed instances keep the runtime hot. You control the number of pre-warmed instances per plan, providing predictable latency under burst.
- Networking/features: VNET integration, private endpoints, increased instance sizes, and deployment slots supported.
Dedicated (App Service) plan:
- Scale and pricing: Runs on provisioned App Service instances with manual or autoscale rules. You pay for the underlying App Service plan regardless of use.
- Execution limits: No platform-imposed timeout for background execution. Ideal when you already have spare App Service capacity or need consistent performance.
- Cold start mitigation: Enable Always On to keep the app loaded. No scale-to-zero; instances remain warm.
Choose Consumption for cost-optimized sporadic workloads, Premium for low-latency and VNET needs, and Dedicated when consolidating with existing App Service capacity or requiring full control. For ultra-low latency, Premium with pre-warmed instances or Dedicated with Always On reduces cold starts. Minimize cold start impact further by trimming dependencies, using run-from-package, and initializing clients lazily.
Triggers and Bindings
Functions are activated by triggers and interact with data via bindings. Triggers define how and when a function runs. Bindings declaratively connect to external services for input/output without imperative SDK code.
Common triggers:
- HTTP trigger: Exposes endpoints for REST-style APIs or webhooks. Authorization levels include Anonymous, Function, and Admin, enforced via keys or platform auth. Consider idempotency and timeouts for long-running tasks; offload to queue or Durable Functions when needed.
- Timer trigger: CRON-based schedules run on a single instance per app (per timer). Use NCRONTAB expressions with time zone configuration. Ideal for maintenance, polling, and cleanup jobs.
- Azure Storage Queue trigger: Responds to messages in a queue. Supports poison message handling with a -poison queue after dequeue count threshold. Configure batch size, visibility timeout, and concurrency via host.json.
- Azure Blob Storage trigger: Reacts to blob create/update events using a combination of polling and Event Grid notifications. Use path patterns to scope containers and prefixes. Understand eventual consistency and retry behavior for large blob uploads.
- Azure Event Hubs trigger: Consumes high-throughput event streams with checkpointing. Configure partition concurrency, batch size, and prefetch for throughput. Suitable for telemetry and stream processing with ordering preserved per partition.
- Azure Service Bus trigger: Supports queue or topic subscription. Configure maxConcurrentCalls, prefetch, and auto-complete behaviors. Dead-letter queues capture messages that exceed delivery attempts for later inspection.
- Azure Cosmos DB trigger: Listens to change feed for inserts and updates. Scales with number of physical partitions; ensure sufficient RU provisioning. Use leases collection to coordinate scale-out across instances.
Bindings:
- Input bindings: Supply data into the function, e.g., blob content, table entity, Cosmos DB documents, or queue message metadata. In .NET, attributes (e.g., [BlobInput]) or function.json define the binding; in other languages, configuration is declarative.
- Output bindings: Write data without SDKs, e.g., enqueue a message, create a blob, send to Event Hub/Service Bus, or write to Cosmos DB. Functions can have multiple output bindings or return a single output from the function signature.
- Binding expressions: Parameterize connection details and paths using placeholders, e.g., {queueTrigger}, {rand-guid}, and environment-based app settings. Connection properties reference application settings names, enabling rotation and secret management. Prefer identity-based connections with managed identity where supported to avoid embedding secrets.
- Concurrency and batch: Control concurrency and batch sizes in host.json per extension (queues, serviceBus, eventHub) to tune throughput and memory usage. Validate poison/dead-letter handling to ensure failures are surfaced.
Design triggers and bindings for idempotency, backpressure, and failure isolation. For at-least-once delivery sources (queues, Event Hubs, Service Bus), write functions as idempotent and resilient to retries.
Durable Functions: Reliable Orchestration Patterns
Durable Functions extends Azure Functions with stateful, reliable orchestration for long-running workflows using a durable task framework.
Function types:
- Orchestrator functions: Describe workflow logic in code using deterministic constructs. Orchestrators replay state upon events and must avoid non-deterministic APIs (DateTime.Now, random, network calls) without appropriate helpers. Use Durable orchestration client APIs to start, query, and manage instances.
- Activity functions: Execute discrete units of work such as calling external APIs, performing CPU-bound operations, or IO tasks. Activities are retryable and independently scalable.
- Entity functions: Provide durable, addressable entities with small, consistent state and operations (e.g., counters, device state). Entities process serialized operations with single-threaded consistency.
Patterns:
- Function chaining: Sequence activities in a defined order (A → B → C), passing results to the next. Useful for pipelines with dependencies.
- Fan-out/fan-in: Start multiple activities in parallel and aggregate results. Orchestrators coordinate with Task.WhenAll-like semantics. Use this for parallel processing of independent tasks.
- Human interaction (external events): Wait for external input (e.g., approval) using WaitForExternalEvent with timeouts and escalation. Combine with durable timers to implement SLAs and compensation logic.
- Async HTTP APIs: Start orchestrations and return 202 Accepted with status/query URLs. Clients poll status endpoints exposed by the Durable client binding for eventual result or state.
- Monitor: Recurrent checkpoints that run on a schedule, e.g., polling an endpoint until a condition is met, using durable timers to avoid holding compute.
- Aggregator/Entity: Store small state next to logic using entity functions for fine-grained coordination without a full workflow.
Durable Functions guarantee at-least-once execution of activities and exactly-once progression of orchestrator state. They persist state in storage (default is Azure Storage); ensure the storage account meets throughput and reliability needs. Use custom retry policies for transient failures and raise events for external interaction. For very long processes, durable orchestrations can run for days to months with built-in durability.
Configuration, Deployment, and Observability
Function app configuration is layered and environment-aware.
- host.json: Controls runtime and extension behavior. Configure logging (sampling, log levels), functionTimeout, extension settings (batch sizes, concurrency, prefetch), and JSON schema version. Keep host.json in source control.
- local.settings.json: Local development settings including connection strings and app settings. Not deployed to Azure. Treat secrets appropriately; exclude from public repos and use user-secrets or environment injection for local development.
- Application settings: Stored in the Function App (App Service) configuration. Critical settings include AzureWebJobsStorage (for storage account used by triggers, logs, and checkpoints), extension-specific connection strings, and any custom configuration. Mark secrets as slot settings to avoid swapping. Use Key Vault references with managed identity to avoid storing secrets in plain text.
Deployment options:
- Zip Deploy: Upload a ZIP of your built artifacts to the app. Fast and simple for CI/CD. Use az functionapp deployment source config-zip or zipdeploy API. It writes files to the content directory.
- Run-From-Package: Set WEBSITE_RUN_FROM_PACKAGE to a package URL (or 1 for latest). The runtime mounts the package read-only, improving cold start and eliminating file lock issues during deployment. Store the package in Blob Storage with a SAS URL for reproducible rollbacks.
- Deployment slots: Stage and production slots enable zero-downtime swaps with warmup. Slots are supported on Premium and Dedicated plans. Configure slot-specific settings (slot setting flag) for secrets and endpoints to prevent cross-environment leakage. Use preSwap warmup to validate extensions and bindings before traffic moves.
Monitoring with Application Insights:
- Invocation logs: Each function invocation emits structured telemetry including Requests, Traces, Exceptions, and Dependencies. Use ILogger (or equivalent) for structured logs. Operation and correlation IDs tie activity and dependencies across services.
- Live Metrics: Real-time view of throughput, failures, and latency without sampling. Useful for observing deployments, scaling, and hot paths. Filter by function name to isolate issues.
- Failures and reliability: Inspect Exceptions, failed Requests, and dependency failures. Configure alerts on failure rate, FunctionExecutionCount anomalies, or DLQ/poison queue growth. For Storage Queue triggers, monitor the -poison queue; for Service Bus/Event Hubs, monitor dead-letter and checkpoint health. Tune host.json retry policies and backoff to reduce impact of transient errors.
- Distributed tracing: Enable W3C tracing headers to propagate correlation through HTTP and messaging. For Durable Functions, the framework links orchestration and activity telemetry, aiding end-to-end diagnostics. Adjust sampling to balance cost and fidelity.
Operate functions with deployment automation (GitHub Actions/Azure Pipelines), health probes for HTTP endpoints, and autoscale-aware tuning. Keep packages lean, cache clients (e.g., HttpClient, Service Bus client) as static singletons, and validate that binding connection settings resolve at startup to prevent runtime failures.
Practical Problem Scenario
Contoso Retail launches a promotion service that applies discounts in real time when customers add items to their cart. The backend must respond to high-variance traffic with low latency, call a third-party pricing API, and update a Cosmos DB cart document. Operations wants zero-downtime deployments and deep visibility into failures.
- Choose the hosting plan and structure the app
- Use an Azure Functions Premium plan with two pre-warmed instances and VNET integration. Premium eliminates cold starts for latency-sensitive cart interactions and secures outbound traffic to the third-party API via a NAT or firewall in the VNET.
- Create a single Function App with an HTTP-triggered function for the cart endpoint and a Durable Functions orchestrator to coordinate discount retrieval and cart update.
- Implement Durable orchestration for reliability and parallelism
- Orchestrator function: Chain steps to validate input, fan out to fetch discounts for each cart line item in parallel via activity functions, then fan in to aggregate the best price. Durable orchestration ensures deterministic control flow and resilience to restarts.
- Activity functions: One activity calls the third-party API with retry policies; another updates the cart in Cosmos DB via an output binding. Activities encapsulate external IO and can be independently retried without duplicating orchestrator logic.
- Configure triggers and bindings for simplicity
- HTTP trigger with Function auth to accept signed requests from the web frontend. Return 202 with a status URL for long-running carts, or 200 for fast paths.
- Cosmos DB output binding on the activity to upsert the cart document. Binding expressions use the cartId from the HTTP payload to target the correct partition key.
- Use managed identity and identity-based connections for Cosmos DB and Key Vault references, removing secrets from app settings.
- Optimize configuration and deployment
- host.json sets functionTimeout to unlimited (Premium) and configures service mesh-friendly HTTP timeouts. Logging levels are tuned to Information for production and Samples are set for 20% to control cost.
- Use run-from-package with packages stored in a versioned Blob container. Deploy via CI with az functionapp deployment and swap through a staging slot to production for zero-downtime releases. Mark connection strings and API endpoints as slot settings to avoid cross-environment leakage.
- Monitor and operate
- Enable Application Insights and Live Metrics to watch throughput and latency during releases. Configure alerts on HTTP 5xx, dependency failure rate to the pricing API, and increases in Durable function failed orchestrations.
- Use distributed tracing to correlate the HTTP request with Durable orchestration and activity dependencies, expediting root-cause analysis for intermittent third-party issues.
Why these choices:
- Premium plan with pre-warmed instances ensures consistently low latency and supports VNET integration for secure egress.
- Durable Functions provides reliable chaining and fan-out/fan-in with automatic state and retry management for external API calls.
- Bindings reduce boilerplate and enforce consistent, declarative data access to Cosmos DB.
- Run-from-package and slots deliver repeatable, atomic deployments without file lock issues or downtime.
- Application Insights offers real-time observability, correlation, and alerting aligned with operational SLAs.
← Azure App Service and Web Apps · All domains · Azure Storage and Blob Storage →
Practice these questions → · Timed practice on ExamRoll.io →
Pass the whole exam — not just this question
You found this answer. Get every verified question and explanation in one place, and save hours of prep. Free to start.
Pass your exam →