Cloud

PHP in the Cloud: Serverless and Edge Computing

Deploy PHP to serverless platforms and edge networks. Covers AWS Lambda with Bref, Vercel Functions, Cloudflare Workers, and when serverless makes sense for PHP.

PHP application deployed across global edge network nodes

PHP was designed for the request-response cycle: process a request, return a response, clean up. This makes it a natural fit for serverless computing, where functions spin up per request and shut down when idle. The challenge has been runtime support—AWS Lambda and other serverless platforms did not natively support PHP.

In 2026, multiple solutions exist for running PHP serverlessly, each with different trade-offs.

AWS Lambda with Bref

Bref is the most mature solution for PHP on Lambda. It provides custom Lambda runtimes for PHP and integrates with the Serverless Framework.

Setup

1
2
3
4
5
# Install Bref
composer require bref/bref bref/laravel-bridge

# Install Serverless Framework
npm install -g serverless

Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# serverless.yml
service: my-php-app

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

plugins:
- ./vendor/bref/bref

functions:
web:
handler: public/index.php
runtime: php-84-fpm
timeout: 28
memorySize: 1024
events:
- httpApi: '*'
environment:
APP_ENV: production
DB_HOST: ${env:DB_HOST}
SESSION_DRIVER: cookie

artisan:
handler: artisan
runtime: php-84-console
timeout: 120

worker:
handler: Bref\LaravelBridge\Queue\QueueHandler
runtime: php-84
timeout: 60
events:
- sqs:
arn: !GetAtt JobsQueue.Arn

How Bref works

Bref creates Lambda layers containing the PHP runtime (PHP binary, extensions, php-fpm). When a request arrives:

  1. Lambda starts the PHP-FPM process (cold start: ~400ms)
  2. Nginx-like layer proxies the HTTP request to PHP-FPM
  3. PHP processes the request normally (your existing code works)
  4. Response is returned through API Gateway
  5. The Lambda instance stays warm for ~5-15 minutes

Cold start optimization

1
2
3
4
5
6
7
# Reduce cold starts by minimizing deployment package size
package:
patterns:
- '!tests/**'
- '!node_modules/**'
- '!.git/**'
- '!storage/logs/**'
1
2
// Optimize the autoloader for Lambda
// composer install --optimize-autoloader --no-dev
Optimization Cold start impact
Optimized autoloader -50ms
Remove dev dependencies -100ms
Smaller deployment package -50-200ms
Provisioned concurrency Eliminates cold start
More memory (1024MB → 2048MB) -100ms (more CPU)

What works on Lambda

  • Laravel (with bref/laravel-bridge)
  • Symfony (with bref/symfony-bridge)
  • Any framework using PSR-7/PSR-15
  • Stateless PHP applications

What does not work

  • File-based sessions (use Redis, DynamoDB, or cookies)
  • File uploads to local disk (use S3)
  • Persistent connections (WebSockets, long-polling)
  • Background processes or cron (use SQS + Lambda or EventBridge)

Laravel Vapor

Vapor is Laravel’s first-party serverless platform, built on AWS:

1
2
3
4
5
# Install Vapor CLI
composer require laravel/vapor-cli --dev

# Deploy
vendor/bin/vapor deploy production

Vapor handles infrastructure automatically: Lambda functions, API Gateway, SQS queues, S3 storage, CloudFront CDN, RDS databases, and ElastiCache.

Vapor vs Bref

Aspect Vapor Bref
Setup complexity Minimal (managed) Moderate (self-configured)
Framework support Laravel only Any PHP framework
Infrastructure Managed by Vapor You manage via serverless.yml
Cost $39/month + AWS AWS only
Customization Limited Full control
Queue handling Built-in SQS bridge Manual SQS configuration

Edge computing with PHP

Edge computing runs code at CDN nodes closest to the user. Response times are 5-50ms instead of 100-500ms from a central server.

Cloudflare Workers (experimental)

PHP does not run natively on Cloudflare Workers (which use V8/JavaScript). However, experimental projects compile PHP to WebAssembly (WASM) for edge execution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// worker.js using php-wasm
import { PHP } from 'php-wasm/web';

export default {
async fetch(request) {
const php = await PHP.load('8.4');
const result = php.run(`<?php
echo json_encode([
'message' => 'Hello from PHP at the edge',
'timestamp' => time(),
]);
?>`);
return new Response(result.text, {
headers: { 'Content-Type': 'application/json' },
});
},
};

This is experimental. PHP-WASM has limitations: no filesystem, no network extensions, no database connections. It works for computation and template rendering, not for full application hosting.

Vercel Serverless Functions

Vercel supports PHP through community runtimes:

1
2
3
4
5
6
7
8
// vercel.json
{
"functions": {
"api/*.php": {
"runtime": "vercel-php@0.7.0"
}
}
}
1
2
3
4
5
6
7
// api/hello.php
<?php
header('Content-Type: application/json');
echo json_encode([
'message' => 'Hello from Vercel',
'php_version' => phpversion(),
]);

Vercel PHP functions are limited compared to Lambda/Bref: fewer extensions, smaller payload limits, and shorter timeouts.

When serverless makes sense for PHP

Good use cases

  1. Variable traffic: Sites with unpredictable traffic (news sites, marketing pages) benefit from auto-scaling to zero.
  2. API endpoints: Stateless REST/GraphQL APIs map cleanly to Lambda functions.
  3. Scheduled tasks: Cron jobs that run for seconds, not minutes, are cheaper on Lambda than on a persistent server.
  4. Cost optimization at low traffic: A site with 1,000 requests/day costs pennies on Lambda vs $5-20/month for a server.

Bad use cases

  1. High-traffic sites: Above ~1M requests/month, a $20 VPS is cheaper than Lambda.
  2. WebSocket applications: Lambda has a 29-second timeout and no persistent connections.
  3. File-heavy applications: Local filesystem is ephemeral on Lambda.
  4. Legacy PHP applications: Code that assumes persistent state, file sessions, or specific server configuration is hard to port.

Cost comparison

Monthly cost for a PHP application handling 500K requests/month, averaging 200ms per request:

Platform Monthly cost Notes
Lambda (Bref) $4-8 Free tier: 1M requests/month
Laravel Vapor $39 + $4-8 AWS Managed platform fee
DigitalOcean droplet $6 1GB RAM, self-managed
Laravel Forge + DO $12 + $6 Managed server
AWS Fargate (container) $15-30 Auto-scaling containers

At low traffic (<100K requests/month), serverless is cheapest. At high traffic (>2M requests/month), a persistent server wins.

Migration path

Step 1: Verify statelessness

1
2
3
4
5
6
7
8
9
// Check for state that won't survive Lambda invocations
// ❌ File-based sessions
'driver' => 'file', // Change to 'cookie', 'redis', or 'dynamodb'

// ❌ Local file storage
Storage::disk('local')->put(...); // Change to Storage::disk('s3')

// ❌ In-memory caching between requests
static $cache = []; // Won't persist between invocations

Step 2: Test locally

1
2
# Bref provides a local Docker environment
vendor/bin/bref local web

Step 3: Deploy to staging

1
serverless deploy --stage staging

Step 4: Load test

1
2
# Use k6, Artillery, or wrk to simulate traffic
k6 run --vus 50 --duration 60s load-test.js

Step 5: Monitor cold starts

Watch CloudWatch metrics for Duration and Init Duration. If init times are too high, consider provisioned concurrency.

Common mistakes

Assuming serverless is always cheaper: At moderate-to-high traffic, serverless can cost 5-10x more than a VPS. Calculate costs at your expected traffic.

Ignoring cold starts: A 600ms cold start is unacceptable for an API powering a mobile app. Measure real cold starts, not best-case scenarios.

Using serverless for long-running processes: Lambda has a 15-minute timeout. Batch jobs and queue workers need different solutions.

Not reducing package size: A 100MB deployment package has 2x the cold start of a 20MB package. Remove dev dependencies, test files, and documentation.

FAQ

Can I run WordPress on Lambda?

Technically yes (with significant modification), but it is not practical. WordPress relies heavily on the filesystem and database queries that do not work well with Lambda’s ephemeral nature. Use traditional hosting for WordPress.

Is PHP-WASM production-ready?

No. It is an active research area with promising results but significant limitations. Use Lambda/Bref for production PHP serverless today.

Should I use Vapor or Bref?

If you use Laravel and want a managed experience, Vapor. If you want more control or use a different framework, Bref. Both use Lambda underneath.

Next steps

Start by running composer require bref/bref and deploying a simple PHP function to Lambda. Measure the cold start time with your actual dependencies. Then calculate the monthly cost at your expected traffic and compare it with traditional hosting.

For containerized PHP deployment (the alternative to serverless), the Docker guide covers production-ready Docker images. For understanding PHP performance in any deployment model, the performance optimization guide covers profiling and tuning.