Azure Functions Serverless Architectures Tutorial

This tutorial guides you through building and deploying serverless applications using Azure Functions. We'll cover common patterns and best practices for creating scalable and cost-effective solutions.

Prerequisites

Before you begin, ensure you have the following installed:

  • Azure Account (Free trial available)
  • Azure Functions Core Tools
  • Your preferred code editor (e.g., VS Code)
  • Node.js (for JavaScript/TypeScript functions) or .NET SDK (for C# functions)

Understanding Serverless with Azure Functions

Azure Functions allows you to run small pieces of code, called "functions," without worrying about managing infrastructure. It scales automatically based on demand, and you only pay for the compute time you consume.

Key Serverless Benefits:
  • No Server Management: Focus on your code, not servers.
  • Event-Driven: Trigger functions based on events from various Azure services and external sources.
  • Automatic Scaling: Handles fluctuating workloads seamlessly.
  • Pay-per-Use: Cost-effective by paying only for execution time.

Scenario: Image Thumbnail Generation

Let's build a common serverless pattern: automatically generating thumbnails for uploaded images.

Step 1: Create an Azure Function Project

Open your terminal or command prompt and run the following commands to create a new Azure Functions project:


func init ImageThumbnailGenerator --worker-runtime node
cd ImageThumbnailGenerator
func new --name GenerateThumbnail --template "Blob trigger"
                

This creates a new project with a function named GenerateThumbnail that will be triggered by changes in Azure Blob Storage.

Step 2: Configure Blob Trigger

Open the function.json file for the GenerateThumbnail function. Ensure the path is set to a container where images will be uploaded (e.g., images/{name}) and the connection refers to your storage account connection string name.


{
  "scriptFile": "index.js",
  "bindings": [
    {
      "name": "myBlob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "images/{name}",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "outputBlob",
      "type": "blob",
      "direction": "out",
      "path": "thumbnails/{name}.jpg",
      "connection": "AzureWebJobsStorage"
    }
  ]
}
                

Step 3: Implement Thumbnail Generation Logic (Node.js)

Update the index.js file with the following code. This example uses the sharp library for image manipulation. You'll need to install it:

Install sharp:


npm install sharp
                

index.js content:


const sharp = require('sharp');

module.exports = async function (context, myBlob) {
    context.log(`JavaScript blob trigger function processed blob
    Name: ${context.bindingData.name}
    Size: ${myBlob.length} Bytes`);

    if (myBlob && myBlob.length > 0) {
        try {
            const thumbnail = await sharp(myBlob)
                .resize(100, 100) // Resize to 100x100 pixels
                .toFormat('jpeg')
                .toBuffer();

            context.bindings.outputBlob = thumbnail;
            context.log('Thumbnail generated and saved.');
        } catch (error) {
            context.log.error('Error generating thumbnail:', error);
        }
    } else {
        context.log('Blob is empty, skipping thumbnail generation.');
    }
};
                
Tip: For production scenarios, consider using a queue to decouple image upload and processing. The HTTP trigger can upload to blob storage and put a message on a queue, and another function can process the queue message to generate thumbnails.

Step 4: Configure Storage Connection

In your local project, update the local.settings.json file with your Azure Storage account connection string. Make sure the key matches the connection name used in function.json (e.g., AzureWebJobsStorage).


{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "YOUR_AZURE_STORAGE_CONNECTION_STRING",
    "FUNCTIONS_WORKER_RUNTIME": "node"
  }
}
                

Step 5: Run and Test Locally

Start your Azure Functions host:


func start
                

Upload an image file (e.g., myimage.jpg) to the images container in your Azure Storage account. You should see a myimage.jpg file appear in the thumbnails container.

Step 6: Deploy to Azure

Once you're satisfied, you can deploy your function app to Azure using the Azure Functions Core Tools CLI or your preferred deployment method (e.g., CI/CD pipelines).


# Example deployment command (requires Azure CLI login)
az functionapp deployment source config-zip --resource-group  --name  --src-zip .
                

Advanced Serverless Patterns

Durable Functions

For orchestrating complex workflows, stateful functions, or long-running processes, explore Azure Durable Functions. They allow you to write stateful workflows in a serverless compute environment.

Examples include:

  • Function chaining
  • Fan-out/fan-in
  • Human interaction
  • Monitoring and approvals

Event Grid Integration

Azure Event Grid provides a highly scalable, fully managed event routing service. You can use it to build event-driven architectures by subscribing to events from various Azure services and routing them to your Azure Functions for processing.