Azure Functions

Azure Functions

           Serverless computing is rightfully gaining more and more attention now a days with cloud ecosystem be it AWS, Azure, GCP, IBM name any of the cloud provider. But the most important discussion over the internet space is whether serverless is actually Server-less in literal meaning!

What is serverless?

                  
            To answer the question, serverless is not literally server less. There are Servers. You still need server to run your application. Serverless computing is a way of abstracting the hassle of the underlying infrastructure from developers so that they can concentrate on the logical implementation. It is a cloud computing execution model where cloud provider handles all the responsibility for common infrastructure management tasks like provisioning, scaling, scheduling, patching etc. It generally provides a stateless run time environment to execute the code and once the execution is completed the resources are not reserved for the same work anymore. Again when next time the event triggers the execution of the code, cloud provider dynamically allocate resources for the same. Hence user is only charged for the period the code is running. So serverless implies that for customer underlying Servers are completely abstract and invisible.
 
It is also termed as "Function as a Service" or "FaaS" as generally code is shipped to cloud provider for execution in a form of function which can be triggered by some form of predefined events like HTTP request, database events, queuing services, monitoring alerts, file uploads, scheduled events etc. 

The first serverless computing offering was Google App Engine introduced in 2008. Subsequently AWS launched AWS lambda in 2014 and then Microsoft Azure and the list goes on. Some of the major serverless computing offerings are:

Microsoft Azure has a range of serverless offerings at the moment AKS, Azure Functions etc. Most pioneer serverless computing or FaaS offering from Microsoft Azure is Azure Functions. Initially Azure launched WebJobs to solve the problem of event triggered computation. Later Azure utilized the concept of same and came up with serverless computation named Azure Functions. 

Here we will discuss about Microsoft Azure Functions.

What is Azure Functions?

According to Azure documentation
Azure Functions is a cloud service available on-demand that provides all the continually updated infrastructure and resources needed to run your applications. You focus on the pieces of code that matter most to you, and Functions handles the rest. Functions provides serverless compute for Azure. You can use Functions to build web APIs, respond to database changes, process IoT streams, manage message queues, and more.

 Azure Functions is a serverless solution is "compute on-demand" offering that allows user to implement code as Function which will runs on dynamically allocated resources responding to critical events. 

Azure takes care of scalability of Functions. When demand increases, more application instances are added automatically to the service and when requests fall, all extra resources and application instances drop off automatically. This feature has an issue of cold start. Cold start is the process when a new instance handles its first request. Even though Azure Functions launches fast, it still takes time to launch an instance and to make all the appropriate service connections.

For more details about cold start please check out Understanding serverless cold start and Cold Starts in Azure Functions.

Some of the reasons of using Functions:

  • Azure functions are easier to write and deploy. Also there are templates of different functions available in different programming languages.
  • Azure functions are fast to execute as there is less resource utilization, startup time, initialization time.
  • Azure functions are compute-on-demand and that is scalable. When demand of execution increases, more resources are allocated automatically to the service and when requests fall, all extra resources and application instances drop off automatically.
  • Azure functions support multiple programming languages including C#, F#, Java, JavaScript, PowerShell, TypeScript, and Python.
  • Azure Functions is serverless. Hence there is no hassle of managing infrastructure.
  • Azure Functions can be build, tested, and deployed in Azure portal, Azure CLI and Visual Studio. 
  • Azure Functions can be executed and debugged in local as well. Also recently Microsoft recently announced KEDA. This provides a new way of running Azure Functions on Kubernetes with KEDA. If you’re running container-hosted Functions on your own infrastructure or another public cloud, you can run them in Kubernetes, using KEDA to support launching new instances as required.

Common use cases of Azure Functions:

         Azure Functions can be used in different use cases and to design a complete serverless solution of complex use cases. But it can not definitely replace an entire website. Best suited use cases are scheduled tasks, small APIs, backend event triggered computing etc.

Here are some common use cases are:

  • HTTP triggered web API
  • Processing file uploads
  • Respond to database change feed
  • Scheduled Tasks
  • Logic to respond to events and messages
  • Real time data processing
  • IoT data stream

 Hosting plans for Azure Functions:

Azure offers three different types of hosting plans or pricing model for Azure Functions:
  • Consumption plan: This is the default hosting plan. In this plan user pays only when their functions are running.
  • App Service plan: Here function runs with App Service Plans. This is suitable for long running jobs.
  • Premium plan: Automatically scales based on demand using pre-warmed workers which run applications with no delay after being idle, runs on more powerful instances, and connects to virtual networks. This plan can be used to avoid cold start based upon the use cases.

Triggers and Bindings

Before we jump into hands on with Azure Functions, let's understand what is trigger and binding. Azure documentation has a very compact information about what is trigger and what is binding.
Trigger:
 
Triggers are what cause a function to run. A trigger defines how a function is invoked and a function must have exactly one trigger. Triggers have associated data, which is often provided as the payload of the function.
Binding:
 
Binding to a function is a way of declaratively connecting another resource to the function; bindings may be connected as input bindings, output bindings, or both. Data from bindings is provided to the function as parameters.
So each function must have one trigger and can have numbers of bindings depends upon the requirement. Binding can be of two types
  • Input
  • Output
Some bindings can have a special direction of "inout". All the supported triggers and bindings are listed in documentation. Also if require it is possible to create custom bindings as well.

 Hands on with Azure Functions

            Now let's see how we can create Azure Functions and deploy a function app there. There are four ways of how we can create Azure Functions App which acts as containers for Functions
  • Azure Portal
  • Azure CLI and Azure Function Core Tool
  • ARM template
  • Visual Studio and Visual Studio Code

 Previously with Functions 1.x, it was possible to deploy multiple Functions of different language in single Azure Function App. But to provide better runtime experience from Functions 2.x, Azure allows to deploy multiple Functions of single programming language in a Functions App.

For simplicity I will create a Functions App using Azure portal. To do so first login to Azure portal and one should have at least free tier subscription. Now search Function App and click create. Once the "Create Function App" blade opens below basic information needs to be provided:

Basics

  • Subscription: Select your subscription
  • Resource Group: Either select an existing Resource Group or create a new Resource Group by clicking "Create new" link
  • Function App name: Provide an unique name for Function App name. 
  • Publish: Select how you want to publish Functions as Code or Docker container. For our demo, I am using code.
  • Runtime stack: Please runtime stack as per your requirement. For us, I have used Node.js
  • Version: Select version of the runtime stack
  • Region: Select in which region you want to host Function App.

Next in Hosting section provide below information

Hosting
  • Operating system: Select whether you want to use Linux or Windows.
  • Plan: Select appropriate hosting plan for Function App. Default plan is Consumption.
 Next in Monitoring section, provide information about Application Insights to enable APM tool to monitor application

Monitoring
  • Enable Application Insights: Select whether you want to enable Application Insights
  • Application Insights: Select an existing or create new Application Insights
  • Region: Region is selected same as Function App.

Next provide suitable Tags for Function App and click Review+create for validation. Once validation is successful, click create to create Function App.



 Once the deployment is completed, Resource Manager will notify about the same. Also we need to create a storage account as that is required to deploy Functions in Function App. But before we proceed with inspecting Function App, I will also share how we can create same using Azure CLI. For that either you can install Azure CLI in local or use Azure Cloud Shell Bash. I will be using Windows 10 system. I have already logged in to my Azure account and used below PowerShell script to create Function App using Azure CLI.

$ResourceGroup = "Function-RG"
$Location = "eastus"
$StorageAccName = "pracfuncstracc"
$FunctionAppName = "my-first-functionapp"

az group create -n $ResourceGroup -l $Location

az storage account create -n $StorageAccName -g $ResourceGroup -l $Location --sku Standard_LRS

az functionapp create -n $FunctionAppName -g $ResourceGroup -s $StorageAccName -c $Location --runtime node --runtime-version 10 --os-type Linux --functions-version 3
 

Once Above script executes successfully, Function App named "my-first-functionapp" will be created in Resource Group named "Function-RG" and a storage account named "pracfuncstracc".

Now either you create Function App through portal or Azure CLI, Function App will be visible in portal.


Overview of Function App

 

Let's try to access the URL of the Function App.

Default page


Woo Hoo! Default page has been rendered.

Wait! Did you notice any difference between both the approach? 😊

There is one extra resource has been provisioned in Azure CLI, a storage account and same storage account has been linked to Function App while creating Function App. What is the significance of the same? Why we did not create the same through portal? 😊We will explore that later while deploying a Function to Function App. Function App actually acts as a container for one or more Functions.

Now let's create a Function.

Create first Function

It is time to create our first Function. Out of plenty of supported language I will be using Node.js. It is possible to develop a Function in portal and choose a wide variety of template to scaffold a Function if OS of the Function App is Windows. As of now it is not allowed to develop Function in portal if OS is Linux.
Develop in portal


I will be using VS code to develop Node based Function. Prerequisite for the same is
  • VS code is installed
  • Node.js is installed
  • Azure Core Tools package is installed
  • Azure Functions extension for VS code is installed
Create new Function project using VS code

 Click "Create New Project" in Azure Functions extension panel in VS code to create a Functions project and scaffold a Function using one of the supported language. It will prompt to select directory for project, language, template(triggers for function), name and authorization level for the Function.

 

Input to create project

 Steps and selection for our project:

  1. Select folder for Function project - FirstFunction
  2. Language - JavaScript
  3. Template - HTTP trigger
  4. Name - HttpTriggeredFunction
  5. Authorization level - Anonymous

After all the above steps VS code will scaffold a Function project with first HTTP trigger Function using JavaScript. Here is the structure of the Function project

Project structure 

Each Function has it's own files inside parent directory of the Function project. In our case HttpTriggeredFunction is present inside FirstFunction (project directory). Each Function has separate index.js and function.json. Parent project directory contains shared host.json, local.settings.json, package.json and proxy.json. Let's explore all the files and their significance.

  • index.js contains the JavaScript implementation of the exported async function which will be executed during event trigger which HTTP request for our Function.
index.json

 First argument of the function is always context object. The runtime uses the context object to pass data to and from your function and the runtime. Used to read and set data from bindings and for writing to logs, the context object is always the first parameter passed to a function.

  • function.json contains information about trigger and both type bindings, i.e., input and output binding. We can add as many input and output binding as we want with details like type, direction(in or out), name etc.

function.json 

There are different ways of accessing trigger and bindings in implementation. Azure documentation provides extensive information about Bindings .

  • The host.json file contains global configuration for all Functions which is used while running Function locally or in Azure. Details of the host.json can be found in Azure documentation.
  • The local.settings.json contains configurations for Function running in local. For hosted Functions these are maintained in Application Settings and Connection strings.
  • The proxy.json allow user to define proxy for different Functions.

 Run Function locally

We can run Function in local using VS code. Now press F5 to run Function locally. It will build the Function and start.

Function running locally

We can copy the endpoint from terminal and test using browser or postman.

Test using postman

Publish Function to Azure

 We can publish Function to either existing Azure Function App or create new Function App and publish there using VS code. As we have already created one Function App "my-first-functionapp", I will publish out HttpTriggeredFunction to "my-first-functionapp" Function App.

I can either right click on the Function project ( FirstFunction ) and select "Deploy to Function App"

Deploy to Azure Function App 
 
or click "Deploy to Function App" icon in Azure Function extension panel to deploy Function to Azure Function App.

Function extension 
 
From the above image as you can see, I have one local Function HttpTriggeredFunction and my-first-functionapp is created in Azure. Once we start deployment process, we have to select existing Function App where we want to publish our function.

Deploy to Function App

Once deployment is completed, HTTP Trigger URLs will be displayed in terminal. We can navigate to the published Function in portal under Functions section of our Function App. It will open the overview of the Function. We can check read only code ( for Linux) and test function from portal under Code + Test section.
 
Code + Test

We can also visualize the  integration of trigger and bindings under Integration section. It is possible to edit bindings and add new bindings from the portal as well if OS is selected as Windows.

Integration 
It is time to test our Function from portal. Testing blade will be visible once we click on the Test/Run in Code + Test section. There we can provide our input and test. output will be displayed in output tab.

Test/Run


That's it for the basic Function. Now we have our first HTTP trigger Function published in Azure Function App and we can trigger the function using the URL.
Also we can deploy multiple Functions in one Function App. Only constraint is all the Functions should be implemented using same programming language. 

But before wrapping up I want to explore some important concepts of Function. If we navigate to our Function App blade, under Settings, there is configuration. Under the configuration section there are mainly two different types of settings, i.e., Application settings and Function runtime settings.

Function runtime settings

Function runtime settings contains Runtime version and Daily Usage Quota (GB-Sec).

Application settings

Application settings are the settings for the Function App passed as environment variables to the application code. Developers has opportunity to mention any environment settings here. These settings are applicable for all the Functions published in the Function App. We also have option to mention Function specific settings under Function Keys for each Function. Some of the common Application settings are
  • APPINSIGHTS_INSTRUMENTATIONKEY
  • AzureWebJobsStorage
  • FUNCTIONS_EXTENSION_VERSION
  • FUNCTIONS_WORKER_RUNTIME
  • WEBSITE_RUN_FROM_PACKAGE
Application settings


I would like to explore next topic is Storage account, Application settings AzureWebJobsStorage and WEBSITE_RUN_FROM_PACKAGE.

Storage account

Here comes the topic which we parked earlier for discussion about storage account. When we created Function App using CLI, we had provisioned one storage account and linked the same with Function App. The reason for that is that Function App uses storage account to maintain settings and code base of the published Functions. If we inspect AzureWebJobsStorage, it contains connection string of the storage account which we liked with the Function App. Also WEBSITE_RUN_FROM_PACKAGE holds path of the zip package of our deployed Functions. 

WEBSITE_RUN_FROM_PACKAGE

Also if we navigate to the containers of the storage account, we will be able to see few containers which are created by Function App. 
Blob Containers

One of the blob container is function-releases which is mentioned in WEBSITE_RUN_FROM_PACKAGE application settings. This actually points to the zip package available inside the containers for package deployment. Those zip files contains implementation of published Functions. So Functions uses this package to deploy and spin up new instance of Function when it receives a trigger event.


One obvious question is when we created Function App through portal, it did not ask to link any storage account. Then how in that case Function App will handle deployment. Answer is that for such scenario, we need to manually add connection string of a storage account in AzureWebJobsStorage Application setting variable for the Function App.

Conclusion

I hope we have got a brief overview of serverless concept and Azure Function. Also we have developed and deployed one Function to Azure Function App and learnt underlying concept of Function. Function is not only very obvious choice for the backend short lived event triggered jobs, also it is gaining more and more attention for right reason in the Microservice world. We can customize authentication and hosting of Function and integrate with Azure API management. For the scope of this article that is all. Later we will dig deeper into other concepts. 

Comments

Popular posts from this blog

HashMap

What is Stream API in Java

HashMap internal working principle