Azure Functions Fundamentals
Last updated: October 26, 2023
Azure Functions is a serverless compute service that enables you to run code on-demand without explicitly provisioning or managing infrastructure. With Azure Functions, you can build applications by using single pieces of code that call out to other services, a process dramatically simplified and cost-effectively managed by Azure.
What are Serverless and Azure Functions?
Serverless computing, often referred to as Function-as-a-Service (FaaS), allows developers to build and run applications without thinking about servers. Azure Functions is Microsoft's FaaS offering, providing a powerful platform for event-driven, scalable compute.
Key characteristics of Azure Functions include:
- Event-driven: Functions are triggered by various events, such as HTTP requests, queue messages, timers, or changes in Azure services.
- Scalable: Azure automatically scales your functions based on demand, handling fluctuations in traffic.
- Cost-effective: You pay only for the compute time your code consumes, with a generous free tier.
- Polyglot: Supports multiple programming languages, including C#, JavaScript, TypeScript, Python, PowerShell, and Java.
- Integrated: Seamlessly integrates with other Azure services and third-party services.
Core Concepts
Triggers
A trigger defines how a function is invoked. When a trigger condition is met, Azure Functions runtime executes your function. Common triggers include:
- HTTP Trigger: Invokes a function via an HTTP request.
- Timer Trigger: Schedules a function to run periodically.
- Queue Trigger: Invokes a function when a message is added to an Azure Storage Queue.
- Blob Trigger: Invokes a function when a new or updated blob is detected in Azure Blob Storage.
- Cosmos DB Trigger: Invokes a function in response to changes in a Cosmos DB collection.
Bindings
Bindings provide a declarative way to connect your function to other services without writing explicit integration code. There are two types of bindings:
- Input Bindings: Provide data to your function.
- Output Bindings: Send data from your function to another service.
For example, a Queue Trigger might automatically load a message from a queue into a function parameter (input binding), and an output binding could write a result to a different queue or database.
Example: HTTP Trigger with Output Binding to Table Storage
Function.cs (C# Example)
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace MyFunctions
{
public static class HttpTriggerExample
{
[FunctionName("HttpTriggerExample")]
public static void Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[Table("MyTable", Connection = "AzureWebJobsStorage")] out MyEntity entity,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = new System.IO.StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}! This HTTP triggered function executed successfully.";
// Create an entity to be saved to Table Storage
entity = new MyEntity
{
PartitionKey = "HttpRequests",
RowKey = Guid.NewGuid().ToString(),
Message = responseMessage
};
log.LogInformation($"Entity created: PartitionKey={entity.PartitionKey}, RowKey={entity.RowKey}, Message={entity.Message}");
}
public class MyEntity
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Message { get; set; }
}
}
}
Deployment and Hosting
Azure Functions can be hosted in several ways:
- Consumption Plan: Ideal for event-driven workloads with intermittent compute needs. Pay-per-execution, automatically scales.
- Premium Plan: Offers pre-warmed instances for faster response times, VNet connectivity, and longer run times.
- Dedicated (App Service) Plan: Run functions on the same infrastructure as App Service plans, suitable for predictable workloads and leveraging existing App Service investments.
Deployment can be done via various methods, including Visual Studio, VS Code, Azure CLI, Azure DevOps, and GitHub Actions.
Best Practices
- Keep functions small and focused: Each function should perform a single, well-defined task.
- Manage dependencies effectively: Use package managers and ensure your dependencies are optimized.
- Handle exceptions gracefully: Implement robust error handling and logging.
- Monitor your functions: Utilize Application Insights for monitoring performance, errors, and usage.
- Choose the right hosting plan: Select a plan that aligns with your application's performance, scaling, and cost requirements.