Optimizing Laravel 11 for Serverless Deployment on AWS Lambda

Websolutionstuff | Sep-25-2024 | Categories : Laravel

In this guide, I'll walk you through how to optimize a Laravel 11 application for serverless deployment on AWS Lambda. Running Laravel on AWS Lambda can bring scalability and cost savings, but it also comes with challenges like cold starts, database connections, and file storage.

I'll explain these issues and provide practical solutions with step-by-step examples and code snippets. By the end of this article, you'll be ready to deploy your Laravel app efficiently on AWS Lambda.

Optimizing Laravel 11 for Serverless Deployment on AWS Lambda

 

Step 1: Prepare Laravel for AWS Lambda

To deploy Laravel on AWS Lambda, you'll need a solution that allows PHP applications to run in this environment. We'll use Bref, a serverless PHP framework that simplifies Laravel deployments on AWS Lambda.

Install Bref in your Laravel project:

composer require bref/bref

Configure serverless.yml for deployment: Create a serverless.yml file at the root of your Laravel project. This file defines how your app will be deployed to AWS Lambda.

service: laravel-on-lambda

provider:
  name: aws
  region: us-east-1
  runtime: provided.al2

functions:
  website:
    handler: public/index.php
    events:
      - http: 'ANY /'
      - http: 'ANY /{proxy+}'

plugins:
  - ./vendor/bref/bref

Set Laravel's storage path to tmp: AWS Lambda has a read-only file system, but it provides /tmp for temporary file storage.

Update config/filesystems.php to handle Lambda's file storage:

'lambda' => [
    'driver' => 'local',
    'root'   => env('LAMBDA_STORAGE_PATH', '/tmp'),
],

 

Step 2: Handle Cold Starts

 Cold starts occur when an AWS Lambda function is invoked after being idle, leading to longer initial response times.

To mitigate cold starts:

Optimize Autoloader: Enable optimized autoloading to reduce the time it takes to load classes.

composer install --optimize-autoloader --no-dev

Keep Lambda Warm: Use a warm-up plugin like serverless-plugin-warmup to keep the function active and reduce cold starts.

npm install serverless-plugin-warmup --save-dev

Add it to the serverless.yml:

plugins:
  - serverless-plugin-warmup

Reduce Bootstrapping Time: Remove unnecessary service providers in app.php to streamline the bootstrapping process.

 

Step 3: Managing Database Connections

 Database connections can be tricky on Lambda since it's a stateless environment. Traditional database connections can cause timeouts or connection exhaustion.

Use AWS RDS Proxy for handling MySQL or PostgreSQL connections: RDS Proxy pools and manages database connections, allowing your Laravel app to scale efficiently. Increase PDO connection retries in your database.php to prevent timeouts.

Update your DB_HOST in the env file.

DB_HOST=my-rds-proxy.endpoint.aws

Increase PDO connection retries in your database.php file 

'mysql' => [
    'retry_after' => 5,
    'retries' => 3,
],

 

Step 4: File Storage with AWS S3

Since Lambda is stateless, you cannot rely on local file storage. Instead, you can use AWS S3 for file uploads and storage.

Set up AWS S3 in config/filesystems.php:

'disks' => [
    's3' => [
        'driver' => 's3',
        'key'    => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],
],

Update the env file with AWS S3 credentials like AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION, AWS_BUCKET

Use S3 for file uploads:

$filePath = $request->file('upload')->store('uploads', 's3');

 

Step 5: Deploy Laravel to AWS Lambda

With all the optimizations in place, you're ready to deploy your Laravel application to AWS Lambda.

 Package your Laravel app for deployment:

serverless deploy

Test your API endpoint to ensure it's working efficiently:

curl https://your-api-endpoint.amazonaws.com/dev

 


You might also like:

Recommended Post
Featured Post
Laravel 8 Export Buttons In Datatables Example
Laravel 8 Export Buttons In Da...

In this article, we will see an example of laravel 8 export buttons in datatables. If you want to export data...

Read More

Oct-14-2020

How to Use Laravel Factory in Seeder
How to Use Laravel Factory in...

Laravel is a popular PHP framework known for its elegance and simplicity in building web applications. When it comes to...

Read More

Sep-13-2023

Laravel 8 Inner Join Query Example
Laravel 8 Inner Join Query Exa...

In this tutorial we will learn about laravel 8 inner join query example. Also see how to join two tables in laravel 8. I...

Read More

Nov-24-2021

Laravel 9 Image Upload Example
Laravel 9 Image Upload Example

In this tutorial, I will explain the laravel 9 image upload example. image or file upload is the most common task in web...

Read More

Feb-28-2022