Building Event-Driven Serverless Architecture with AWS EventBridge and Serverless Framework

Dixit R Jain
6 min readMay 6, 2023

--

In today’s world, modern software development is all about creating highly scalable, fault-tolerant, and cost-efficient solutions. In order to achieve this, serverless architecture has gained immense popularity in recent years. Serverless computing enables developers to focus on writing code without worrying about the infrastructure management.

Introduction to AWS EventBridge

AWS EventBridge is a serverless event bus service that makes it easy to connect your applications with data from a variety of sources. You can use EventBridge to build event-driven architectures that respond to changes in your AWS environment, as well as to events from your own custom applications.

EventBridge uses an event-driven architecture, where events are emitted by sources and consumed by targets. Sources can be AWS services like S3, EC2, and Lambda, or custom applications that emit events to the EventBridge event bus. Targets can be AWS services like SNS, SQS, and Lambda, or custom applications that subscribe to events from the event bus.

Introduction to Serverless Framework

The Serverless Framework is an open-source framework that makes it easy to build serverless applications on AWS, Azure, and Google Cloud. It provides a simple, yet powerful way to define your serverless application’s infrastructure, deployment, and configuration using YAML.

The Serverless Framework supports multiple programming languages and has a vast library of plugins that extend its functionality. With the Serverless Framework, you can quickly and easily deploy your serverless applications to the cloud, without the need for manual configuration or infrastructure management.

What we will learn:

In this tutorial, we’ll build an event-driven serverless architecture using AWS EventBridge and the Serverless Framework. We’ll create two Lambda functions: one that publishes an event to EventBridge, and another that consumes the event and logs it to the console along with an API Gateway POST endpoint which will be used to invoke the first lambda.

Prerequisites

Before we begin, you should have the following:

  • An AWS account
  • Node.js installed on your machine
  • The Serverless Framework installed globally on your machine (npm install -g serverless)
  • The aws-sdk npm package installed in your project

Creating the Serverless Project

First, let’s create a new Serverless project. Open your terminal and run the following commands:

serverless create --template aws-nodejs --path eventbridge-serverless-demo
cd eventbridge-serverless-demo
npm init -y
npm install aws-sdk

This will create a new Serverless project using the AWS Node.js runtime, and install the aws-sdk npm package in your project directory.

Writing the Lambda Functions

Now, let’s write the Lambda functions that will publish and consume events in EventBridge. Open the file called handler.js in your project directory, and add the following code (Replace the existing code with below code):

const AWS = require('aws-sdk');
const eventBridge = new AWS.EventBridge();

module.exports.publishEvent = async (event) => {
const params = {
Entries: [
{
Source: 'my-source',
DetailType: 'my-detail-type',
Detail: JSON.stringify(JSON.parse(event.body)),
},
],
};

try {
const data = await eventBridge.putEvents(params).promise();
console.log(`Event published: ${JSON.stringify(event.body)}`);
return {
statusCode: 200,
body: JSON.stringify(data),
};
} catch (err) {
console.log(err);
return {
statusCode: 500,
body: JSON.stringify({ message: err }),
};
}
};

module.exports.consumeEvent = async (event) => {
console.log(`Event consumed: ${JSON.stringify(event.detail)}`);
};

This file exports two Lambda functions — publishEvent and consumeEvent. The publishEvent function publishes an event to EventBridge, while the consumeEvent function logs the event when it is consumed.

Configuring the Serverless Project

Next, let’s configure the Serverless project by opening theserverless.yml file in your project directory and adding the following contents (Replace the existing code with below code):

service: eventbridge-serverless-demo
provider:
name: aws
runtime: nodejs18.x
region: us-east-1

iamRoleStatements:
- Effect: Allow
Action:
- events:PutEvents
Resource: '*'

functions:
publishEvent:
handler: handler.publishEvent
events:
- http:
path: publishEvent
method: post

consumeEvent:
handler: handler.consumeEvent
events:
- eventBridge:
name: publisherConsumerRule
pattern:
source:
- my-source

This configuration creates two Lambda functions: publishEvent and consumeEvent.

The publishEvent function is triggered by an HTTP POST request to the /publishevent endpoint. This function publishes an event to Amazon EventBridge using the putEvents API.

The consumeEvent function is triggered by an event rule with name publisherConsumerRule in Amazon EventBridge. This function consumes events that match the specified pattern, which in this case is any events with a source of my-source.

Setting Up AWS Credentials

To set up our AWS credentials, we need to create an AWS access key and secret key. Follow the steps below to create a new access key and secret key:

  1. Log in to the AWS Management Console and go to the IAM service.
  2. Click on “Users” in the left sidebar and then click on your username.
  3. Scroll down to the “Security credentials” section and click on “Create access key”.
  4. Click on “Download .csv file” to download your new access key and secret key.

To configure your AWS credentials, run the following command in your terminal:

serverless config credentials --provider aws --key <your-access-key-id> --secret <your-secret-access-key>

Replace <your-access-key-id> and <your-secret-access-key> with the Access Key ID and Secret Access Key that you have in the downloaded file from the previous step.

Deploying the Serverless Project

Finally, let’s deploy the Serverless project to AWS. Run the following command in your terminal:

serverless deploy

This command packages and deploys the Serverless project to AWS. Once the deployment is complete, you should see output similar to the following:

endpoints:
POST - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/publishEvent
functions:
publishEvent: eventbridge-serverless-demo-dev-publishEvent
consumeEvent: eventbridge-serverless-demo-dev-consumeEvent

Now make a note of API Gateway POST Endpoint generated here.

Testing the Serverless Project

To test the Serverless project, we can use the curl command to send an HTTP POST request to the /publishEvent endpoint:

curl -X POST -d '{"message":"Hello, world!"}' https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/publishEvent

Replace xxxxxxxxxx with actual value present in the endpoint generated by deploy command.

This command sends an HTTP POST request with a JSON payload containing a message field.

If the request is successful, you should see output similar to the following:

{"FailedEntryCount":0,"Entries":[{"EventId":"b4298738-990b-e003-7f2b-63c67195a2bd"}]}

This output indicates that the publishEvent function successfully published an event to AWS EventBridge.

To verify that the consumeEvent function received the event, we can check the logs for the function in the AWS Lambda console. Navigate to the consumeEvent function in the AWS Lambda console, and click the "Monitoring" tab. You should see the recent invocation cloudwatch log stream. Click the recent log stream and you should see below logs.

This output indicates that the consumeEvent function successfully consumed the event that was published by the publishEvent function.

Conclusion

In this tutorial, we explored how to build an event-driven serverless architecture using AWS EventBridge and the Serverless Framework. By combining the event producer and consumer functions in a single Serverless Framework project, we created a streamlined and efficient solution. We learned how to deploy the Lambda functions, trigger events through an API Gateway endpoint, and consume events using AWS EventBridge.

This event-driven architecture provides a scalable and decoupled approach to building serverless applications. It enables various components to communicate and react to events in a flexible and efficient manner. With AWS EventBridge and the Serverless Framework, developers can easily harness the power of event-driven architecture and build robust serverless applications.

Remember to properly manage AWS credentials and permissions, and feel free to explore further to enhance the functionality of your event-driven serverless application. Happy coding!

--

--

Dixit R Jain

Senior Software Development Engineer I at PowerSchool India Pvt Ltd. I work as full stack developer with javascript and AWS as my core technology.