Select your cookie preferences

We use cookies and similar tools to enhance your experience, provide our services, deliver relevant advertising, and make improvements. Approved third parties also use these tools to help us deliver advertising and provide certain site features.

SQS to Lambda

Created with SnapSQSAWS Lambda

Create a Lambda function that subscribes to an SQS queue

The SAM template deploys a Lambda function, an SQS queue and the IAM permissions required to run the application. SQS invokes the Lambda function when new messages are available.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless patterns - SQS to Lambda (uksb-1tthgi812) (tag:sqs-lambda)

Resources:
  # Define the SQS queue
  MySqsQueue:
    Type: AWS::SQS::Queue

  # Define the consumer Lambda function
  QueueConsumerFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: src/
      Handler: app.handler
      Runtime: nodejs18.x
      Timeout: 3
      MemorySize: 128
      Events:
        MySQSEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt MySqsQueue.Arn
            BatchSize: 10
Outputs:
  QueueConsumerFunction:
    Description: QueueConsumerFunction function name
    Value: !Ref QueueConsumerFunction
  
  SQSqueueName:
    Description: SNS queue name
    Value: !GetAtt MySqsQueue.QueueName

  SQSqueueARN:
    Description: SQS queue ARN
    Value: !GetAtt MySqsQueue.Arn

  SQSqueueURL:
    Description: SQS queue URL
    Value: !Ref MySqsQueue

< Back to all patterns


GitHub icon Visit the GitHub repo for this pattern.

Download

git clone https://github.com/aws-samples/serverless-patterns/ cd serverless-patterns/sqs-lambda

Deploy

sam deploy --guided


Testing

Use the AWS CLI to send a message to the SQS queue and observe the event delivered to the Lambda function:
1. Delete the stack: sam delete --stack-name STACK_NAME.
1. Send the SQS message: aws sqs send-message --queue-url ENTER_YOUR_SQS_QUEUE_URL --message-body "Test message"
2. Retrieve the logs from the Lambda function: sam logs -n ENTER_YOUR_CONSUMER_FUNCTION_NAME.

Cleanup

1. Delete the stack: sam delete --stack-name STACK_NAME.
2. Confirm the stack has been deleted: aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"

James Beswick

Presented by James Beswick

I am a self-confessed serverless geek and enjoy helping developers build faster with serverless! I have been software developer and product manager before becoming a Developer Advocate. Ask me anything!

Follow on LinkedIn