Microsoft Azure Functions

·

8 min read

Overview

Azure Functions is a serverless computing service that enables you to run code on-demand without having to explicitly provision or manage infrastructure. It can be used to run scripts or programs, process data, and integrate with other services, among other things. The nice thing is it is really easy to get up and running.

Here are some examples of what you can do with Azure Functions:

  • Run background jobs on a schedule such as backing up data, generating reports, or sending notifications. You can use the "Timer trigger" in Azure Functions to schedule the execution of a function. You can specify the schedule using a cron expression (Linux crontab format) as well.

  • Process data as it is added to a data store. This can be useful for tasks that need to be performed every time new data is available, such as validating the data, aggregating it, or sending notifications.

    • Azure Cosmos DB documents: You can use the "Cosmos DB trigger" to trigger a function when a new document is added to a collection.

    • Azure Storage blobs: "Blob trigger" to trigger a function when a new blob is added to a container.

    • Azure Queue storage messages

  • Automate business processes, for example, you could use an HTTP trigger to start a function when a webhook is called.

  • Build microservices and simple APIs

  • Build event-driven applications

    • Respond to Azure Event Grid events by using subscriptions and filters

    • Respond to high volumes of Azure events hubs events

    • Responds to Azure Service bus queue and topic messages

Azure Functions can be triggered by a variety of events, including HTTP requests, changes to data in a database, or the arrival of a message on a message queue. It can also be called directly using its HTTP endpoint or a client library. Azure Functions supports a variety of programming languages, including C#, F#, Node.js, Java, PHP, JavaScript and Python.

Azure functions include multiple templates you can use in key scenarios. You can use the Azure portal, the Azure Functions CLI, or the Azure Functions REST API to create and manage functions.

Triggers

Here are some triggers that you can use with Azure Functions to schedule a job:

HTTPTrigger - Functions support HTTP requests like we can do get and post requests. You can customize the trigger to respond to webhooks. Webhooks themselves come in several versions to handle different providers like GitHub and Slack.

TimerTrigger - As the name suggests, this particular feature lets you run events on a schedule. This is provided automatically in all development environments, without the need for installing the package manually or registering the extension.

GitHub Webhook - Installing Webhooks can help you build or set up GitHub Apps. This would help in the integrations that subscribe to certain events on GitHub. Other functions include: updating an external issue tracker, updating a backup mirror, triggering CI builds and deploying to your production server.

Generic Webhook - This is almost like a messaging format through which you can chat with the application of your choice. The template listens for messages and posts updates specific to the JSON payload.

CosmosDBTrigger - Functions support trigger, input binding and output bindings for Azure Cosmos DB. Once CosmosDBTrigger listens for updates and updates across various partitions, the change feed would publish inserts and updates, but not deletions.

BlobTrigger - With the help of this template, you can trigger a function when a blob is created/updated. WebJobs SDK monitors the log files constantly to check for new or changed blobs.

QueueTrigger - QueueTrigger helps to trigger a function when a new update comes up on the queue. The queue message is the input to the function, and might even resend the message for a retry loop.

EventHubTrigger - SendEvents() emits messages to the event hub. Trigger() will listen to the event and emit a new one with an incremented counter. Functions provide support for trigger and output bindings for Event Hubs.

ServiceBusQueueTrigger - Through the service bus queue trigger, the developer can execute the code in the function every time the service bus received a message.

ServiceBusTopicTrigger - When the function is triggered with a service bus topic message, the developer can publish and push messages to the topic.

Bindings

A binding is a way to connect the input and output of your function to other services, such as storage queues, event hubs, and service bus queues. When you create a function, you can use bindings to access data from these external services without writing any additional code. Instead, you can use declarative bindings to specify the input and output of your function in the function's configuration.

There are different types of bindings available in Azure Functions, including:

  • Input bindings: These bindings allow your function to receive data from an external service. For example, you can use an input binding to read data from a storage queue or an event hub.

  • Output bindings: These bindings allow your function to write data to an external service. For example, you can use an output binding to write data to a storage table or a service bus queue.

  • Trigger bindings: These bindings define the event that will cause your function to be executed. For example, you can use a trigger binding to specify that your function should be executed when a new item is added to a storage queue, or when a new message is received on an event hub.

You can use bindings to simplify the code in your functions and make it easier to connect to external services. You can also use bindings to enable your functions to scale automatically in response to changes in the workload.

Steps to create Azure functions

  1. Sign in to the Azure portal.

  2. Click the "Create a resource" button in the top left corner of the portal.

  3. In the "Search the Marketplace" field, enter "Function App" and press Enter.

  4. Click the "Function App" item in the search results.

  5. In the "Create Function App" blade, enter a name for your function app in the "Name" field.

  6. Choose the subscription and resource group you want to use for your function app.

  7. Choose a hosting plan and location for your function app.

  8. Click the "Create" (Review + create) button to create your function app.

  9. Go to resources to view your new function app.

Once your function app has been created, you can create a new function by following these steps:

  1. In the Azure portal, navigate to your function app.

  2. Click the "Functions" tab in the function app blade.

  3. Click the "Add" button in the top left corner of the blade.

  4. Choose a trigger for your function. A trigger is an event that causes your function to be executed.

  5. Choose a language for your function.

  6. Enter a name for your function.

  7. Click the "Create" button to create your function.

  8. Write your code for the function in the Azure portal, or use a local development environment to develop your function and then deploy it to Azure.

  9. Test your function by triggering it and verifying that it works as expected.

  10. Publish your function by clicking the "Save and run" button in the Azure portal.

Azure function folder structure

The code for all the functions in a specific function app is located in a root project folder, myFunctionApp in our case using python.

myFunctionApp/
|-- host.json
|-- local.settings.json
|-- requirements.txt
|-- my_function/
    |-- __init__.py
    |-- function.json
    |-- main.py

Here is a brief explanation of each file and folder:

  • host.json: This file contains global configuration settings for the Azure Functions runtime. You can use this file to specify things like the version of the runtime, the number of workers to use, and the size of the function's memory allocation.

  • local.settings.json: This file contains local configuration settings for your function app, such as the values of connection strings and app settings. This file is used during local development and is not deployed to Azure.

  • requirements.txt: This file lists the Python packages that your function app depends on. The Azure Functions runtime will install these packages when you deploy your function app to Azure.

  • my_function/: This folder contains the code and configuration for a specific function within your function app. The name of the folder should match the name of the function.

  • __init__.py: This file is optional, but it can be used to define the namespace for your function.

  • function.json: This file contains the configuration for your function, including the bindings, triggers, and other settings.

  • main.py: This file contains the code for your function.

Azure Function example using Python

To use the azure function service, you will need to install a Visual Studio code and the "Azure Functions" extension.

import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
    name = req.params.get('name')
    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
             "Please pass a name in the request body",
             status_code=400
        )

Best practices using functions

  1. Functions should be stateless and idempotent.

  2. Use queues for cross-function communication. If you require direct communication, consider durable functions or Azure Logic Apps.

  3. Avoid long-running functions.

Durable Functions

Azure Durable Functions is an extension of Azure Functions that lets you write stateful functions in a serverless environment. It allows you to define workflows that span multiple functions and can be long-running

Durable Functions use the concept of "orchestrators" and "activities" to define and execute workflows. An orchestrator is a special type of function that coordinates the execution of one or more activity functions. Activity functions are ordinary Azure Functions that perform specific tasks as part of the workflow.

Durable Functions provides built-in support for state management, checkpoints, and restarting failed workflows, so you can focus on writing the business logic of your functions without worrying about the underlying infrastructure.

Common use cases:

  1. Function chaining: Using the output of one function as an input to another.

  2. Fan out /fan in: Functions are executed in parallel, and their aggregation is used in a single function.

Did you find this article valuable?

Support Siddharth by becoming a sponsor. Any amount is appreciated!