AWS Event Bridge with Custom bus and Serverless Framework

Have you wondered what is EventBridge and how do you start using it with serverless? Well then this article is for you.

So, what exactly is Event Bridge?

In simple terms Event Bridge provides a “Bus” in which events can be pushed and then can be consumed via a service. AWS already has got a default event bus wherein all the events generated by various AWS services (Lambda, SQS, DynamoDb etc) are pushed.

We can either write services that listen to these default events, or we can create a new bus altogether where we can push and consume our own custom events.

This article will shows how a new custom Event Bus can be created and how we can then consume its events via Lambda functions.

The first step is to create a new Event Bus in the AWS console:

Go to “Amazon EventBridge”, under Events, click on “Event buses”
In the Event Bus Console, Click Create event bus

Add a name for your event bus and then click on “Create”. (You can define Resource based policy if you want to grant permissions to access/manage events to another account or to all members of your AWS Organisation else just leave it empty for now).

Now that we have our Event Bus in place, we can add and consume events from this bus. So to get started, Let us write a function that will put events to this Bus:

import {EventBridge} from "aws-sdk";module.exports.addEventToBridge = async (val: number, context: any) => {
try {
const source = "com.test";
const detailType = Number(val) % 2 === 0 ? "Even Number" : "Odd Number";
await addEventToEventBridge(val, detailType, source);
return callback(null, "DONE", context);
} catch (err) {
console.log(err);
callback(err, {}, context);
throw err;
}
};
const addEventToEventBridge = async (value: string, detailType: string, source: string) => {
const eventBridge = new EventBridge();
const params = {
Entries: [{
Detail: JSON.stringify({value}),
DetailType: detailType,
EventBusName: "TestBus",
Source: source,
Time: new Date(),
}],
};
return await eventBridge.putEvents(params).promise();
};

This is a simple function that pushes events consisting of some numeric data. Each event must have a “Source” and a “DetailType”. The source helps identify the origin of the event. It could be any of the custom source like “com.test.source”. The “DetailType” helps in identifying the event detail. For eg: “OrderPlaced”, “PaymentRecieved”, etc. The “Detail” field consists of the JSON stringified event data.

The above function (addEventToBridge) is simply pushing events to the based on what type of number is received in its args.

Once we have events being pushed to the Event Bridge, we can add some logic to consume these events.

Let us create 2 Lambdas: One will listen events of type “Even Number” and other with type “Odd Number”. It is also possible for a lambda to listen to multiple event detail types.

So here we go:

Lambda listening to events added by event bridge

module.exports.eventBridgeListen1 = async (event: any, context: any) => { 
try {
console.log(event?.detail?.value);
// Processing Logic
return callback(null, "DONE", context);
} catch (err) {
console.log(err);
callback(err, {}, context);
throw err;
}
};

The event payload is received in “event.detail” field when the lambda is invoked via the Event Bridge.

The complete serverless file will look something like this:

service: eventbridge-test
provider:
name: aws
runtime: nodejs12.x
region: us-west-1
memorySize: 2000
timeout: 900
deploymentBucket:
name: test-deploy-bucket
iamRoleStatements:
- Effect: "Allow"
Action:
- "events:PutEvents"
Resource: custom-bus-arn
functions:
eventBridgeListen:
handler: dist/lambda.eventBridgeListen
reservedConcurrency: 1 #optional
events:
- eventBridge:
eventBus: custom-bus-arn
pattern:
source:
- com.test
eventBridgeDetailedEvent1:
handler: dist/lambda.eventBridgeListen1
reservedConcurrency: 1 #optional
events:
- eventBridge:
eventBus: custom-bus-arn
pattern:
source:
- com.test
detail-type:
- Odd Number
eventBridgeDetailedEvent2:
handler: dist/lambda.eventBridgeListen2
reservedConcurrency: 1 #optional
events:
- eventBridge:
eventBus: custom-bus-arn
pattern:
source:
- com.test
detail-type:
- Even Number
- Special Number

The above serverless file will create 3 Lambdas. One will listen to all the events added into our custom bus having source “com.test”. The second one will listen to events having source “com.test” and detail type as “Odd Number”. The third one will listen to events having source “com.test” and detail type as “Odd Number” or “Special Number”.

The concurrency for each of these lambdas is set to 1 in the above code. This means that only one instance of lambda will execute at a time. It comes in useful particularly when you want to process exactly one event at a time. Note: This is not a mandatory field and

In case of throttling, the events will retry to get executed until a certain limit is reached.

Default Limits:
The maximum number of hours unprocessed events are kept is 24 hours. The maximum number of times an event is retried for sending to a target after an error occurs (including throttling) is 185 times.

The above defaults can be overridden according to application requirements.

In Closing:

Event-driven architectures have three key components: event producers, event routers, and event consumers. A producer publishes an event to the router, which filters and pushes the events to consumers. Producer services and consumer services are decoupled, which allows them to be scaled, updated, and deployed independently.

Using EventBridge it is possible to trigger and communicate effectively between different decoupled events and update the state of the system effectively

Serverless EventBridge Documentation: https://www.serverless.com/blog/eventbridge-use-cases-and-tutorial

Full Stack Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store