In this post, we will briefly introduce Serverless architecture and discuss how it is an optimal solution for handling event-driven processing.
Serverless is an architectural paradigm in which either a function or a microservice can be hosted on a cloud server without the server running continuously; it is an event-driven approach where each execution starts, runs a small process to meet the request, and stops at the end. Some of its defining characteristics are:
To explain how Serverless architecture works, let's consider an example where we create a Serverless function that calculates BMI (Body Mass Index) through a Telegram chatbot. Passing aleatory commands to the bot, we will receive the right command syntax to write in order to tell the bot to calculate BMI. When the user enters his weight and height information, the bot will convey this to the Serverless function; the function will then calculate the BMI and send the result back to the user, as depicted in the chart below:
Chatbot flow
With this "big picture" chart in mind, let's examine the individual components involved in this process. First, we have created a Telegram chatbot following these steps. The bot's function is to receive a request and pass it along either through a pre-configured webhook or through a pooling model, which makes background requests for the chatbot server.
In our case, we are using the webhook mechanism. This means that when a message is sent, the Telegram chatbot server will redirect the request to a specific endpoint already configured in the webhook. This request then goes with the chatbot payload so that our FaaS can receive and process the message.
Setting webhook
For this example, we have used Google Functions as our FaaS provider, which requires a valid Google Account in Google Cloud. We access Google Cloud through the dashboard panel, where we click "Main Menu" - "Cloud Functions."
We then create a function called "function-bot," exposing an HTTP endpoint, but we can also choose other trigger types, such as pub/sub or Cloud storage buckets. When creating a function, users can specify the memory size to be allocated as well as the code that will be the main execution function. The code must be in Node.js at this time and can be put into an inline editor, zip package upload, or Cloud repository. The function follows the Express.js framework standards, receiving a request and response as input parameters. The Serverless function code that receives the chatbot webhook request operates as follows:
const request = require('request').defaults({ encoding: null }); let url = "https://api.telegram.org/token/sendMessage?chat_id=chat_id&text=$message"; /** * Responds to any HTTP request that can provide a "message" field in the body. * * @param {!Object} req Cloud Function request context. * @param {!Object} res Cloud Function response context. */ exports.bmi = (req, res) => { if (req.body.message === undefined) { // This is an error case, as "message" is required. res.status(400).send('No message defined!'); } else { // Everything is okay. console.log(req.body.message); let message = req.body.message.text; let re = /\d\d\/\d\d\d/; if(!message.match(re)) { sendMessage("Put Weight in Kilograms/Height in centimeters to calculate your BMI. Ex 87/188"); return res.status(200).end(); } let weight = message.split("/")[0]; let height = message.split("/")[1]/100; let num_result = weight/Math.pow(height,2); console.log(num_result) if(num_result >= 25) { sendMessage("You are in overweight range."); } else if(num_result > 18.5 && num_result < 25) { sendMessage("You are in healthy range"); } else { sendMessage("You are in underweight range."); } return res.status(200).end(); } }; function sendMessage(message) { let newUrl = url.replace("$message", message) request.get(newUrl, (error, response, body) => { let json = JSON.parse(body); console.log(json); }); }
The above code illustrates how, after this BMI processing, we must call the Telegram chatbot URL with the BMI level as the payload message. Once all configurations have been completed, we can publish our function. At this point, our system is able to execute through the HTTP endpoint. Since we have completed all the steps to execute our chatbot, we can access the bot, which we named "myhealthybot," through the Telegram interface. We can start the chat by listing weight and height information.
The chatbot response is instantaneous.
In the example above, we've created a simple chatbot to illustrate how quickly and simply you can create Serverless functions, which are scalable and affordable options for handling asynchronous processing. The market at large is utilizing tools like Serverless more and more, so be sure to take some time to explore all the uses of this architecture for your own business.
Cheers!
https://core.telegram.org/bots/api
https://martinfowler.com/articles/serverless.html
https://aws.amazon.com/lambda/
https://azure.microsoft.com/en-us/services/functions/
https://cloud.google.com/functions/