In this post I will show how to create a serverless Azure function.
Cloud Hosting
Instead of on-premise hardware, most projects now opt for some form of cloud hosted infrastructure. This means we can provision new servers by the click of a button in a portal as supposed to manually configuring infrastructure from scratch.
Cloud hosting in its traditional form gives you the hardware, but leaves it to you to configure the actual runtime application. An example of this is deploying a NodeJs application to Azure. Azure gives you everything you need in terms of the hosting environment, but you still have to know how to properly configure the NodeJs hosting application to expose the api.
Serverless
Serverless functions are a simplification of this model where you only worry about deploying code in the form of a simple function, but leave it to the platform to provide a software host that will expose the function. A typical setup is to make the function available over http, but the key point is that you don’t have to worry about explicitly exposing an endpoint to call the function.
The name serverless may seem like a misnomer since we are still dealing with a server somewhere to expose the “serverless” function. Personally I think the name is good since to me it refers to removing the software server layer (e.g. Node host) that you otherwise would have to create manually. Still, in practice the benefits of this are not necessarily mind blowing, but there are a few other aspects to consider.
On Demand Hosting
The serverless hosting model allows us to host a function as freestanding code that only gets activated on demand when a call is made. This means we are only billed for actual invocations of the function. The traditional hosting model requires us to pay for a host process that is running 24-7, but with serverless we don’t pay for idle hosting.
Demo
My specific use case for deploying a serverless function is a query of my most recent articles to power my blog’s main landing page. I have included the code for my serverless recent_articles function below:
In addition to the boilerplate code create by the Visual Studio serverless function template, I have included a helper class to retrieve articles from MongoDB. I am omitting the ArticleService implementation for brevity.
There you have it. This is all you need to configure a serverless function in Azure. Every time you visit my main landing page the server less function is called if the data wasn’t already cached.