sorenandersen.com

Using EventBridge for decoupling and asynchronous processing

September 01, 2020

Event-driven architectures and AWS EventBridge has been a hot topic for a while now in the serverless space and since serverless by nature is event-driven I am equally enthusiastic. This is really how we should design resilient, scalable and maintainable serverless systems.

To wet my toes after watching Sessions With SAM (S1E3): Amazon EventBridge I took the opportunity to port the deployment of Eric’s sample code to the Serverless Framework.

The interesting part here is how to declare rules for matching events to its target(s), and as it turns out it is really easy. For instance the following function:

functions:
  sentiment:
    handler: functions/sentiment.handler
    events:
      - eventBridge:
          eventBus: ${self:custom.eventBus.arn}
          pattern:
            source:
              - demo.eventbridge.text-endpoint
            detail-type:
              - sentiment

… will be triggered by the following event:

await eventBridge.putEvents({
  Entries: [
    {
      Detail: JSON.stringify({ data: 'Event detail passed to the target' }),
      DetailType: 'sentiment'
      Source: 'demo.eventbridge.text-endpoint',
      EventBusName: process.env.EVENT_BUS_NAME,
    },
  ],
}).promise()

The custom event bus is declared in the resources section:

resources:
  Resources:
    CustomBus:
      Type: AWS::Events::EventBus
      Properties:
        Name: ${self:custom.eventBus.name}

custom:
  eventBus:
    name: ${self:service.name}-bus-${self:provider.stage}
    arn: arn:aws:events:#{AWS::Region}:#{AWS::AccountId}:event-bus/${self:custom.eventBus.name}

Knowing that we’re not doing any wonders here I think this small example still demonstrates what a remarkably low barrier there is to start building event-driven architectures.

The complete runnable example can be found here.

References


Søren Andersen

Digital garden of Søren Andersen.
Posts on tech that I use and learn.