[Azure Functions] Intro to Serverless applications in Azure

“Serverless computing(SC)”  is a most cited buzzword in cloud computing after AI/ML, microservices, IoT, AR/VR/MR etc. Almost all the tech conferences has at least one session around this topic in their slot. Serverless computing is there for sometime now but recently getting adapted and used in conjunction with various cloud born solutions because of its easiness.

What is actually then SC? It is our next generation of "true" PaaS computing service or also called our next layer of abstraction in Cloud Compute. In Cloud computing term, this is called as function as a service(FaaS) aka event driven computing where our code invoked on demand. Studies predicts that, in future(2022) we will be buying bunch of functions to meet most of the current simple requirements. In the serverless model, the cloud provider fully manages the underlying infra so as a developer we focus only on our requirement or integration points. The idea is to break our application into silos functions like say add, update, validate, send an email or delete some backend records based on the events submitted over REST API endpoints(on demand) etc.

Background? AWS was the first one to introduce such model of computing called AWS Lamda in 2014. Within two years, Microsoft(Azure Functions), IBM(OpenWhisk), Googles (Google cloud functions) and even mid tier providers also has their offerings for this. At the current rate, we wouldn't be surprised to see FaaS as main tool used for get it done(GTD) "many" disjointed computing from our mainstream application. Let say, it could be a simple validation to complex log analysis or job submission invoked from any device or platform or language. Lot of cool things like tooling, continuous delivery, source control integration support etc happening in this space brings this confident.

Is it a microservices? It may look similar to microservices but actually not. In microservices, we can group multiple such services to form a single service but in case of serverless computing, our code is executed in isolation(silos), autonomous and in granular level.

Scenarios?  It can used for log analysis, IoT backend, cognitive bots, mobile back ends and REST API like querying weather forecast on a button click event etc. Most used one is user uploading an image, process (resize,crop etc) and then to required size for the reader device type.

benefits? The main advantages it brings is "cost", "scalability", "development cycle", "tooling setup" and freedom from infra maintenance. User is expected to pay only for the milliseconds compute used for this function runs and not for the whole instance.

What Azure offers in this space (Serverless architectures)? Azure Functions allows developers who already working with the Azure platform to integrate functions easily into their existing Azure-based workflow. It is a serverless compute executes little bit of code on demand. It provides more or less similar features like AWS Lambda and Google Functions however this stackoverflow(page) summarize all the differences in detail. Best part about this service is, it rightly expose required “Functions as a Service” over HTTP end endpoints which can be triggered through timer based events or external service events like blob uploaded to storage or data insertion in backend etc. It can be scaled based on customer selection. By the way, Azure function is built on top of App Service and WebJobs SDK.

Any other serverless service from Azure? Azure functions and Azure Logic apps offers serverless compute. The key difference is, the LogicApps doesn't provide a way to write custom code.

Let us see a sample Azure Functions usage in real time usecase.

image image

This example is borrowed from my Pluralsight training video to demonstrate the power of Azure functions. In this demo, we expect the user to upload the image to Azure storage which will be submitted to Cognitive service after Azure functions invoked after “BlobTrigger” event

Step1:- Create a Cognitive Service Emotion API from the Azure portal and keep the key ready. https://www.microsoft.com/cognitive-services/en-us/Emotion-api/documentation image

Step 2) Create a new Storage Account having container named “images”, this is where we are going to dump the images as input for Cognitive service to fetch from.

image

Step3:- Go ahead and create a function say “imageprocessingdemo” by selecting a “BlobTrigger-CSharp” template and have the below code.

image

Step4:- Input the image path, storage account details from where the images will be pulled after the trigger event.

image[65]

 

Step5:- Pls note, Azure Functions gets compiled on Save button event. So, upon “run” event we can the see the uploaded image score.

2017-03-18T21:39:32.590 GetUri:https://functionimages.blob.core.windows.net/images/crying-baby[1].jpg?sv=2015-12-11&sr=b&sig=ZBktU%2F4T60SfgeTgTpQXF%2FF%2xxxxxNP93YN1U%3D&st=2017-03-18T21:09:32Z&se=2017-03-18T22:09:32Z&sp=r 2017-03-18T21:39:38.197 results:[{"faceRectangle":{"height":967,"left":1560,"top":653,"width":967},"scores":{"anger":1.18772381E-09,"contempt":1.18056471E-08,"disgust":3.18779553E-06,"fear":7.162184E-08,"happiness":5.468896E-10,"neutral":1.40484147E-07,"sadness":0.9999966,"surprise":1.34302474E-11}}] 2017-03-18T21:39:38.197

Function completed (Success, Id=ce4f2b14-9cee-4148-a111-d38f5d2aaa16)

Code:-

#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Storage"

using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using System.Text;

public static async Task Run(CloudBlockBlob myBlob, string name, TraceWriter log)
{

    log.Info($"C# Blob trigger function Processed blob\n Name:{name}");

var uri=GetUri(myBlob);
log.Info($"GetUri:{uri}");

    var analysis= await GetAnalysis(uri);

    log.Info($"results:{analysis}");
}

public static Uri GetUri(CloudBlockBlob blob)
{

   var sasPolicy =new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessStartTime = DateTime.Now.AddMinutes(-30),
SharedAccessExpiryTime = DateTime.Now.AddMinutes(30)
};
var sastoken= blob.GetSharedAccessSignature(sasPolicy);
var uri = new Uri($"{blob.Uri.ToString()}{sastoken}");
return uri;
}

public static async Task<string> GetAnalysis(Uri uri){

    var client = new HttpClient();
var data = JsonConvert.SerializeObject(new { url = uri.ToString() } );
var request = new HttpRequestMessage
{
RequestUri=new Uri("https://api.projectoxford.ai/emotion/v1.0/recognize"),
Method= HttpMethod.Post
};

    request.Headers.Add("Ocp-Apim-Subscription-Key","e538a0xxfexxxxc6f41965894");
request.Content= new StringContent(data,Encoding.UTF8, "application/json");

    var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
return result;
}

Bindings:-

{
"bindings": [
{
"name": "myBlob",
"type": "blobTrigger",
"direction": "in",
"path": "images/{name}",
      "connection": "functionimages_STORAGE"
}
],
"disabled": false
}

Few other use cases where Azure Functions can be used,

  • Find and clean invalid data from the backend storage table for every 15 mins (Timer based)
  • Transform the user uploaded files to storage – say convert to different format or compress or resize or insert into data rows (Event Based)
  • Read the sales data excel file from OneDrive, analyze and create new sheets with charts (Saas Event processing)
  • Loaded web page calling web hook > Create ad based on user profile (Applications - Serverless web Application architectures)
  • Photo taken in mobile, webbook called to store it in Azure storage which is then scaled to different resolution using Azure functions (Async background processing as mobile backend)
  • Massage the streaming data and transform to structured data for DB insertion
  • Message sent to chatbot and responding to the questions (real-time bot messaging)
  • ETL loads (Extract, Transform, & Load)
  • Sending email reminder after some alert/event say insurance renewal
  • Automated billing reminder

Reference:-

https://functions.azure.comhttps://tryappservice.azure.com https://crontab.guru/  (useful to generate “Schedule” for timerbasedtriggers, don’t forget to add secondsl) https://www.troyhunt.com/azure-functions-in-practice/  https://mikhail.io/2017/03/azure-functions-as-facade-for-azure-monitoring/

Let me know if you have used Azure Functions for your interesting scenario.

Comments

  • Anonymous
    September 04, 2017
    Thanks