Azure Functions â Serverless Computing Guide
In this tutorial, you'll learn about Azure Functions. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Azure Functions is a serverless compute service by Microsoft Azure that lets you run event-driven code without provisioning or managing infrastructure, automatically scaling from zero to millions of executions based on demand.
What You'll Learn
You'll understand Azure Functions' core concepts â triggers, bindings, hosting plans, Durable Functions for workflows â and build real serverless solutions with HTTP, timer, and queue triggers.
Why Azure Functions Matters
Serverless eliminates infrastructure management. You write only the code that matters, pay only for execution time, and scale automatically. DodaTech uses Azure Functions to process file scans in DodaZIP, send email notifications, and run scheduled security audits without maintaining any servers.
Real-World Use
When a user uploads a ZIP file to cloud storage, an Azure Function automatically triggers, extracts the contents, scans each file against known malware signatures, and stores the results â all without a single VM.
Azure Functions Learning Path
flowchart LR A["Cloud Computing Basics"] --> B["Azure Functions Overview"] B --> C["Triggers & Bindings"] C --> D["Durable Functions"] D --> E["Monitoring & Scaling"] E --> F["Production Serverless Apps"] C:::current classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px
Prerequisites: Basic C# or PowerShell knowledge. An Azure subscription (free tier works). Install Azure Functions Core Tools.
Function Types: Triggers and Bindings
| Trigger | Fires When | Use Case |
|---|---|---|
| HTTP | HTTP request received | REST API, webhooks |
| Timer | Cron schedule | Scheduled jobs, cleanup |
| Blob | File created/changed in Blob Storage | Image processing, file scan |
| Queue | Message added to Queue Storage | Background processing |
| Event Grid | Azure event | System-wide reactions |
| Service Bus | Message in Service Bus queue/topic | Enterprise messaging |
Bindings are declarative connections to data sources. An input binding reads data; an output binding writes data.
Code Examples
Example 1: HTTP Trigger with C#
using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace DodaTech.Functions;
public class HealthCheck
{
[Function("HealthCheck")]
public HttpResponseData Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req,
FunctionContext executionContext)
{
var logger = executionContext.GetLogger("HealthCheck");
logger.LogInformation("Health check requested at {Time}", DateTime.UtcNow);
var response = req.CreateResponse(HttpStatusCode.OK);
response.WriteString("DodaTech Serverless: OK");
response.Headers.Add("Content-Type", "text/plain");
return response;
}
}
Test with curl:
curl https://dodatech-functions.azurewebsites.net/api/HealthCheck
Expected output:
DodaTech Serverless: OK
Example 2: Timer Trigger â Security Audit Cleanup
using System;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace DodaTech.Functions;
public class SecurityLogCleanup
{
[Function("SecurityLogCleanup")]
public void Run([TimerTrigger("0 0 3 * * *")] TimerInfo timer, FunctionContext context)
{
var logger = context.GetLogger("SecurityLogCleanup");
logger.LogInformation("Daily security log cleanup started at {Time}", DateTime.UtcNow);
// Delete log entries older than 90 days
// This runs at 3:00 AM every day
int deletedCount = 0; // In production, query Azure Table Storage
logger.LogInformation("Deleted {Count} expired log entries", deletedCount);
}
}
Cron expression 0 0 3 * * * = every day at 3:00 AM UTC. The six fields are: second, minute, hour, day of month, month, day of week.
Example 3: Blob Trigger â File Scan Pipeline
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace DodaTech.Functions;
public class FileScanProcessor
{
[Function("FileScanProcessor")]
public async Task Run(
[BlobTrigger("uploads/{name}", Connection = "AzureWebJobsStorage")] Stream blobStream,
string name,
FunctionContext context)
{
var logger = context.GetLogger("FileScanProcessor");
logger.LogInformation("Processing uploaded file: {Name}", name);
// Read file into memory
using var memoryStream = new MemoryStream();
await blobStream.CopyToAsync(memoryStream);
byte[] fileBytes = memoryStream.ToArray();
// Perform signature-based scan (simplified)
bool isMalicious = ScanForThreats(fileBytes);
logger.LogInformation("Scan result for {Name}: {Result}", name,
isMalicious ? "MALICIOUS" : "CLEAN");
}
private bool ScanForThreats(byte[] content)
{
// This pattern is used in Durga Antivirus Pro's cloud scanning pipeline
// Check against known malware signatures
return false; // Simplified for example
}
}
Durable Functions: Serverless Workflows
Durable Functions let you write stateful workflows in a serverless environment.
[Function("ScanOrchestrator")]
public async Task<string> RunOrchestrator(
[OrchestrationTrigger] TaskOrchestrationContext context)
{
var files = await context.CallActivityAsync<string[]>("GetFilesToScan");
var tasks = files.Select(f => context.CallActivityAsync<bool>("ScanFile", f));
var results = await Task.WhenAll(tasks);
int threats = results.Count(r => r);
return $"Scanned {files.Length} files, found {threats} threats.";
}
Hosting Plans Comparison
| Plan | Scale | Cold Start | Cost | Use Case |
|---|---|---|---|---|
| Consumption | Auto-scale to 200 instances | Yes (2-5s) | Pay-per-execution | Spiky workloads, low traffic |
| Premium | Auto-scale, pre-warmed | No | Per-second + fixed | Production, predictable traffic |
| Dedicated (App Service) | Manual scale | No | VM cost | Always-on, existing App Service |
Security: Managed Identity Instead of Keys
Always use Managed Identity instead of connection strings:
// Program.cs â use DefaultAzureCredential
builder.Services.AddSingleton(new BlobServiceClient(
new Uri("https://dodatechstorage.blob.core.windows.net"),
new DefaultAzureCredential()));
Common Errors
Function timeout: Consumption plan functions time out after 5 minutes (230 seconds for HTTP). Use Premium plan or Durable Functions for long-running tasks.
Cold start latency: After idle periods, the first request is slow because the runtime loads. Use Premium plan with pre-warmed instances or keep-alive triggers.
Missing
local.settings.json: Running locally requiresAzureWebJobsStorageconnection string inlocal.settings.json. TheValuessection is mandatory.Blob trigger fires multiple times: Blob triggers have at-least-once semantics. Make your function idempotent (check if already processed via a tracking table).
Scale controller throttling: If you have many function apps in one region, the scale controller may throttle. Distribute across regions or use Premium plan.
Connection Pool exhaustion: Each function instance holds connections. Use
IHttpClientFactoryfor HTTP calls and reuse clients as singletons.Logging not appearing in Application Insights: Your function must reference
Microsoft.Azure.Functions.Worker.ApplicationInsightsand configureAPPLICATIONINSIGHTS_CONNECTION_STRING.
Practice Questions
- What is the difference between a trigger and a binding?
- How long can a Consumption plan function run before timing out?
- What is cold start, and how do you mitigate it?
- What does the
[BlobTrigger]attribute connect to? - When would you use Durable Functions instead of a regular function?
Answers:
- A trigger starts the function execution; a binding connects to data (input or output) without custom code.
- 5 minutes for non-HTTP functions; 230 seconds for HTTP-triggered functions.
- Cold start is the delay when a function loads after being idle. Mitigate with Premium plan (pre-warmed instances) or keep-alive triggers.
- It connects to Azure Blob Storage â the function fires when a new blob is created in the specified container.
- When you need stateful workflows, fan-out/fan-in patterns, or human interaction (approval workflows).
Challenge
Build a serverless image processing pipeline. When a user uploads a JPEG to Blob Storage, an Azure Function resizes it to three sizes (thumbnail, medium, large), extracts EXIF metadata, stores all versions in different containers, and logs the processing results.
Real-World Task
Create an HTTP-triggered Azure Function that accepts a URL, downloads the page content, checks it against a list of known phishing patterns, and returns a security score. Deploy it behind Azure API Management with Rate Limiting and API key authentication.
Featured Snippet
What are Azure Functions?
Azure Functions is a serverless compute service that runs event-driven code in response to HTTP requests, timers, queue messages, or storage events, scaling automatically and charging only for execution time.
FAQ
Try It Yourself
What's Next
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro