Using Amazon Lambda with Amazon EventBridge

In today's fast-paced world of cloud computing, serverless architecture has emerged as a game-changer for developers seeking efficient and scalable solutions. Amazon Web Services (AWS) offers a powerful combination of services to make serverless development a breeze. One such pairing is Amazon Lambda and Amazon EventBridge, a dynamic duo that enables event-driven, serverless computing. In this comprehensive guide, we will explore how to use Amazon Lambda with Amazon EventBridge, providing valuable insights and practical tips for developers.

AWS SAM Template to Spin It Up

When embarking on a serverless journey with Amazon Lambda and Amazon EventBridge, the journey begins with infrastructure as code (IaC). AWS Serverless Application Model (SAM) simplifies the process of defining the AWS resources required for your serverless application.

To get started, you'll need to create an AWS SAM template. This template defines your application's AWS resources, including Lambda functions and EventBridge rules. We'll walk you through the process, covering:

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
  • AWSTemplateFormatVersion: This specifies the format version of the AWS CloudFormation template. In this case, it's set to '2010-09-09', which is a standard version.
  • Transform: This indicates the transformation that should be applied to the template. In this template, it's set to 'AWS::Serverless-2016-10-31', which means it's a SAM template for serverless applications.

Now let's dive into the resources defined in the template:

Resources:
  MyEventBridgeLambdaFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
  • Resources: This section defines AWS resources, in this case, a Lambda function.
  • MyEventBridgeLambdaFunction: This is a user-defined logical name for the Lambda function resource.
  • Type: Specifies the AWS resource type, which is 'AWS::Serverless::Function' in this case, indicating it's a Lambda function managed by SAM.
      Handler: index.handler
      Runtime: nodejs14.x
      CodeUri: ./src
      FunctionName: my-eventbridge-lambda
      Description: Lambda function to process events from EventBridge
      MemorySize: 128
      Timeout: 10
  • Handler: This is the name of the file (without the file extension) and the name of the exported function within that file that AWS Lambda uses as an entry point. In this case, it's index.handler, which means AWS Lambda will look for a file named index.js (or equivalent) and use the handler function as the entry point.
  • Runtime: Specifies the runtime environment for the Lambda function, which is nodejs14.x in this example.
  • CodeUri: Specifies the location of the Lambda function code. In this case, it's expected to be in the ./src directory.
  • FunctionName: This is the name of the Lambda function as it will appear in AWS. It's set to my-eventbridge-lambda.
  • Description: Provides a brief description of the Lambda function.
  • MemorySize: Specifies the amount of memory allocated to the Lambda function, which is 128 MB in this case.
  • Timeout: Sets the maximum time (in seconds) that the Lambda function can run before it's terminated.
      Role: !GetAtt MyEventBridgeLambdaFunctionRole.Arn
      Events:
        EventBridgeEvent:
          Type: EventBridgeRule
          Properties:
  • Role: Specifies the IAM (Identity and Access Management) role assumed by the Lambda function. In this case, it's referencing the IAM role defined below as MyEventBridgeLambdaFunctionRole.
  • Events: This section defines the events that trigger the Lambda function. In this template, it's set to trigger the function when an event matching the EventBridge rule name EventBridgeEvent occurs.
            EventBusName: default
            Pattern:
              source:
                - "your.source.namespace"
              detail:
                eventType:
                  - "yourEventType"
  • EventBusName: Specifies the name of the EventBridge event bus where events are received. In this example, it's set to default, which is the default event bus.
  • Pattern: Defines the event pattern to match. It's set to match events with a specific source namespace ("your.source.namespace") and event type ("yourEventType"). You should replace these placeholders with your actual source namespace and event type.
  MyEventBridgeLambdaFunctionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: MyEventBridgeLambdaFunctionRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Policies:
        - PolicyName: LambdaEventBridgePolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - 'logs:CreateLogGroup'
                  - 'logs:CreateLogStream'
                  - 'logs:PutLogEvents'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'events:PutEvents'
                Resource: '*'
  • MyEventBridgeLambdaFunctionRole: This defines the IAM role that the Lambda function assumes. It has a name of MyEventBridgeLambdaFunctionRole.
  • AssumeRolePolicyDocument: Specifies the policy that grants the Lambda service the permission to assume this role.
  • Policies: Defines the policies attached to this IAM role. It includes permissions to create and write logs to CloudWatch Logs and to put events into EventBridge.

The complete template is available below.

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'

Resources:
  MyEventBridgeLambdaFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: index.handler
      Runtime: nodejs14.x
      CodeUri: ./src
      FunctionName: my-eventbridge-lambda
      Description: Lambda function to process events from EventBridge
      MemorySize: 128
      Timeout: 10
      Role: !GetAtt MyEventBridgeLambdaFunctionRole.Arn
      Events:
        EventBridgeEvent:
          Type: EventBridgeRule
          Properties:
            EventBusName: default
            Pattern:
              source:
                - "your.source.namespace"
              detail:
                eventType:
                  - "yourEventType"

  MyEventBridgeLambdaFunctionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: MyEventBridgeLambdaFunctionRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Policies:
        - PolicyName: LambdaEventBridgePolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - 'logs:CreateLogGroup'
                  - 'logs:CreateLogStream'
                  - 'logs:PutLogEvents'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'events:PutEvents'
                Resource: '*'

Example of a Lambda Code in TypeScript

Now that you have your serverless application infrastructure defined, it's time to write the Lambda function code.

// Import the AWS SDK for Node.js
import { Handler } from 'aws-lambda';

// Define the Lambda handler function
export const handler: Handler = async (event) => {
  try {
    // Extract the message from the event
    const message = JSON.parse(event.body);

    // Your processing logic here
    // For example, you can log the message or perform some data processing
    console.log('Received message:', message);

    // Return a response (if needed)
    return {
      statusCode: 200,
      body: JSON.stringify({ message: 'Message processed successfully' }),
    };
  } catch (error) {
    console.error('Error processing message:', error);

    // Return an error response
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'Internal Server Error' }),
    };
  }
};
  • We import the Handler type from the 'aws-lambda' module to define our Lambda handler function.
  • The Lambda handler function handler receives the event object, which contains the data sent by EventBridge.
  • We assume that the message sent by EventBridge is in JSON format. We parse it using JSON.parse(event.body) to extract the message.
  • You can replace the comment Your processing logic here with your actual processing logic for the received message. For example, you might want to store the message in a database, send it to another service, or perform any other custom processing.
  • The code logs the received message for debugging purposes.
  • Finally, the Lambda function can return a response (e.g., an acknowledgement) if needed. In this example, it returns a 200 OK response with a simple JSON message.

Use Cases: Where can you use it?

The integration of AWS Lambda and Amazon EventBridge opens up a wide range of powerful use cases for event-driven, serverless architectures. Here are some common use cases where AWS Lambda and EventBridge integration can be employed:

  1. Real-time Data Processing: Lambda functions can be triggered by events from EventBridge when new data arrives, enabling real-time processing. For example, you can process incoming data streams, perform analytics, and take immediate actions based on the data.
  2. Automated Workflows: EventBridge can orchestrate automated workflows by triggering Lambda functions in response to various events. This is useful for streamlining business processes, such as order processing, document approvals, or customer onboarding.
  3. Event-Driven Microservices: Lambda and EventBridge are well-suited for building event-driven microservices architectures. Each microservice can publish events to EventBridge when it completes its task, and other microservices can subscribe to these events to respond accordingly.
  4. Serverless Webhooks: You can use Lambda functions triggered by HTTP requests via API Gateway. EventBridge can then route these HTTP events to specific functions, allowing you to create dynamic, serverless webhooks for third-party integrations.
  5. Scheduled Tasks: EventBridge can schedule Lambda functions to run at specific times or intervals. This is valuable for running maintenance tasks, generating reports, or executing cleanup operations at predefined schedules.
  6. Monitoring and Alerting: Lambda functions can process CloudWatch Events sent by EventBridge. This is crucial for creating custom monitoring and alerting systems based on specific events or thresholds.
  7. Data Ingestion and Transformation: EventBridge can ingest data from various sources and trigger Lambda functions to transform and load it into databases or data warehouses. This is commonly used for ETL (Extract, Transform, Load) processes.
  8. Centralized Logging and Auditing: EventBridge can aggregate logs and events from multiple AWS accounts and services. Lambda functions can then process and store these events for centralized logging, auditing, and compliance purposes.
  9. Cross-Account Event Routing: EventBridge allows you to route events across different AWS accounts. This is beneficial for building multi-account architectures, enabling account isolation, and facilitating centralized event processing.
  10. Third-Party Integrations: EventBridge can integrate with third-party SaaS applications using partner event buses. Lambda functions can respond to events from these external services, enabling seamless automation and integration with external systems.
  11. Custom Authentication and Authorization: Lambda functions can implement custom authentication and authorization logic based on events from EventBridge. This can be used to enforce fine-grained access control in your applications.
  12. Dynamic Resource Scaling: EventBridge can trigger Lambda functions to automatically scale resources based on event-driven demand. This is valuable for handling burst workloads, such as image or video processing during peak traffic.
  13. User Activity Tracking: Lambda functions can process user activity events captured by EventBridge. This allows you to track user interactions and behaviour in your applications, which can be useful for analytics and user engagement optimization.

These use cases demonstrate the flexibility and versatility of AWS Lambda and Amazon EventBridge integration in building event-driven, serverless applications. By combining the power of event-driven architecture with serverless computing, you can create scalable, efficient, and responsive systems tailored to your specific needs.

Conclusion

In conclusion, the integration of AWS Lambda and Amazon EventBridge represents a paradigm shift in modern application development. It empowers developers to build highly scalable, event-driven architectures that respond to real-time events and automate workflows with ease.

As you explore the endless possibilities of AWS Lambda and EventBridge, stay updated with the latest trends, best practices, and insightful articles in the world of AWS and cloud computing. To keep your knowledge fresh and your skills sharp, consider becoming a subscriber of AWSMag.com, where you'll find a treasure trove of valuable content, tutorials, and expert insights on AWS services, serverless computing, and much more.

Don't miss out on the opportunity to stay ahead in the ever-evolving world of cloud technology. Sign up for AWSMag.com today and join a community of like-minded professionals who are passionate about AWS and the limitless potential it offers for your projects and career.