Link EventBridge to SQS to lambda

Xander Verheij
ihomer academy
Published in
2 min readNov 18, 2022

--

Skip everything and look at some working (at time of writing) code: click here.

How to connect EventBridge to SQS to lambda using serverless framework typescript.

Example Use case:

Messages from eventbridge can not be batched.
However it can speed up certain use cases tremendously if you batch messages and handle them in one lambda invocation. A good example is when you need to communicate to a database system.

High Level Architecture Overview

To accomplish this we need to create a couple of resources:

  • EventBridge (the default is fine)
  • Policy to allow EventBridge to call SQS
  • EventRule
    To Connect EventBridge to SQS
  • SQS Queue
  • A Lambda function
serverless.ts:const serverlessConfiguration = {
...
functions: {
eventbridgeSqsLambda: {
handler: `./handler.main`,
events: [
{
sqs: {
arn: {
'Fn::GetAtt': ['Queue', 'Arn']
}
}
}
]
}
},
resources: {
Resources: {
Queue: {
Type: 'AWS::SQS::Queue'
},
EventRule: {
Type: 'AWS::Events::Rule',
Properties: {
Description: 'EventRule',
Name: 'EventbridgeToQueue',
EventPattern: {
source: [
{
prefix: 'example-prefix'
}
]
},
Targets: [
{
Arn: {
'Fn::GetAtt': ['Queue', 'Arn']
},
Id: 'SQSqueue'
}
]
}
},
EventBridgeToToSqsPolicy: {
Type: 'AWS::SQS::QueuePolicy',
Properties: {
PolicyDocument: {
Statement: [
{
Effect: 'Allow',
Principal: {
Service: 'events.amazonaws.com'
},
Action: 'SQS:SendMessage',
Resource: {
'Fn::GetAtt': ['Queue', 'Arn']
}
}
]
},
Queues: [
{
Ref: 'Queue'
}
]
}
}
}
}
}
module.exports = serverlessConfiguration;

At https://github.com/IHomer/eventbridge-sqs-lambda you can find working code you can deploy yourself. Testing is easy just open two consoles, one for sending a message, one for receiving the message.
And run the following commands in the two separate consoles:

npx sls logs -t -f eventbridgeSqsLambdaaws events put-events --entries file://mock-events.json

--

--