Azure Functions
Azure Functions
│
├── 1. Core Concepts
│ ├── Serverless: No infrastructure management, pay-per-execution.
│ ├── Event-Driven: Code runs in response to events (triggers).
│ ├── Scalability: Automatic scaling based on demand.
│ ├── Cost-Effective: Pay only for what you use (Consumption plan).
│ ├── Function App: The hosting unit for one or more functions.
│ │ ├── Runtime Stack: .NET, Node.js, Python, Java, PowerShell, Custom
Handlers.
│ │ └── Platform: Windows or Linux.
│ ├── Function: A single unit of code (method/script) that performs a specific
task.
│ └── Use Cases:
│ ├── APIs & Microservices
│ ├── Real-time data processing (e.g., IoT)
│ ├── Scheduled tasks (CRON jobs)
│ ├── File processing (e.g., image resizing)
│ ├── Event stream processing
│ └── Orchestrating workflows (Durable Functions)
│
├── 2. Development & Tooling
│ ├── Supported Languages:
│ │ ├── C# (.NET Core, .NET Framework - isolated worker model recommended
for .NET 5+)
│ │ ├── JavaScript (Node.js)
│ │ ├── TypeScript (transpiled to JavaScript)
│ │ ├── Python
│ │ ├── Java
│ │ ├── PowerShell
│ │ └── Custom Handlers (Go, Rust, etc. via HTTP worker)
│ ├── Development Tools:
│ │ ├── Azure Portal (quick edits, management)
│ │ ├── Visual Studio (rich C# development)
│ │ ├── Visual Studio Code (extensions for all languages)
│ │ ├── Azure Functions Core Tools (CLI for local dev, deployment)
│ │ └── Maven/Gradle (for Java)
│ ├── Local Development:
│ │ ├── Core Tools (`func start`)
│ │ ├── Debugging support in IDEs
│ │ ├── `local.settings.json` (local app settings, connection strings)
│ ├── Project Structure:
│ │ ├── `host.json` (global configuration for all functions in a Function App)
│ │ ├── `function.json` (per-function configuration - bindings, triggers, for
non-.NET in-proc)
│ │ ├── Code files (e.g., `.cs`, `.js`, `.py`)
│ │ └── `proxies.json` (for Azure Functions Proxies - simpler API gateway
features)
│ └── Dependency Management:
│ ├── NuGet (C#)
│ ├── npm (JavaScript/TypeScript)
│ ├── pip (Python - `requirements.txt`)
│ ├── Maven/Gradle (Java)
│
├── 3. Triggers & Bindings (Declarative Data Integration)
│ ├── Triggers (What invokes the function):
│ │ ├── HTTP Trigger (webhooks, APIs)
│ │ ├── Timer Trigger (scheduled execution)
│ │ ├── Queue Trigger (Azure Storage Queues, Service Bus Queues)
│ │ ├── Blob Trigger (new/updated blobs in Azure Storage)
│ │ ├── Event Hub Trigger (stream processing)
│ │ ├── Event Grid Trigger (reactive programming to Azure events)
│ │ ├── Cosmos DB Trigger (changes in a Cosmos DB collection - Change Feed)
│ │ ├── Service Bus Topic Trigger
│ │ ├── Durable Functions Orchestration/Activity Trigger
│ │ └── Custom Triggers (less common, via extensions)
│ ├── Bindings (How data flows in/out without SDKs):
│ │ ├── Input Bindings (read data):
│ │ │ ├── Azure Blob Storage
│ │ │ ├── Azure Table Storage
│ │ │ ├── Azure Cosmos DB
│ │ │ ├── Azure SQL (Preview)
│ │ │ └── Custom
│ │ ├── Output Bindings (write data):
│ │ │ ├── Azure Blob Storage
│ │ │ ├── Azure Table Storage
│ │ │ ├── Azure Queue Storage
│ │ │ ├── Azure Service Bus (Queues, Topics)
│ │ │ ├── Azure Cosmos DB
│ │ │ ├── Azure Event Hubs
│ │ │ ├── Azure Event Grid
│ │ │ ├── SendGrid (email)
│ │ │ ├── Twilio (SMS)
│ │ │ ├── Azure SQL (Preview)
│ │ │ └── HTTP (response)
│ │ └── Binding Expressions: Path parameters, dynamic data (`{queueTrigger}`,
`sys.randguid`)
│
├── 4. Hosting & Scaling
│ ├── Hosting Plans:
│ │ ├── Consumption Plan:
│ │ │ ├── Pay-per-execution & resource consumption.
│ │ │ ├── Automatic scaling (even to zero).
│ │ │ ├── Configurable timeout (default 5 min, max 10 min).
│ │ │ └── Cold start potential.
│ │ ├── Premium Plan:
│ │ │ ├── Pre-warmed instances (no cold start).
│ │ │ ├── VNet integration.
│ │ │ ├── Longer run durations (default 30 min, max unlimited -
configurable).
│ │ │ ├── More powerful instances.
│ │ │ └── Predictable pricing based on instance size/count.
│ │ ├── App Service Plan (Dedicated):
│ │ │ ├── Runs on dedicated VMs you manage (like Web Apps).
│ │ │ ├── Predictable cost, potentially underutilized.
│ │ │ ├── "Always On" setting to avoid cold starts.
│ │ │ └── Custom Docker images.
│ │ └── Kubernetes (with KEDA - Kubernetes-based Event Driven Autoscaling):
│ │ ├── Run Functions in your AKS cluster.
│ │ └── Fine-grained control over scaling and environment.
│ ├── Scaling Mechanics:
│ │ ├── Scale Controller: Monitors event sources and load.
│ │ ├── Instance Limits: Per Function App and per region.
│ │ └── Concurrency: `maxConcurrentRequests` (HTTP), `batchSize` (Queues, Event
Hubs).
│ ├── Runtime Versions:
│ │ ├── ~1 (.NET Framework) - Legacy
│ │ ├── ~2 (.NET Core 2.x) - Out of support
│ │ ├── ~3 (.NET Core 3.1, Node 10/12, Python 3.6-3.8, Java 8/11) - Out of
support for .NET Core 3.1, Node 12, Python 3.6
│ │ └── ~4 (.NET 6/7/8 - Isolated Worker, Node 14/16/18, Python 3.7-3.11, Java
8/11/17, PowerShell 7.2) - Current Recommended
│
├── 5. Deployment
│ ├── Methods:
│ │ ├── Zip Deploy (recommended, cross-platform)
│ │ ├── Run From Package (runs from mounted package, read-only file system)
│ │ ├── Visual Studio Publish
│ │ ├── VS Code Azure Functions Extension
│ │ ├── Azure CLI (`az functionapp deployment source config-zip`)
│ │ ├── Azure DevOps (CI/CD pipelines)
│ │ ├── GitHub Actions (CI/CD pipelines)
│ │ ├── Container Registry (for Premium/App Service Plan with custom
containers)
│ │ └── ARM Templates / Bicep (Infrastructure as Code)
│ ├── Deployment Slots:
│ │ ├── Staging, UAT, etc. environments.
│ │ ├── Swap with production (with/without preview).
│ │ ├── Test in production.
│ │ └── Settings can be "slot-specific".
│
├── 6. Monitoring & Diagnostics
│ ├── Azure Monitor:
│ │ ├── Application Insights:
│ │ │ ├── Automatic instrumentation (for supported runtimes).
│ │ │ ├── Live Metrics Stream.
│ │ │ ├── Distributed Tracing (end-to-end transaction view).
│ │ │ ├── Dependencies tracking.
│ │ │ ├── Failures & Exceptions.
│ │ │ ├── Performance analysis.
│ │ │ └── Availability tests.
│ │ ├── Logs:
│ │ │ ├── Function execution logs.
│ │ │ ├── Host logs.
│ │ │ └── Log Analytics (Kusto Query Language - KQL).
│ │ └── Metrics: Execution count, success/failure rate, duration, etc.
│ ├── Built-in Logging:
│ │ ├── `ILogger` (C#)
│ │ ├── `context.log` (JavaScript, Python)
│ │ └── Standard logging libraries (Java, PowerShell)
│ ├── Alerts: Configure alerts based on metrics or log queries.
│ └── Health Checks: (For Premium/App Service Plan) Endpoint to report
application health.
│
├── 7. Security
│ ├── Authentication & Authorization:
│ │ ├── Function Keys (API Keys - System, Function, Host):
│ │ │ ├── `anonymous`, `function`, `admin` authorization levels.
│ │ │ └── Stored in Azure, managed via Portal/API.
│ │ ├── App Service Authentication / Authorization ("Easy Auth"):
│ │ │ ├── Azure Active Directory (AAD)
│ │ │ ├── Microsoft Account
│ │ │ ├── Facebook, Google, Twitter
│ │ ├── API Management Integration:
│ │ │ ├── Advanced policies, rate limiting, quotas, OAuth 2.0.
│ │ ├── Custom Authentication (e.g., validating JWT tokens in code).
│ ├── Networking:
│ │ ├── VNet Integration (Premium, App Service Plan, ASE).
│ │ ├── Private Endpoints (access Function App privately).
│ │ ├── Access Restrictions (IP filtering, service endpoints).
│ │ ├── Hybrid Connections (access on-premises resources).
│ ├── Secrets Management:
│ │ ├── Application Settings (store connection strings, keys).
│ │ ├── Azure Key Vault integration (securely store and access secrets).
│ │ └── Managed Identities:
│ │ ├── System-assigned or User-assigned.
│ │ └── Authenticate to other Azure services (Key Vault, Storage) without
storing credentials in code.
│ ├── Input Validation: Crucial to prevent injection attacks.
│ └── CORS (Cross-Origin Resource Sharing): Configure allowed origins.
│
├── 8. Durable Functions (Stateful Serverless Workflows)
│ ├── Extension for Azure Functions.
│ ├── Use Cases:
│ │ ├── Function chaining.
│ │ ├── Fan-out/Fan-in patterns.
│ │ ├── Async HTTP APIs (long-running operations).
│ │ ├── Human interaction patterns (approval workflows).
│ │ └── Stateful singleton actors (Entities).
│ ├── Core Concepts:
│ │ ├── Orchestrator Functions: Define the workflow in code (C#, JS, Python,
PS).
│ │ ├── Activity Functions: Units of work within the orchestration.
│ │ ├── Entity Functions: Stateful actors for managing small pieces of state.
│ │ ├── Client Functions: Start, manage, query orchestrations.
│ ├── State Management: Uses Azure Storage (Queues, Tables, Blobs) by default.
Netherite/MSSQL also options.
│ └── Checkpointing & Replay: Orchestrator code replays to rebuild local state.
│
├── 9. Best Practices & Patterns
│ ├── Idempotency: Design functions to be safely retried.
│ ├── Single Responsibility: Keep functions small and focused.
│ ├── Statelessness (for most functions, Durable Functions for state).
│ ├── Efficient Connection Management: Use static clients (e.g., `HttpClient`).
│ ├── Error Handling & Retries: Implement robust error handling; leverage built-
in retry policies for triggers.
│ ├── Cold Start Optimization:
│ │ ├── Choose Premium plan.
│ │ ├── Keep package size small.
│ │ ├── Use "Run From Package".
│ │ └── Optimize dependencies.
│ ├── Asynchronous Code: Use `async/await` properly.
│ ├── Testing: Unit tests, Integration tests (with `TestHost` or Core Tools).
│ ├── Configuration Management: Use App Settings, Key Vault.
│ └── Cost Optimization:
│ ├── Choose appropriate hosting plan.
│ ├── Optimize function execution time.
│ ├── Monitor and manage scaling.
│
└── 10. Advanced Topics & Integrations
├── Custom Handlers: Use any language that can run an HTTP server.
├── Azure Functions Proxies (legacy, consider API Management for new designs):
│ └── Simple API gateway to modify requests/responses or route to other
backends.
├── Integration with other Azure Services:
│ ├── API Management (full API gateway)
│ ├── Logic Apps (visual workflow orchestration)
│ ├── Event Grid (decoupled eventing)
│ ├── Azure DevOps / GitHub Actions (CI/CD)
│ └── Application Gateway / Front Door (WAF, SSL offloading, routing)
├── Dependency Injection: Supported in .NET Functions.
├── Isolated Worker Model (.NET): Runs .NET function out-of-process, allowing
more control over dependencies and .NET versions.
└── Resiliency Patterns: Circuit Breaker, Retry, Dead-letter queues.
###################################################################################
############
Azure Functions (Serverless Compute)
###################################################################################
############
Azure Functions is Microsoft's serverless compute service that enables you to run
small pieces of code ("functions") in the cloud without worrying about provisioning
or managing servers. It's event-driven, meaning your code executes in response to a
variety of events, and you typically pay only for the time your code runs
(Consumption plan).
1. Core Concepts
These are the fundamental ideas underpinning Azure Functions.
Serverless:
Description: This doesn't mean there are no servers; rather, you, as the developer,
don't manage them. Azure handles the underlying infrastructure, OS patching,
scaling, and availability. You focus solely on writing your function code.
Implication: Reduced operational overhead, faster development cycles.
Event-Driven:
Description: Functions are designed to execute in response to specific events or
"triggers." These triggers can be an HTTP request, a new message in a queue, a file
upload to blob storage, a timer, or an event from another Azure service.
Implication: Enables reactive architectures where systems respond dynamically to
changes and data.
Scalability:
Description: Azure Functions automatically scales the number of instances running
your code based on the incoming event rate and load. If there are many HTTP
requests or messages in a queue, more function instances will be spun up. If
there's no activity, it can scale down to zero (in the Consumption plan).
Implication: Handles fluctuating workloads efficiently without manual intervention.
Cost-Effective:
Description: Primarily refers to the Consumption plan where you pay for execution
time (in GB-seconds) and the number of executions. If your function isn't running,
you're not paying for compute (though you might pay for associated storage or other
services).
Implication: Can be very economical for workloads with sporadic or unpredictable
traffic.
Function App:
Description: A Function App is the hosting container and management unit for one or
more individual functions. It provides the execution context, runtime stack
(e.g., .NET, Node.js, Python), and platform (Windows or Linux). All functions
within a Function App share the same configuration, scaling plan, and resources.
Implication: Organizes related functions and defines their common environment.
Function:
Description: A single, self-contained unit of code (a method in C#, a function in
JavaScript/Python) designed to perform a specific task. Each function is associated
with a trigger and can have input and output bindings.
Implication: Promotes modular, focused code units.
Use Cases:
APIs & Microservices: Build lightweight HTTP APIs.
Real-time data processing: Process data from IoT Hub or Event Hubs.
Scheduled tasks (CRON jobs): Run code on a schedule using Timer triggers.
File processing: Respond to new blobs in Azure Storage (e.g., image resizing, log
parsing).
Event stream processing: Handle high-throughput event streams.
Orchestrating workflows: Implement complex, stateful workflows with Durable
Functions.
2. Development & Tooling
How you write, test, and manage your Azure Functions code.
Supported Languages:
Description: Azure Functions supports a wide array of popular programming
languages, allowing developers to use their preferred stacks.
C#: Can run in-process (older model, tightly coupled with Functions host) or out-
of-process (isolated worker model, recommended for .NET 5+ for more flexibility,
control over .NET versions, and dependencies).
JavaScript (Node.js): Widely used for event-driven and asynchronous programming.
TypeScript: Provides static typing for JavaScript, transpiled to JS before
deployment.
Python: Popular for data processing, scripting, and machine learning tasks.
Java: For enterprise applications, leveraging the JVM.
PowerShell: Excellent for automation tasks and interacting with Azure resources.
Custom Handlers: A language-agnostic way to run functions. You provide an HTTP
server, and the Functions host forwards requests to it. Enables Go, Rust, etc.
Development Tools:
Azure Portal: Basic code editing, configuration management, monitoring, and quick
testing. Good for simple functions or management tasks.
Visual Studio: Rich, full-featured IDE for C#/.NET development with excellent
debugging, testing, and publishing support for Azure Functions.
Visual Studio Code: Lightweight, extensible editor with powerful Azure Functions
extensions for all supported languages, enabling local development, debugging, and
deployment.
Azure Functions Core Tools: A command-line interface (CLI) essential for local
development, debugging, creating new functions/projects, and deploying Function
Apps, regardless of the IDE.
Maven/Gradle: Build tools for Java developers to manage dependencies and package
their Functions projects.
Local Development:
Description: Azure Functions Core Tools (func start) allow you to run the Functions
runtime locally, simulating the Azure environment. This is crucial for testing and
debugging before deployment.
local.settings.json: This file (not checked into source control) stores local
application settings, connection strings, and other secrets needed for local
development. It mimics the Application Settings in Azure.
Project Structure:
host.json: Global configuration file for all functions within a Function App. It
controls aspects like logging, Application Insights sampling, HTTP behavior,
concurrency limits, and extension bundle versions.
function.json: (Primarily for non-.NET in-process languages or .NET isolated model
using attributes for configuration) Defines a single function, its trigger, input
bindings, and output bindings.
Code files: The actual source code of your functions (e.g., .cs, .js, .py).
proxies.json: (Legacy feature, consider API Management for more complex scenarios)
Defines simple API proxy behavior, allowing you to modify requests/responses or
route to different backends.
Dependency Management:
Description: Each language has its standard way of managing external libraries and
packages:
NuGet: For C# (.NET) projects.
npm (package.json): For JavaScript/TypeScript (Node.js) projects.
pip (requirements.txt): For Python projects.
Maven (pom.xml) / Gradle (build.gradle): For Java projects.
3. Triggers & Bindings (Declarative Data Integration)
The mechanism that starts your function and how it interacts with data sources.
Overall Concept: Triggers and bindings provide a declarative way to connect your
function to other services. Instead of writing boilerplate code to connect to a
queue, read a blob, or send an email, you define these connections in configuration
(e.g., function.json or attributes in C#), and the Functions runtime handles the
data flow.
Triggers (What invokes the function):
HTTP Trigger: Executes in response to an HTTP request (e.g., from a browser, mobile
app, or another service). Ideal for building APIs.
Timer Trigger: Executes on a CRON schedule (e.g., "run every 5 minutes" or "run at
2 AM every day").
Queue Trigger: Executes when a new message is added to an Azure Storage Queue or
Azure Service Bus Queue.
Blob Trigger: Executes when a new or updated blob (file) is detected in Azure Blob
Storage.
Event Hub Trigger: Executes in response to events published to an Azure Event Hub,
suitable for high-throughput event stream processing.
Event Grid Trigger: Executes in response to events from various Azure services or
custom events published to Azure Event Grid, enabling reactive programming.
Cosmos DB Trigger: Executes when documents are created or modified in an Azure
Cosmos DB collection (leveraging the Change Feed).
Service Bus Topic Trigger: Executes when a new message arrives on a Service Bus
Topic subscription.
Durable Functions Orchestration/Activity Trigger: Specific triggers used within
Durable Functions workflows.
Custom Triggers: Less common, can be developed for specific needs via extensions.
Bindings (How data flows in/out without SDKs):
Input Bindings: Provide a declarative way to read data from external sources and
make it available to your function code as parameters. Examples:
Azure Blob Storage: Read a blob based on a path.
Azure Table Storage: Read an entity or a set of entities.
Azure Cosmos DB: Read a document.
Azure SQL: Read data from a SQL database.
Output Bindings: Provide a declarative way to write data from your function to
external services. The function's return value or specific output parameters are
sent to the bound service. Examples:
Azure Blob Storage: Write data to a new blob.
Azure Table Storage: Write new entities.
Azure Queue Storage / Service Bus: Send messages.
Azure Cosmos DB: Write documents.
Azure Event Hubs / Event Grid: Publish events.
SendGrid / Twilio: Send emails or SMS messages.
HTTP: Send an HTTP response (this is a special output binding for HTTP triggers).
Binding Expressions: Allow you to use values from the trigger payload or other
sources to dynamically configure binding paths or properties. For example,
{queueTrigger} in a blob path binding would use the content of the queue message as
the blob name. sys.randguid generates a random GUID.
4. Hosting & Scaling
Where and how your Function App runs and scales.
Hosting Plans:
Consumption Plan:
Description: Truly serverless. You pay per execution and for resource consumption
(memory/CPU time). Scales automatically from zero to many instances based on load.
Pros: Most cost-effective for sporadic workloads, no cost when idle (for compute).
Cons: Potential for "cold starts" (a delay for the first request after a period of
inactivity as an instance needs to be provisioned/warmed up). Timeout limits
(default 5 min, max 10 min).
Premium Plan:
Description: Offers features of the Consumption plan (event-driven scaling) but
with enhanced performance and capabilities like pre-warmed instances (to avoid cold
starts), VNet integration, longer run durations (default 30 min, configurable up to
unlimited theoretically, but practically constrained by host restarts), and more
powerful instance SKUs.
Pros: No cold starts, more compute power, VNet access, longer execution times.
Cons: More expensive than Consumption, as you pay for pre-warmed instances even
when idle.
App Service Plan (Dedicated):
Description: Runs your Function App on dedicated Virtual Machines (VMs) that you
select (same as Azure Web Apps). You pay for the VMs regardless of whether your
functions are running.
Pros: Predictable costs, "Always On" setting to keep instances warm, custom Docker
images, can use underutilized VMs from existing App Service Plans.
Cons: Can be less cost-effective if workloads are very spiky; you manage the
scaling rules more directly.
Kubernetes (with KEDA):
Description: Kubernetes-based Event Driven Autoscaling (KEDA) allows you to run
Azure Functions (as containers) in your Azure Kubernetes Service (AKS) cluster or
any Kubernetes cluster. KEDA scales your function containers based on event
sources.
Pros: Fine-grained control, leverage existing Kubernetes investments and tooling.
Cons: More operational overhead as you manage the Kubernetes cluster.
Scaling Mechanics:
Scale Controller: A component in Azure that monitors event sources (e.g., queue
length, HTTP traffic) and decides when to scale your Function App instances up or
down.
Instance Limits: There are limits on the maximum number of instances a Function App
can scale to, which vary by plan and region.
Concurrency: Configuration settings like maxConcurrentRequests (for HTTP triggers)
or batchSize and newBatchThreshold (for queue/event hub triggers) influence how
many concurrent executions a single instance can handle, which in turn affects
scaling decisions.
Runtime Versions:
Description: Azure Functions has evolved with different runtime versions (~1, ~2,
~3, ~4), each supporting different versions of underlying frameworks (like .NET)
and languages. It's crucial to use a supported runtime version for security,
performance, and feature updates.
Current Recommended: ~4 (supports .NET 6/7/8 in isolated worker model, newer
Node.js, Python, Java, PowerShell versions). Older versions are progressively
deprecated or out of support.
5. Deployment
How you get your function code into Azure.
Methods:
Zip Deploy: The recommended and most common method. You package your Function App
project (code and dependencies) into a .zip file and deploy it. The func azure
functionapp publish <AppName> command uses this.
Run From Package: A variation of Zip Deploy where the Function App runs directly
from the deployed package file (mounted as read-only). Improves cold start times
and deployment reliability.
Visual Studio Publish: Right-click publish from Visual Studio, which often uses Zip
Deploy or Web Deploy under the hood.
VS Code Azure Functions Extension: Provides commands to deploy your project
directly from VS Code.
Azure CLI: Using commands like az functionapp deployment source config-zip.
Azure DevOps / GitHub Actions: Automate your build and deployment process through
CI/CD pipelines. This is the best practice for production applications.
Container Registry: If using Premium or App Service Plan with custom Docker
containers, you deploy by pushing your image to a registry (like Azure Container
Registry) and configuring the Function App to pull from it.
ARM Templates / Bicep: Infrastructure as Code (IaC) tools to define and deploy not
just the Function App infrastructure but can also include code deployment steps.
Deployment Slots:
Description: Feature available in Standard tier App Service Plans, Premium plan,
and Dedicated plan. Allows you to deploy new versions of your Function App to a
non-production "slot" (e.g., "staging").
Benefits:
Test the new version in a production-like environment without impacting the live
version.
Perform a "swap" operation, which warms up the new version in the slot and then
seamlessly switches traffic to it with minimal downtime.
Rollback easily by swapping back if issues are found.
Slot-Specific Settings: Application settings and connection strings can be marked
as "slot-specific," meaning they don't move with the code during a swap. Useful for
different database connection strings for staging vs. production.
6. Monitoring & Diagnostics
Understanding how your functions are performing and troubleshooting issues.
Azure Monitor: The central Azure service for collecting, analyzing, and acting on
telemetry from your Azure resources, including Azure Functions.
Application Insights:
Description: A powerful Application Performance Management (APM) service deeply
integrated with Azure Functions. It automatically collects telemetry like request
rates, response times, failure rates, and dependencies.
Features: Live Metrics Stream (real-time view), Distributed Tracing (visualize end-
to-end flow of requests across services), dependency tracking (calls to databases,
HTTP APIs), failure analysis, performance profiling.
Logs:
Function execution logs: Logs generated by your function code (ILogger,
context.log) and by the Functions runtime about individual executions.
Host logs: Logs from the Functions host process itself.
Log Analytics: Logs can be sent to a Log Analytics workspace where you can query
them using Kusto Query Language (KQL) for advanced analysis and dashboarding.
Metrics: Pre-defined metrics like Function Execution Count, Success/Failure Rate,
Execution Duration, Memory Working Set, etc., are available for monitoring and
alerting.
Built-in Logging:
Description: Functions runtimes provide built-in logging mechanisms.
ILogger (C#): Standard .NET logging interface.
context.log (JavaScript, Python): Context object has methods for logging.
Standard logging libraries (Java, PowerShell) are also supported. These logs are
typically captured by Application Insights.
Alerts:
Description: You can configure alerts in Azure Monitor based on metrics (e.g.,
"alert if failure rate > 5%") or log query results (e.g., "alert if a specific
error message appears"). Alerts can trigger notifications (email, SMS, webhook) or
automated actions.
Health Checks:
Description: (For Premium/App Service Plan) You can configure a health check path
in your Function App. Azure will periodically ping this endpoint, and if it doesn't
respond correctly, the instance can be taken out of rotation. Useful for load
balancers.
7. Security
Protecting your functions and their data.
Authentication & Authorization:
Function Keys (API Keys):
Description: Simple secret keys used to grant access to HTTP-triggered functions.
Levels:
anonymous: No key required.
function: A function-specific key or a host key is required.
admin: The master host key is required (grants access to all functions in the app).
Management: Managed in Azure, can be rotated. Best for service-to-service
communication where more robust auth isn't feasible.
App Service Authentication / Authorization ("Easy Auth"):
Description: A platform feature that integrates identity providers directly into
your Function App without code changes.
Providers: Azure Active Directory (AAD), Microsoft Account, Facebook, Google,
Twitter.
Functionality: Handles token validation, session management. User identity
information is passed to your function via request headers.
API Management Integration:
Description: Place Azure API Management in front of your Azure Functions to provide
a robust API gateway.
Benefits: Advanced policies (rate limiting, quotas, request/response
transformation), OAuth 2.0/OpenID Connect validation, subscription keys, developer
portal.
Custom Authentication:
Description: Implement authentication logic directly within your function code,
e.g., validating JWT tokens passed in the Authorization header.
Networking:
VNet Integration: (Premium, App Service Plan, ASE) Allows your Function App to
access resources within an Azure Virtual Network (VNet) or on-premises (via
VPN/ExpressRoute).
Private Endpoints: Allows clients in your VNet to securely access your Function App
via a private IP address from your VNet, without exposing it to the public
internet.
Access Restrictions: IP filtering (allow/deny specific IP addresses or ranges) and
service endpoint restrictions (allow traffic only from specific VNets/subnets).
Hybrid Connections: (Requires App Service Plan) Allows access to on-premises
resources without a full VNet integration.
Secrets Management:
Application Settings: Key-value pairs configured for your Function App. Good for
non-sensitive configuration, but connection strings and API keys here are encrypted
at rest by Azure.
Azure Key Vault integration: The recommended way to store and manage sensitive
secrets (API keys, connection strings, certificates). Your Function App can
reference secrets in Key Vault directly in its Application Settings (e.g.,
@Microsoft.KeyVault(SecretUri=...)).
Managed Identities:
Description: An Azure AD identity automatically managed by Azure for your Function
App.
Types: System-assigned (tied to the lifecycle of the Function App) or User-assigned
(standalone Azure resource).
Benefit: Allows your Function App to authenticate to other Azure services that
support AAD authentication (like Key Vault, Storage, SQL Database) without needing
to store any credentials (like connection strings or keys) in your application
settings or code.
Input Validation:
Description: Always validate any data received by your function (from HTTP
requests, queue messages, etc.) to prevent injection attacks, ensure data
integrity, and handle malformed inputs gracefully.
CORS (Cross-Origin Resource Sharing):
Description: Configure which other domains are allowed to make requests to your
HTTP-triggered functions. This is a browser security mechanism.
8. Durable Functions (Stateful Serverless Workflows)
An extension for building long-running, stateful orchestrations in a serverless
way.
Description: Durable Functions allow you to write stateful workflows
(orchestrations) using ordinary code. It manages state, checkpoints, and restarts
for you, making it easier to implement complex patterns.
Use Cases:
Function chaining: Execute a sequence of functions in a specific order.
Fan-out/Fan-in: Execute multiple functions in parallel and then aggregate their
results.
Async HTTP APIs: For long-running operations that can't complete within a single
HTTP request timeout. The client gets an immediate response with a status URL to
check later.
Human interaction patterns: Workflows that require human input (e.g., approval
processes) and can pause for extended periods.
Stateful singleton actors (Entities): Model stateful objects that can be called and
updated.
Core Concepts:
Orchestrator Functions: Define the workflow logic using code (C#, JS, Python, PS).
They can call activity functions, other orchestrations, wait for external events,
and manage state. Orchestrator code must be deterministic.
Activity Functions: The actual units of work within an orchestration. They perform
tasks like database calls, API requests, or computations. They can be regular Azure
Functions.
Entity Functions: (Actor model) Define operations for reading and updating small
pieces of state, known as durable entities.
Client Functions: Regular Azure Functions (often HTTP-triggered) that start new
orchestrations, query their status, or send events to them.
State Management:
Description: Durable Functions automatically persist the execution state of
orchestrations. By default, it uses Azure Storage (Queues for messages, Tables for
history/state, Blobs for large messages/leases). Netherite (uses Event Hubs and
Azure Cache for Redis/FASTER) and MSSQL are alternative storage providers for
higher performance scenarios.
Checkpointing & Replay:
Description: Orchestrator functions replay their execution from the beginning
whenever they "wake up" (e.g., an activity completes, a timer fires, or an external
event is received). They use the persisted history to quickly skip over already
completed steps and rebuild their local state. This makes orchestrations resilient
to process failures.
9. Best Practices & Patterns
Guidelines for building robust, efficient, and maintainable Azure Functions.
Idempotency: Design functions so that executing them multiple times with the same
input produces the same result without unintended side effects. Important because
triggers (like queues) might deliver a message more than once.
Single Responsibility: Keep functions small, focused, and doing one thing well.
This improves testability, maintainability, and reusability.
Statelessness (for most functions): Standard functions should ideally be stateless.
If state is needed across executions, use external stores (like Azure Storage,
Cosmos DB) or leverage Durable Functions for workflow state.
Efficient Connection Management: For services like HttpClient, database clients,
etc., create static or singleton instances and reuse them across function
executions within the same instance to avoid socket exhaustion and improve
performance.
Error Handling & Retries: Implement robust error handling (try-catch blocks).
Leverage built-in retry policies for triggers (e.g., queue triggers automatically
retry on failure) or implement custom retry logic where needed (e.g., with Polly
library in .NET). Use dead-letter queues for messages that consistently fail.
Cold Start Optimization:
Choose Premium plan: Eliminates cold starts with pre-warmed instances.
Keep package size small: Smaller deployment packages load faster.
Use "Run From Package": Can improve load times.
Optimize dependencies: Only include necessary libraries. For .NET, compile in
Release mode and consider ReadyToRun compilation.
Asynchronous Code: Use async/await properly in languages that support it (C#, JS,
Python) to avoid blocking threads and improve throughput, especially for I/O-bound
operations.
Testing: Write unit tests for your function logic. For integration tests, you can
use the TestHost (for .NET in-process) or run locally with Azure Functions Core
Tools and test against actual triggers/bindings with mock or real services.
Configuration Management: Use Application Settings for configuration. Store
sensitive data in Azure Key Vault and reference it from App Settings.
Cost Optimization:
Choose the most appropriate hosting plan for your workload.
Optimize function execution time and memory usage.
Monitor and fine-tune scaling behavior to avoid over-provisioning.
10. Advanced Topics & Integrations
More specialized features and how Functions fit into the broader Azure ecosystem.
Custom Handlers:
Description: Allows you to use languages or runtimes not natively supported by
Azure Functions (e.g., Go, Rust, PHP, Deno). Your code runs as an HTTP server, and
the Functions host forwards events to it as HTTP requests.
Azure Functions Proxies:
Description: (Legacy feature, generally recommend Azure API Management for new
designs). A way to create a lightweight API facade on top of your Function App or
other backend services. Allows simple request/response modifications and routing.
Integration with other Azure Services:
API Management: A fully-featured API gateway to manage, secure, and publish your
Function APIs.
Logic Apps: Visually design and orchestrate workflows that can call Azure Functions
as part of their steps. Good for integrating disparate systems.
Event Grid: A fully managed event routing service. Functions can subscribe to Event
Grid topics to react to events from various Azure services or custom applications.
Azure DevOps / GitHub Actions: Set up robust CI/CD pipelines for automated
building, testing, and deployment of your Function Apps.
Application Gateway / Front Door: Azure services that can provide Web Application
Firewall (WAF), SSL offloading, path-based routing, and global load balancing in
front of your Function Apps (especially HTTP-triggered ones).
Dependency Injection:
Description: Supported in .NET Functions (both in-process and isolated worker
model). Allows you to register and resolve services (like HttpClient, custom
services, database contexts) in a structured way, promoting better code
organization and testability.
Isolated Worker Model (.NET):
Description: For .NET Functions, this model runs your function code in a separate
worker process from the Functions host runtime.
Benefits: Allows use of any .NET version (e.g., .NET 7, .NET 8) independent of the
Functions host, full control over dependencies and middleware, and aligns more
closely with standard ASP.NET Core development. This is the recommended model for
new .NET Functions.
Resiliency Patterns:
Description: Implementing patterns to make your functions more robust against
transient failures.
Examples: Circuit Breaker (stop calling a failing service for a period), Retry
(with exponential backoff), Dead-letter queues (for messages that can't be
processed after several attempts). Libraries like Polly (for .NET) can help
implement these.
This detailed breakdown covers the key aspects of Azure Functions, providing a
solid foundation for understanding and utilizing this powerful serverless platform.