All Articles

Sending Slack notifications via AWS Lambda

At Drover the backend is written in Ruby and we have several Slack channels to which we send notifications regarding the status of some background jobs.

These notifications can be something like some vehicle failed to be booked or we failed to purchase insurance for some driver. They’re mostly to help out the people working on the back office, letting them know that something didn’t go as expected.

These notifications are sent via Slack’s ruby gem. The gem itself is quite lightweight but we are thinking on moving to a more microservices oriented architecture so we decided to experiment with Amazon Lambda to send the notifications instead.

For this I’m supposing you already have an AWS account configured and are familiar with the concepts of SQS and Lambda. The architecture of this simple system can de described as follows:

Everytime we need to push a notification to Slack, our backend app (running on EC2) sends a message to a dedicated queue on SQS. We chose to send a message to SQS instead of invoking the Lambda directly to avoid keeping the app waiting for the function to respond, instead posting a message to a queue is blazing fast and the app can continue working seamlessly. The message contains all the information for displaying the message, as in which channel to post it, the text, and some customization options like color.

./Slack-Lambda.png

This Lambda is configured to be triggered every time a new message is pushed onto the dedicated queue (this can be done easily on the AWS Lambda UI).

The function for sending the notifications to Slack is written in Python, due to it an easy language to use, having no cold start times on Lambda. The assembly of the deployment package is also fast as we’re only using libraries that are already included on AWS Lambda environment (json and requests).

Slack’s API only requires you to send a POST HTTP request to a specified URL to post a message on a channel, so the core of the function may look like this:

requests.post(slack_webhook_url, data=str(body['message_data']))

And that’s it, once you set everything up you can remove the gem from your Gemfile and you’ve entered the world or serverless computing with this simple use case.

So what did you think of it? Hit me up on Twitter with your thoughts and opinions.