This chapter covers Azure Functions, a serverless compute service that allows you to run event-driven code without managing infrastructure. For the AZ-204 exam, Azure Functions is a major topic, appearing in approximately 15-20% of questions across compute, triggers, bindings, Durable Functions, and security. You must understand hosting plans, scaling behaviors, binding types, and how to secure and monitor function apps. This chapter provides the deep, mechanistic knowledge required to answer exam questions confidently.
Jump to a section
Imagine a pop-up restaurant kitchen that only fires up its stoves when a customer places an order. The kitchen has a menu (the function app) with several dishes (functions). When a customer calls in an order (HTTP trigger), the host (the Azure Functions host) notes the order details and starts a timer. The host then wakes up a chef (a function instance) from standby, hands them the recipe (binding configuration) and ingredients (input bindings), and the chef cooks the dish. If another order for the same dish arrives while the first chef is still cooking, the host can either wake up another chef (scale out) or queue the order (if concurrency limits are set). Once the dish is ready, the chef plates it (output binding) and hands it to a server (the host returns the HTTP response). The chef then cleans up (instance is deallocated after idle timeout, default 5 minutes in Consumption plan) and goes back to standby. If no orders come for a while, the host turns off the stoves entirely (scales to zero). The key mechanic is that the kitchen has no permanent staff—chefs are hired (instances created) only when needed and let go (deallocated) when idle, which saves cost but means the first order after a quiet period takes longer (cold start) because the host must wake up a chef and find the recipe from cold storage (read function code from Azure Files).
What is Azure Functions and Why It Exists
Azure Functions is a serverless compute service that executes code in response to events. It abstracts away the underlying infrastructure, allowing developers to focus on business logic. The service automatically scales based on demand, and you only pay for the compute resources consumed during execution. This model is ideal for workloads with variable or unpredictable traffic, such as processing file uploads, responding to HTTP requests, or handling queue messages.
How Azure Functions Works Internally
At its core, Azure Functions runs on the Azure Functions host, a runtime that manages function execution. When a trigger event occurs (e.g., an HTTP request, a new queue message), the host receives the event and invokes the appropriate function. The host handles: - Scaling: In the Consumption and Elastic Premium plans, the host monitors the number of events waiting to be processed. It uses a scale controller to add or remove function app instances. The scale controller checks every 10 seconds for the Consumption plan, and can add up to 200 instances (default) per function app. - Binding: The host reads the function.json or attributes in code to determine input and output bindings. It creates and manages connections to Azure services (e.g., Blob Storage, Service Bus) automatically. - Lifecycle: On first invocation after a period of inactivity, the host experiences a cold start—loading the function code from Azure Files into memory, which adds latency (typically 0.5-5 seconds for C#, longer for Java). Once loaded, subsequent invocations are warm and fast.
Key Components, Values, Defaults, and Timers
- Hosting Plans: - Consumption Plan: Scales automatically, scales to zero when idle. Billed per execution (number of executions × execution time × memory consumption). Default memory: 1,536 MB. Execution timeout: 5 minutes (default), max 10 minutes. Cold start latency is highest. - Elastic Premium Plan: Pre-warmed instances reduce cold starts. Scales automatically but not to zero. Billed per second of instance usage. Execution timeout: 30 minutes (default), max unlimited (60 minutes for Linux). Supports virtual network integration. - Dedicated (App Service) Plan: Runs on VMs you manage. No automatic scaling to zero. Billed for the VM. Execution timeout: 30 minutes (default), can be increased. Best for predictable, high-throughput workloads.
Triggers: The event that invokes a function. Common triggers:
HTTPTrigger: Responds to HTTP requests. Supports authorization levels: anonymous, function, admin.
BlobTrigger: Fires when a blob is created/updated in Azure Blob Storage. Uses a poison blob queue for failed processing.
QueueTrigger: Fires when a message is added to an Azure Storage Queue. Supports batch processing.
TimerTrigger: Fires on a schedule using CRON expressions.
ServiceBusTrigger: Fires when a message arrives in a Service Bus queue or topic.
EventGridTrigger: Fires when an Event Grid event is received.
Bindings: Connections to other Azure services. Input bindings provide data, output bindings send data. Bindings are defined in function.json or via attributes (e.g., [Blob("container/{name}")]). You can mix input and output bindings in one function.
- Host Configuration (host.json): Controls global behaviors:
- maxBatches: For queue triggers, number of messages to process simultaneously (default 16).
- batchSize: For queue triggers, number of messages to retrieve at once (default 16).
- functionTimeout: Timeout for function execution (default 00:05:00 for Consumption, 00:30:00 for Premium/Dedicated).
- queues.maxDequeueCount: Number of times to retry a queue message before moving to poison queue (default 5).
- Application Settings: Configure environment variables. Key settings:
- AzureWebJobsStorage: Connection string for Azure Storage account used by the Functions runtime.
- WEBSITE_RUN_FROM_PACKAGE: Set to 1 to run from a deployment package (reduces cold start).
- FUNCTIONS_WORKER_RUNTIME: Language stack (dotnet, node, python, java, powershell).
Configuration and Verification Commands
Create a function app:
az functionapp create --resource-group myGroup --consumption-plan-location westus --name myFuncApp --storage-account mystorage --runtime dotnetDeploy code:
func azure functionapp publish myFuncAppView logs:
az functionapp logs tail --name myFuncApp --resource-group myGroupCheck application settings:
az functionapp config appsettings list --name myFuncApp --resource-group myGroupHow Azure Functions Interacts with Related Technologies
Azure Logic Apps: Both are serverless, but Logic Apps are workflow-oriented with a designer, while Functions are code-first. Functions can be called from Logic Apps via the Azure Functions connector.
Azure Event Grid: Functions can be triggered by Event Grid events, enabling reactive architectures. Event Grid is a fully managed event routing service.
Azure Durable Functions: An extension that allows stateful workflows in Functions. It manages state, checkpoints, and replays automatically.
Azure API Management: Can proxy HTTP-triggered functions to add API management features like rate limiting, authentication, and versioning.
Azure Monitor: Provides metrics and logs for function apps. You can set alerts based on execution count, failure rate, and duration.
Security Considerations
Authorization Keys: HTTP-triggered functions require an authorization key (function or admin) unless set to anonymous. Keys are stored in Azure Blob Storage and can be managed via the portal or Azure CLI.
Managed Identities: Use system-assigned or user-assigned managed identities to access Azure resources without storing credentials.
Network Security: Premium plan supports VNet integration. Consumption plan does not support VNet integration except for outbound traffic configuration.
Environment Variables: Store connection strings and secrets in application settings, not in code. Use Key Vault references for sensitive values.
Create a Function App
Use the Azure CLI, portal, or PowerShell to create a function app. You must specify a hosting plan (Consumption, Premium, or Dedicated), a storage account (required for runtime operations), and a runtime stack. The function app is the container that holds one or more functions. The storage account stores function code (for Consumption plan), execution logs, and state information. The runtime stack determines the language and version (e.g., dotnet, node, python). After creation, you configure application settings like connection strings and runtime settings.
Define a Function with Trigger and Bindings
Create a function using a template (e.g., HTTP trigger, Blob trigger). In C#, you use attributes like `[HttpTrigger]` and `[Blob("container/{name}")]`. In other languages, you configure function.json. The trigger defines the event that invokes the function. Bindings define how the function reads input and writes output. For example, an HTTP trigger can use an input binding to read a blob and an output binding to write to a queue. The binding configuration includes connection strings (set in app settings) and paths.
Write Function Code
Implement the function logic. The function receives a context object (e.g., `ExecutionContext` in C#, `context` in Node.js) that provides access to bindings, logs, and cancellation tokens. You can use dependency injection for services (e.g., ILogger, HttpClient). The code should be stateless and idempotent to handle retries. Use async/await for I/O operations. Avoid long-running operations that exceed the function timeout.
Deploy the Function App
Deploy code using `func azure functionapp publish`, Git deployment, or CI/CD pipelines. The deployment package is uploaded to Azure. For Consumption plan, the code is stored in Azure Files. For Premium/Dedicated, it can be deployed via ZIP deploy or run from a package. After deployment, the function app restarts to pick up the new code. You can verify deployment by invoking the function and checking logs.
Monitor and Scale
Monitor function execution using Application Insights or the Azure portal. Set up alerts for failures or high latency. The scale controller automatically adjusts the number of instances based on the number of events waiting to be processed. In Consumption plan, the scale controller checks every 10 seconds and can scale up to 200 instances per function app. For Premium plan, you can configure minimum and maximum instance counts. Use the 'Scale' blade in the portal to view current instance count and scale decisions.
Enterprise Scenario 1: Image Processing Pipeline
A media company uploads thousands of images daily to Azure Blob Storage. They need to generate thumbnails and apply watermarks. They deploy a BlobTrigger function that processes each new blob. The function reads the image, resizes it, adds a watermark, and writes the output to another container. Using the Consumption plan, they pay only when images are uploaded. During peak hours, the function scales out to hundreds of instances, processing images in parallel. They set the maxDequeueCount to 3 to retry failed processing, and use a poison blob queue to log failures. They monitor with Application Insights to track processing time and failure rates. A common misconfiguration is not setting the AzureWebJobsStorage connection string correctly, causing the function to fail silently.
Enterprise Scenario 2: Real-Time Order Processing
An e-commerce platform processes orders from a Service Bus queue. A ServiceBusTrigger function reads each order message, validates it, updates inventory, and sends a confirmation email via SendGrid. They use the Premium plan to avoid cold starts and ensure low latency. They configure a maximum instance count of 20 to control costs. They use managed identity to access the Service Bus and Azure SQL database, eliminating connection strings. They implement retry logic with exponential backoff for transient failures. The function uses output bindings to write to a database and send email. A common issue is hitting the Service Bus session lock timeout (default 1 minute) if the function takes too long, so they set the function timeout to 5 minutes and use maxAutoRenewDuration.
Enterprise Scenario 3: Scheduled Data Aggregation
A financial analytics company runs a TimerTrigger function every hour to aggregate market data from an external API and store results in Cosmos DB. They use the Consumption plan because the workload is predictable and low volume. The function uses input bindings to read configuration from Blob Storage and output bindings to write to Cosmos DB. They use Application Insights to monitor execution duration and set an alert if it exceeds 4 minutes (near the 5-minute timeout). They discovered that the function occasionally fails due to a transient API error, so they added retry logic with a circuit breaker pattern. A pitfall is the TimerTrigger's CRON expression using UTC time, which can cause off-by-one errors if not accounting for daylight saving.
Exam Focus for AZ-204
The AZ-204 exam tests Azure Functions under objective 'Implement Azure Functions' (weighted heavily). Key areas:
Hosting Plans: Know the differences in scaling, billing, and cold start. Common wrong answer: 'Consumption plan supports VNet integration.' It does not; only Premium and Dedicated do. Another: 'Dedicated plan scales to zero.' No, it does not; you pay for the VM even when idle.
Triggers and Bindings: You must know which triggers are available and their configuration. Trap: 'BlobTrigger supports all blob storage account types.' Actually, BlobTrigger only works with general-purpose v2 and BlobStorage accounts, not general-purpose v1. Another: 'QueueTrigger automatically deletes messages after processing.' True, but only if the function completes successfully; if it fails, the message is returned to the queue after the visibility timeout (default 30 seconds).
Durable Functions: Understand the three function types: Orchestrator, Activity, and Client. Common wrong answer: 'Orchestrator functions can contain I/O operations directly.' They cannot; all I/O must be through activity functions. Another: 'Durable Functions are only available in the Consumption plan.' They are available in all plans.
Security: Know how to use authorization keys and managed identities. Exam loves: 'What is the default authorization level for an HTTP trigger?' Answer: Function (requires a function-level key). Another: 'How to configure managed identity for a function app?' Use az functionapp identity assign.
Monitoring: Application Insights integration is automatic when you create a function app. Know how to query logs and set alerts. Common wrong answer: 'You must manually add the Application Insights SDK.' Actually, it's added automatically for most languages.
Numbers to Memorize: Consumption plan timeout: 5 minutes (max 10). Premium plan timeout: 30 minutes (unlimited for Linux). Scale controller check interval: every 10 seconds for Consumption. Max instances: 200 per function app (Consumption). Default batch size for queue trigger: 16. Default max dequeue count: 5.
Edge Cases: TimerTrigger uses CRON expressions in UTC. If a function takes longer than the schedule interval, the next scheduled run is skipped until the current one completes. For blob triggers, the function may receive a blob that is still being written (partial read); use a lease or check the blob's LastModified property.
Eliminating Wrong Answers: If a question mentions 'scaling to zero', it's Consumption. If it mentions 'VNet integration', it's Premium or Dedicated. If it mentions 'pre-warmed instances', it's Premium. If it mentions 'pay per execution', it's Consumption. If it mentions 'always on', it's Dedicated.
Azure Functions supports three hosting plans: Consumption (scale to zero, pay per execution), Premium (pre-warmed, VNet, unlimited timeout), and Dedicated (always on, predictable pricing).
The default execution timeout is 5 minutes for Consumption, 30 minutes for Premium/Dedicated. Can be increased to 10 minutes for Consumption, unlimited for Premium (Linux).
Triggers define the event that invokes a function: HTTP, Blob, Queue, Timer, Service Bus, Event Grid, etc.
Bindings connect functions to Azure services declaratively; input bindings read data, output bindings write data.
Durable Functions enable stateful workflows: Orchestrator functions coordinate activity functions; state is persisted and replayed.
Application Insights is automatically integrated for monitoring; use it to track executions, failures, and performance.
Managed identities allow secure access to Azure resources without storing credentials in code or settings.
Cold start occurs when a function app is idle and then invoked; Premium plan reduces cold starts with pre-warmed instances.
The scale controller for Consumption plan checks every 10 seconds and can scale up to 200 instances per function app.
BlobTrigger only works with GPv2 and BlobStorage accounts; requires a queue for poison blob handling.
TimerTrigger uses CRON expressions in UTC; if execution exceeds interval, next scheduled run is skipped.
Authorization keys for HTTP triggers: function-level keys are specific to a function, admin-level keys apply to all functions in the app.
These come up on the exam all the time. Here's how to tell them apart.
Consumption Plan
Scales to zero when idle; no cost when not running.
Cold starts on first invocation after idle period.
Maximum execution timeout: 5 minutes (default), can be increased to 10 minutes.
No VNet integration (except for outbound traffic).
Billed per execution (number of executions × execution time × memory).
Premium Plan
Always at least one warm instance; no scale to zero.
Pre-warmed instances reduce cold start latency.
Maximum execution timeout: 30 minutes (default), unlimited for Linux.
Supports VNet integration (inbound and outbound).
Billed per second of instance usage (minimum 1 minute).
HTTPTrigger
Invoked by an HTTP request (GET, POST, etc.).
Supports authorization keys (anonymous, function, admin).
No built-in retry; must implement in code.
Returns an HTTP response (status code and body).
Commonly used for REST APIs and webhooks.
QueueTrigger
Invoked when a message is added to an Azure Storage Queue.
No authorization concept; relies on queue permissions.
Built-in retry: up to `maxDequeueCount` times (default 5).
No direct response; output bindings for results.
Commonly used for background processing and async tasks.
Mistake
Azure Functions always runs on Linux.
Correct
Azure Functions supports both Windows and Linux. The hosting plan determines the OS. Consumption plan runs on Windows. Premium and Dedicated plans support both Windows and Linux. You can choose the OS when creating the function app.
Mistake
All triggers support automatic retries with exponential backoff.
Correct
Only some triggers have built-in retry policies. For example, QueueTrigger retries up to `maxDequeueCount` times (default 5) with a visibility timeout. HTTPTrigger does not automatically retry; you must implement retry logic in your code. BlobTrigger uses a poison queue for failed blobs.
Mistake
You can use any Azure storage account for BlobTrigger.
Correct
BlobTrigger only works with general-purpose v2 (GPv2) and BlobStorage accounts. It does not work with general-purpose v1 (GPv1) or premium storage accounts. You also need a queue storage account for the poison queue.
Mistake
Durable Functions can only be used with HTTP triggers.
Correct
Durable Functions can be triggered by any trigger type (HTTP, Queue, Timer, etc.). The client function that starts the orchestration can be any trigger. The orchestrator and activity functions are triggered by the Durable Functions extension itself.
Mistake
The Consumption plan supports always-on execution.
Correct
The Consumption plan scales to zero when idle. There is no 'always on' setting. For continuous execution, use the Premium plan (which keeps instances warm) or the Dedicated plan (which runs on a VM).
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
The Consumption plan scales to zero when idle and you pay per execution. It has a maximum execution timeout of 10 minutes and experiences cold starts. The Premium plan keeps at least one instance warm, supports VNet integration, and allows unlimited execution time (Linux). You pay per second of instance usage. For exam: remember that Premium reduces cold starts and supports VNet; Consumption is cheaper for sporadic workloads.
For queue-triggered functions, retries are automatic: messages are returned to the queue after a visibility timeout (default 30 seconds) and reprocessed up to `maxDequeueCount` times (default 5). For HTTP triggers, you must implement retry logic in your code (e.g., using Polly). Durable Functions have built-in retry policies for activity functions. Exam tip: know that BlobTrigger uses a poison queue for failed blobs.
Yes, you can use input and output bindings for Azure SQL (preview) or use the SqlClient library directly. For secure access, use managed identities. In the exam, remember that bindings simplify code but you can always use the SDK for more control.
A cold start occurs when a function app is invoked after being idle, requiring the runtime to load the function code into memory. It adds latency (typically 0.5-5 seconds). To reduce cold starts, use the Premium plan (pre-warmed instances), set `WEBSITE_RUN_FROM_PACKAGE` to 1 (run from deployment package), or use the Dedicated plan (always on).
Set the authorization level to 'function' or 'admin' (default is 'function'). Use function keys for specific functions or admin keys for all functions. You can also use Azure AD authentication, managed identities, or API Management for additional security. Exam tip: know that the 'anonymous' level requires no key, so it's public.
The default maximum is 200 instances per function app. This can be increased by contacting support. The scale controller checks every 10 seconds to add or remove instances. Exam tip: this is a common number to remember for scaling questions.
Yes, Durable Functions are supported in all hosting plans (Consumption, Premium, Dedicated). However, in the Consumption plan, you may experience cold starts for orchestrator functions. The Premium plan is recommended for production Durable Functions due to lower latency.
You've just covered Azure Functions Development — now see how well it sticks with free AZ-204 practice questions. Full explanations included, no account needed.
Done with this chapter?