Introduction
Azure Functions is Microsoft’s serverless computing service that enables you to run event-triggered code without provisioning or managing infrastructure. This service allows developers to focus on writing code that matters to their business rather than maintaining servers, making it ideal for microservices, background processing, scheduled tasks, and event-driven applications.
Core Concepts
Concept | Description |
---|---|
Function App | Container for multiple functions that share configuration, deployment, and scaling |
Trigger | Event that causes a function to run (HTTP, timer, storage events, etc.) |
Binding | Declarative way to connect data and services to your function |
Plan Types | Consumption, Premium, Dedicated (App Service) – different scaling and performance options |
Runtime | The environment that executes your function (.NET, JavaScript, Python, etc.) |
Function Types & Triggers
Common Triggers
- HTTP Trigger: Runs when an HTTP request is received
- Timer Trigger: Runs on a schedule
- Blob Trigger: Runs when a file is added/updated in Azure Storage
- Queue Trigger: Runs when a message is added to Azure Storage Queue
- Event Hub Trigger: Runs when events arrive in an Event Hub
- CosmosDB Trigger: Runs when documents change in a CosmosDB collection
- Service Bus Trigger: Runs when messages arrive in a Service Bus queue/topic
Binding Types
- Input Bindings: Read data from a source
- Output Bindings: Write data to a destination
Quick Start Guide
Prerequisites:
- Azure account
- Visual Studio, VS Code, or Azure Portal
- Azure Functions Core Tools (for local development)
Create a Function App:
az functionapp create --resource-group MyResourceGroup --name MyFunctionApp --storage-account MyStorageAccount --consumption-plan-location eastus --runtime dotnet
Create a Function (locally):
func init MyFunctionProject --dotnet cd MyFunctionProject func new --name MyHttpFunction --template "HTTP trigger"
Test Locally:
func start
Deploy to Azure:
func azure functionapp publish MyFunctionApp
Configuration Management
Local Settings (local.settings.json)
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;...",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"MyCustomSetting": "Value"
}
}
Environment Variables in Azure
- Set in Azure Portal → Function App → Configuration → Application settings
- Access in code via
Environment.GetEnvironmentVariable("MyCustomSetting")
Security Best Practices
- Authentication/Authorization: Use App Service Authentication
- Keys and Secrets: Store in Azure Key Vault
- Function Keys:
function.json
contains a “authLevel” property:- anonymous: No API key required
- function: Function-specific API key required
- admin: Master key required
Common Patterns & Examples
HTTP Trigger (.NET)
[FunctionName("HttpExample")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
Timer Trigger (JavaScript)
module.exports = async function (context, myTimer) {
var timeStamp = new Date().toISOString();
if (myTimer.isPastDue) {
context.log('JavaScript is running late!');
}
context.log('JavaScript timer trigger function ran!', timeStamp);
};
Queue Trigger with Blob Output (Python)
import logging
import json
import azure.functions as func
def main(msg: func.QueueMessage, outputBlob: func.Out[str]) -> None:
logging.info('Python queue trigger function processed a queue item.')
message = msg.get_body().decode('utf-8')
result = json.dumps({
'id': msg.id,
'body': message,
'processed': True
})
outputBlob.set(result)
Plan Comparison
Feature | Consumption | Premium | App Service |
---|---|---|---|
Auto-scaling | ✓ (to zero) | ✓ (with pre-warmed instances) | ✓ (manual/auto) |
Cold Start | Yes | Minimized | No |
Max Execution Time | 10 minutes | 30 minutes | Unlimited |
Memory | Up to 1.5 GB | Up to 14 GB | Depends on tier |
VNET Support | Limited | Full | Full |
Pricing Model | Pay-per-execution | Fixed + per-second | Fixed |
Durable Functions
Orchestration Patterns:
- Function Chaining: Sequence of functions where output → input
- Fan-out/Fan-in: Parallel execution with aggregation
- Async HTTP APIs: Long-running operations with status polling
- Monitor: Recurring process in a workflow
- Human Interaction: Incorporate human approval in automated processes
Example Orchestrator (C#):
[FunctionName("OrderProcessing")]
public static async Task<object> RunOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context)
{
var orderData = context.GetInput<OrderData>();
// Call activity functions
await context.CallActivityAsync("ValidateOrder", orderData);
await context.CallActivityAsync("ProcessPayment", orderData);
// Call external system with retry policy
var retryOptions = new RetryOptions(
firstRetryInterval: TimeSpan.FromSeconds(5),
maxNumberOfAttempts: 3);
await context.CallActivityWithRetryAsync("ShipOrder", retryOptions, orderData);
return new { OrderId = orderData.OrderId, Status = "Completed" };
}
Common Challenges & Solutions
Challenge | Solution |
---|---|
Cold Start Latency | Use Premium plan, keep functions warm, optimize dependencies |
Connection Management | Use static clients, implement connection pooling |
Function Timeouts | Break into smaller functions, use Durable Functions for long-running operations |
Local Debugging | Use VS Code with Azure Functions extension, Azure Storage Emulator |
CORS Issues | Configure CORS in function.json or host.json |
Function Dependencies | Use Dependency Injection, configure DI in startup.cs |
Performance Tips
- Keep Dependencies Minimal: Large dependencies increase cold start time
- Optimize Resource Usage:
- Reuse HTTP clients and database connections
- Use connection pooling
- Implement caching where appropriate
- Async/Await Patterns: Use proper async patterns in your code
- Batch Processing: Process multiple items together when possible
- Function Fusion: Combine closely related functions to reduce overhead
Monitoring & Diagnostics
Application Insights
- Enable in Azure Portal: Function App → Configuration → Application Insights
- Key Metrics:
- Invocation count and duration
- Success rate
- Dependency calls
Logging
// C#
log.LogInformation("Function processed order {orderId}", orderId);
// JavaScript
context.log("Function processed order", orderId);
// Python
logging.info(f"Function processed order {order_id}")
host.json Configuration
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
},
"logLevel": {
"default": "Information",
"Function": "Information",
"Host.Results": "Error"
}
}
}
Resources for Further Learning
- Official Documentation: Azure Functions Documentation
- Azure Functions GitHub: GitHub Repository
- Sample Projects: Azure Samples
- Learning Path: Microsoft Learn
- Community Support: Stack Overflow Azure Functions Tag
Azure Functions CLI Commands
# Create a new function project
func init MyProject --dotnet
# Add a new function
func new --name MyFunction --template "HTTP trigger"
# Run locally
func start
# Publish to Azure
func azure functionapp publish MyFunctionApp
# List templates
func templates list
# Add extension package
func extensions install --package Microsoft.Azure.WebJobs.Extensions.Storage --version 4.0.4
Function.json Example (JavaScript/TypeScript)
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": ["get", "post"],
"route": "products/{id}"
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"type": "table",
"direction": "in",
"name": "productData",
"tableName": "Products",
"partitionKey": "Products",
"rowKey": "{id}",
"connection": "AzureWebJobsStorage"
}
]
}
This comprehensive cheatsheet covers the essential aspects of Azure Functions for both beginners and intermediate developers. Use it as a quick reference to accelerate your serverless development with Microsoft Azure!