Serverless Laravel on AWS Lambda with Bref and Terraform

Mahmut Sarıkaya 4 dk okuma 3 Görüntülenme 0
Serverless Laravel on AWS Lambda with Bref and Terraform

Why consider serverless for Laravel?

Imagine a Laravel application that scales from zero to thousands of requests per second without touching a single EC2 instance. In 2023, AWS reported that over 30% of new applications were built on serverless platforms, driven by the promise of automatic scaling and pay‑per‑use pricing. For Laravel developers, the combination of Bref and Terraform turns that promise into a reproducible workflow.

Prerequisites and system requirements

Before writing any code, make sure you have:

  • PHP 8.1 or newer installed locally.
  • Composer 2.x.
  • A Git‑enabled repository.
  • A AWS account with IAM permissions for Lambda, API Gateway, and IAM role creation.
  • Terraform 1.5 or later.

All tools are cross‑platform; the guide assumes a Unix‑like shell.

Setting up Bref in a Laravel project

Start with a fresh Laravel installation or an existing project. Adding Bref is a single Composer command, then a small configuration change.

composer require bref/bref "^1.6"

Next, publish the Bref configuration file so you can customize the runtime and layers:

php artisan vendor:publish --provider="Bref\BrefServiceProvider"

The generated serverless.yml will later be ignored because Terraform will provision the infrastructure, but keeping it helps local testing with bref local.

Defining the Lambda handler with Bref

Create a serverless.php file at the project root. This file tells Bref how to bootstrap Laravel inside the Lambda execution environment.

<?php

require __DIR__.'/vendor/autoload.php';

use Illuminate\Support\Facades\Route;

Route::get('/hello', function () {
    return 'Hello from Laravel on Lambda!';
});

return \Bref\Laravel\Bridge::run();

The route definition is optional – you can rely on the normal routes/web.php file – but adding a quick endpoint demonstrates that the handler works before you package the application.

Infrastructure as code with Terraform

Terraform replaces the manual steps of creating a Lambda function, an API Gateway, and the required IAM role. Store the following main.tf in a infra directory.

provider "aws" {
  region = "us-east-1"
}

resource "aws_iam_role" "lambda_exec" {
  name = "lambda_exec_role"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Principal = { Service = "lambda.amazonaws.com" }
    }]
  })
}

resource "aws_lambda_function" "laravel" {
  function_name    = "laravel-bref"
  filename         = "../lambda.zip"
  handler          = "index.php"
  runtime          = "provided.al2"
  role             = aws_iam_role.lambda_exec.arn
  source_code_hash = filebase64sha256("../lambda.zip")
  memory_size      = 1024
  timeout          = 30
}

resource "aws_api_gateway_rest_api" "laravel_api" {
  name = "laravel-api"
}

resource "aws_api_gateway_resource" "proxy" {
  rest_api_id = aws_api_gateway_rest_api.laravel_api.id
  parent_id   = aws_api_gateway_rest_api.laravel_api.root_resource_id
  path_part   = "{proxy+}"
}

resource "aws_api_gateway_method" "any" {
  rest_api_id   = aws_api_gateway_rest_api.laravel_api.id
  resource_id   = aws_api_gateway_resource.proxy.id
  http_method   = "ANY"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "lambda" {
  rest_api_id = aws_api_gateway_rest_api.laravel_api.id
  resource_id = aws_api_gateway_resource.proxy.id
  http_method = aws_api_gateway_method.any.http_method
  integration_http_method = "POST"
  type = "AWS_PROXY"
  uri = aws_lambda_function.laravel.invoke_arn
}

The lambda.zip artifact is produced by Bref’s bref build command (see next section). Terraform references it via a relative path, keeping the repository tidy.

Deploying with Terraform

Run the classic Terraform workflow:

cd infra
terraform init
terraform plan -out=tfplan
terraform apply tfplan

Terraform will create the IAM role, upload the zip, configure the Lambda function, and expose it through an HTTP API Gateway. The output includes the invoke_url – copy it for testing.

Testing the API Gateway endpoint

After the apply finishes, verify the deployment with a simple curl request:

curl https://{api-id}.execute-api.us-east-1.amazonaws.com/hello

You should see the string Hello from Laravel on Lambda!. If you receive a 502 error, check the CloudWatch logs for the Lambda – they often reveal missing environment variables or permission issues.

Performance and cost considerations

Lambda cold starts for a PHP runtime are typically under 800 ms when you allocate 1024 MB of memory, according to Bref benchmarks (2022). For traffic spikes, API Gateway automatically distributes load, and you only pay for the compute time used – roughly $0.000016 per GB‑second in the US‑East‑1 region. A modest 100,000 requests per month with an average execution time of 200 ms would cost less than $2, a dramatic reduction compared to a t3.micro EC2 instance running 24/7.

Conclusion

By combining Laravel, Bref, and Terraform you gain a repeatable, version‑controlled pipeline that transforms a traditional monolith into a truly serverless API. The steps – installing Bref, creating a handler, packaging with bref build, and describing the infrastructure in Terraform – can be scripted in CI/CD, enabling zero‑downtime releases and automatic scaling. The result is a lean, cost‑effective backend that lets you focus on business logic instead of server management.

Author: Mahmut Sarıkaya — sarikayadev.com

Sources

  • Official Bref documentation
  • AWS Lambda PHP runtime guide
  • Terraform AWS Provider reference
Etiketler: #Laravel serverless #Bref #AWS Lambda #Terraform #API Gateway
Paylaş:
M

Yazar

Mahmut Sarıkaya

yazılım Geliştirici

Yorumlar

Henüz yorum yok. İlk yorumu siz yapın!

Yorum Bırakın

3 + 2 =