Getting Started with Azure Functions : Fundamentals | Azure function tutorial | What is Azure Function

{tocify} $title={Table of Contents}


Introduction

Computer programming, irrespective of language used is simply a way of providing input, processing it and getting the desired output. 

Earlier it was all done in one place but with the evolution, individual responsibilities are segregated at all levels. There is shift from monolithic approach to microservices approach.

And functions are very much native citizen of this approach, where a single function is responsible for performing single task.

Thus in a project there can be many function catering to specific tasks, and they can be called from any where in the project - isn't it cool, but it can be more cool.

Consider second project there also many functions are created, some might be same as in project one and some may be specific to this project - so here the approach can be to reduce the redundancy upto some extent, by adding reference to project one and the functions performing same task can be reused.

What if projects are not accessible to you (say projects from different departments of same org).

To address the issue of redundancy and focus on reusability, Azure Functions was coined by Microsoft. (Almost every major cloud provider has some offering around it like AWS Lambda, Google cloud functions etc)

The idea is to have your functions deployed somewhere in cloud and whenever needed can be called/invoked by your application.

Thus no need of adding reference, no dependency, no tight coupling etc.

Apart from addressing the above issues and increasing the reusability, one major advantage is that you don't have to worry about managing the infrastructure, it is taken care by Microsoft.

What is Azure Functions

                

                                          Azure Functions == Events + Code


Azure functions Process events with serverless code.


Event is nothing but state change notification. In simple terms it is indicator of something happened.

Like change in data in a database table, file getting created or modified, hike in CPU utilization, change in time etc.

Events can be user generated or it can be system generated - like a user creating a file is user generated event whereas CPU utilization hiking is system generated event.


Serverless
 in reality there are servers/ virtual machine which host them but are hidden(no direct access) from users.

Thus the developer/user does not have to think about setting up servers to host the code nor they have to think about managing them.


Serverless code - code getting executed without user knowing where 

So Azure function is - A single function with an event to start it and code to respond to the event. Code is run on some Servers in the Microsoft datacenter.


Azure Functions are stateless, if state is to be maintained then it can be done using some storage options.


It is based on Event based Programming i.e., writing a piece of code which will be executed whenever any particular event occurs on infrastructure managed by Microsoft.




Building Blocks of Azure Function

Webjobs are used to run background jobs, and azure function is built on top of it and web apps.

Triggers

You have written some code in your function and now you want to use it, how do we do that - it is with the help of trigger. Trigger is the only way to invoke/start the function.

There can only be one Trigger for any particular Azure Function and it is mandatory for function to have a trigger.

It is an Event Listener which listens to events and it is this which tells function to initiate the execution.

Triggers are what cause a function to run and can be of many type. Below are few which are supported as of now (in future it will definitely grow)

  1. Azure Schedule
  2. HTTP (REST or webhook)
  3. Azure Blob Storage
  4. Event from Azure Event Hubs/Grid
  5. Azure Storage Queues
  6. Azure Service Bus Queues and Topics
  7. Azure Event Grid

Bindings

In your function you might need data from somewhere(some input) or might want to send data somewhere (some output). And to do that you need to create a connection with those systems/application etc.

Here rather than creating connections programmatically, it is done declaratively. 

Bindings are declarations that connect the function to another resource. And it is passed as parameters to the function.

There can zero to many input bindings (connection which is used to get data in function) and zero to many output bindings (connection which is used to send data out of function).

Currently supported/available Input bindings

Azure Blob Storage
Azure Storage Tables
Azure Mobile Apps SQL Tables
Azure Cosmos DB Documents


Currently supported/available Output bindings

Azure Blob Storage
Azure Storage Tables
Azure Mobile Apps SQL Tables
Azure Cosmos DB Documents
Azure Push Notifications
Twilio SMS Text
SendGrid Email


Functions.json


Functions.json files contains bindings info along with triggers



Functions.json file



Local.settings.json


Local.settings.json file is actually container of application level configuration which is used while running functions locally.

It(configurations) has to be added in function Apps Application settings after function is deployed on Azure.




What is Azure Function App


Function App is a host/container for one or more functions, it lets you group functions as a logical unit for management, deployment and sharing of resources. 

Segregation of Function app can be done based on various criteria's like department wise, functionality wise, environment wise etc.
 - say functions performing finance related tasks can be grouped together in FinanceApp, HR related functions in HRApp .
- Encryption/Decryption/Encoding/Decoding related functions in SecurityApp, Maths related functions in MathApp etc.
- Dev related functions in DevApp, Prod related functions in Prod App etc.

It is just logical grouping of functions and it does not stop you to use it from anywhere. FinanceApp can have a function which can be used by HR Department.

Azure Function App V1 supports multiple language functions in one app whereas v2 supports only same language.

Functions can be coded using various languages like C#, Python, F#, TypeScript, Powershell, Java etc

And as it is collection of functions, any configurations done at function app level gets applied to all the functions it has.

Function App is the unit for development, deployment and scaling.


When you create a function app, it must be linked to a storage account. You can select an existing account or create a new one. The function app uses this storage account for internal operations such as logging function executions and managing execution triggers (except HTTP triggers) .

On the Consumption service plan, this is also where the function code and configuration file are stored.

Function apps created through the Consumption plan don't support virtual network integration.

Host.json


host.json file contains configuration options that affect all functions in a function app instance( configurations like compiled app path). 


Hosting Models of Function App


Behind the scenes, an Azure Function App is a collection of one or more virtual machines (VMs) running a web server - which are responsible to provide the resources required to execute the functions. 

Remember, individual functions can't be hosted. It has to be part of a function App.

And based on whether you want to reserve the capacity or not, need vnet integrations and scaling options, few plans are offered by Microsoft. (For Both Windows and Linux)

Consumption plan(Default)

It is the default option, where you don't reserve capacity, rather it is automatically managed. i.e. On need more instances is added and when not required instances are removed. 

Functions running on a Consumption Plan have a default timeout of five minutes(maximum it can be extended to 10 minutes) and maximum memory usage is upto 1.5 GB.

And in a scenario, where there is no load (nothing to execute), the instances are brought down to zero.

Once instances are brought down to zero, if new request comes in then for getting executed new instance is created(it takes some time), the delay in getting started is called Cold Start.

If the load increases, new instances are automatically added and instances removed as load decreases, thus the scaling out and in happens automatically - you don't have to do any configuration for it.

And as compute resources are added as an when required, there is no fixed ip address (as underlying servers may or may not be same), thus this plan does not support Virtual network integration.

As it's an On-demand option, you pay for what you use - costing is done on the number of executions, time taken in executions and memory utilized.


Upto 1 millions executions are free per month.


Premium plan

This can be looked upon as a superset of consumption plan, where it addresses the limitations of it - No Cold start and supports VNet Integration.

And a subset of Dedicated plan, as here minimum resource has to be reserved and you need to pay for it even if it is not used.

Like consumption it supports automatic scaling, but here we have to specify the maximum limit it can be scaled.




Dedicated (App Service) plan

Here we reserve the resources (servers) and irrespective of whether we use it(executing functions) or not we have to pay the charges. So pricing is based on provisioning and not on use.

As resources are always available, the cold start scenario has no place here. 

Autoscale is not possible here as function runtime can maximum scale within underlying VM's capacity , you have to manually configure the scaling based on criteria.

There is no limit on function execution time and on memory usage(it depends how much you have procured via plan).



Development options 


There are two options available for developing function, it can be done in Azure Portal which has built in web based code editor also you can build and debug code locally on your machine (it actually helps in using existing libraries)

Developing functions in Azure Portal

It is very straight forward, you do not need to install anything. Just login to Azure portal and start using the web based code editor.

And as we are developing in portal itself, saving the code also deploys your function. 

Developing functions in Visual Studio/VS Code/Any editor + core tools

Here first you need to add extension - Azure Functions and web jobs tools if using visual studio 2017.

In either of the way, below templates with respective triggers are available for creating Azure function :
HTTP trigger
Blob storage trigger
Queue storage trigger
Service Bus Queue trigger
Service Bus Topic trigger
Timer trigger 
Event Grid trigger
Event Hub trigger
Azure Cosmos DB trigger

Creating Function using Azure Portal 

Let's have quick look on how to create a function. First we need to create a Function App to hold the function. 

When you create a function app, it must be linked to a storage account. You can select an existing account or create a new one.

Create Function App


Create Function App


Provide the details like FunctionApp Name,Runtime Stack, Version and Region.

Valid characters are a-z, 0-9 and - for function App name



Once function app is procured, next is to create function 

Create HttpTriggered Function


Create Azure function using azure portal



Click on function-->Create button --> select Development env as Develop in Portal --> from templates select Http Trigger

Give name to function and select Authorization level

Authorization level lets you choose whether you want a key to use to access function
anonymousNo API key is required.
functionA function-specific API key is required. This is the
default value when a level isn't specifically set.
adminThe master key is required.

Note: Always refrain from sharing master key with client, only share function key specific to particular functions needed by client.


Project templates often create a method named Run, but the method name can be any valid C# method name.


The order of parameters in the function signature does not matter. For example, you can put trigger parameters before or after other bindings, and you can put the logger parameter before or after trigger or binding parameters.


http triggered function



The function created consists of default code to give an idea how it works, a simple code which basically is checking for for name in query parameter and if it is not available in then it looks into the request body . It is taking in two parameters i. req over http ii. instance of a logger

And returns "Hello, {name}. This HTTP triggered function executed successfully."

and if name is not passed as input in either query parameter or in body then it returns following in response.

"This HTTP triggered function executed successfully. Pass a name in the query string
or in the request body for a personalized response"


Integration View


Click on the Integration to see the pictorial view of function, it shows how
it is triggered, what all inputs are used, where all the output is sent,

Integration view of function


Testing

We can test the above function in the portal itself or using some client app (postman/ARC) etc.

For testing using portal go to Code+Test --> Test/Run-->Input-->Select Http method --> In Body provide data

testing using portal

We can either pass the data in body or as an Query Parameter. (As our function looks at both places).

For testing using rest api clients go to Code+Test --> GetFunctionUrl
get function url


Copy the url and use it to test the function through any rest api client like Postman or ARC etc.

Conclusion

In this post the intention was to clarify the fundamentals of Azure Function like 
  • the need of Azure Function
  • how Azure Function can be developed
  • how Azure Function can be hosted
  • the languages Azure Function supports and 
  • Azure Function hosting plans etc.

If you have questions or suggestions, feel free to do in comments section below !!!


Do share if you find this helpful .......
 
                          Knowledge Sharing is Caring !!!!!!


Learn More about Logic App

Post a Comment

If you have any suggestions or questions or want to share something then please drop a comment

Previous Post Next Post