MauroBaptista.com

Running Laravel Workers in AWS Lambda

Laravel AWS Lambda

In the post Releasing a Laravel app in Lambda using Serverless framework we were exposed to how to set up your Laravel app in AWS Lambda, now we are going a little bit more complex, and set the workers.

First, to do that, we will need to use different AWS services, such as RDS and Elasticache. To do that, we will need to add Lambda in the same VPC as these services. So, we need to configure the Security Groups and, also, the Subnet Ids.

1provider:
2 ...
3 vpc:
4 securityGroupIds:
5 - sg-***
6 subnetIds:
7 - subnet-***
8 - subnet-***
9 ...

As we are going to trigger the Lambda using the AWS SQS, we also need to give the proper access to:

1provider:
2 ...
3 iamRoleStatements:
4 - Effect: Allow
5 Action:
6 - sqs:SendMessage
7 - sqs:DeleteMessage
8 - sqs:ReceiveMessage
9 Resource: arn:aws:sqs:*:*:${self:custom.sqs}
10 ...

Now, as the other post, let's add some custom variables:

1custom:
2 ...
3 stage: ${opt:stage, self:provider.stage}
4 prefix: ${self:service}-${self:custom.stage}
5 worker: ${self:custom.prefix}-worker
6 sqs: ${self:custom.prefix}-main

This way we are going to use a queue named something like my-project-production-main.

In our functions we need to set the worker:

1functions:
2 ...
3 worker:
4 name: ${self:custom.worker}
5 handler: worker.php
6 layers:
7 - ${bref:layer.php-81}
8 events:
9 - sqs:
10 arn: !GetAtt MainQueue.Arn
11 batchSize: 1

And, at last, we need to create the needed resource:

1resources:
2 Resources:
3 MainQueue:
4 Type: AWS::SQS::Queue
5 Properties:
6 QueueName: ${self:custom.sqs}
7 MessageRetentionPeriod: 1209600
8 VisibilityTimeout: 60
9 RedrivePolicy:
10 deadLetterTargetArn:
11 Fn::GetAtt:
12 - MainDeadLetterQueue
13 - Arn
14 maxReceiveCount: 3
15 MainDeadLetterQueue:
16 Type: AWS::SQS::Queue
17 Properties:
18 QueueName: ${self:custom.sqs}-dead-letter-queue
19 MessageRetentionPeriod: 1209600