Serverless PHP Options in 2026 Compared

Khimananda Oli 8 min read Cloud
Serverless PHP Options in 2026 Compared

By Khimananda Oli | Last reviewed: August 2026

Running PHP without managing servers has matured from experimental hacks to a viable production strategy, but choosing the right platform remains confusing. This guide breaks down Serverless PHP Options in 2026 Compared across AWS, Google Cloud, and Azure, focusing on real-world constraints like cold starts, filesystem limitations, and framework compatibility. Whether you are deploying a high-traffic Laravel API or maintaining a legacy WordPress site, understanding these architectural trade-offs prevents costly rewrites later. For teams still evaluating traditional infrastructure, my previous analysis on hosting Laravel on AWS EC2 provides a baseline for cost and performance comparison against the serverless models discussed here.

Serverless PHP Runtime Models 2026AWS Lambda (Bref)Event-Driven / FaaSCustom Runtime (PHP-FPM)Ephemeral /tmp StorageMax Timeout: 15 minBest: APIs, QueuesGoogle Cloud RunContainer-as-a-ServiceStandard Docker ImageFull Linux FilesystemMax Timeout: 60 minBest: Full-Stack AppsAzure FunctionsManaged App ServiceCustom Handler / V2Read-Only + /tmp WriteMax Timeout: 10 min (Flex)Best: Enterprise Integration
Comparison of runtime environments for Serverless PHP Options in 2026 Compared across major cloud providers.

How do AWS Lambda and Bref handle PHP execution?

AWS Lambda does not natively support PHP, which historically made it a non-starter for our stack. That changed with Custom Runtimes and the open-source project Bref. In 2026, Bref v2.x is the de facto standard, providing an optimized PHP-FPM binary compiled specifically for Amazon Linux 2023. When you deploy, your code runs inside a microVM that boots in milliseconds, but the architecture imposes strict constraints you must respect.

Cold Start Optimization Strategies

The most common complaint about serverless PHP is latency during cold starts. With PHP 8.4 and SnapStart enabled, initialization time for a typical Laravel app has dropped from ~800ms to under 200ms in most regions. However, this requires specific configuration:

  • Provisioned Concurrency: Essential for user-facing endpoints where P99 latency matters. Keep 2-5 instances warm during peak hours.
  • Dependency Reduction: Every megabyte of deployment package adds extraction time. Use bref/cli to strip dev dependencies before packaging.
  • OPcache Preloading: Configure opcache.preload in your php.ini to cache framework classes at startup, reducing first-request overhead by 30-40%.
# Example serverless.yml optimization for Laravel
provider:
    name: aws
    runtime: provided.al2023
    region: ap-south-1
    architecture: arm64

functions:
    web:
        handler: public/index.php
        layers:
            - ${bref:layer.php-84-fpm}
        environment:
            APP_ENV: production
            OPACHE_PRELOAD: /var/task/vendor/autoload.php
        snapStart: true

For teams handling sensitive data, remember that Lambda's ephemeral storage is encrypted at rest but shared across invocations within the same execution environment. Always clear sensitive variables after processing. If your compliance requirements demand stricter isolation, consider the container-based approach discussed next or review AWS IAM best practices to lock down function permissions.

When should you choose Google Cloud Run over Lambda?

Google Cloud Run occupies a middle ground between pure FaaS and managed Kubernetes. It accepts any OCI-compliant container, meaning you can run the exact same Docker image locally, in CI, and in production without runtime translation layers. This eliminates the "works on my machine" problems that plague Lambda deployments using custom runtimes.

Filesystem and Execution Freedom

Unlike Lambda's restrictive 512MB /tmp limit, Cloud Run allows mounting volumes and writing anywhere in the container filesystem (though only /tmp persists between requests on the same instance). More importantly, Cloud Run supports execution times up to 60 minutes for HTTP requests, making it viable for report generation, large file processing, and complex migrations that would timeout on Lambda.

The trade-off is billing granularity. While Lambda charges per millisecond, Cloud Run bills per vCPU-second and memory-second. For sporadic traffic, Cloud Run can be more expensive because idle instances still consume minimal resources unless configured to scale to zero. However, for sustained loads, the per-request cost often undercuts Lambda because you aren't paying for API Gateway markup.

# Dockerfile optimized for Cloud Run PHP
FROM php:8.4-apache-bookworm

RUN apt-get update && apt-get install -y libpng-dev libzip-dev \
    && docker-php-ext-install pdo_mysql gd zip opcache \
    && a2enmod rewrite

COPY . /var/www/html
RUN chown -R www-data:www-data /var/www/html/storage

# Cloud Run requires listening on PORT env var
ENV PORT=8080
EXPOSE 8080

CMD ["apache2-foreground"]

What are the practical limits of Azure Functions for PHP?

Azure Functions supports PHP through Custom Handlers, essentially running your PHP application as an HTTP server that communicates with the Azure Functions Host via localhost. This indirection adds overhead compared to native runtimes like Node.js or C#. In practice, expect 100-200ms additional latency per request purely from the host-proxy communication layer.

The Flex Consumption plan introduced in late 2024 improved cold start behavior significantly, but the ecosystem for PHP-specific tooling remains thin. Most community libraries target AWS or GCP. If your organization mandates Azure for contractual or compliance reasons, Functions works adequately for background processing and internal APIs. For customer-facing applications serving Nepali or South Asian users, however, the lack of a Mumbai region equivalent for Functions (compared to AWS/GCP) can add 40-80ms of network latency that impacts perceived performance.

Platform Selection Decision FlowWorkload Type?Event / Queue / CronHTTP / Web AppEnterprise / LegacyDuration < 15 min?Yes → AWS LambdaNo → Cloud Run JobsNeed Docker / Long Run?Yes → Cloud RunNo → Lambda + API GWMicrosoft Ecosystem?Yes → Azure FunctionsNo → Re-evaluate LeftCritical Constraint CheckLocal File Writes? → Cloud Run or EFS (Lambda)WebSocket Support? → Cloud Run Only
Decision matrix for evaluating Serverless PHP Options in 2026 Compared by workload type and technical constraints.

How do costs compare for realistic PHP traffic patterns?

Benchmarks from synthetic tests rarely reflect actual billing. Below is a comparison based on a mid-sized Laravel application serving 2 million requests monthly with average 150ms execution time and 512MB memory allocation. These figures assume optimal configuration for each platform.

CriteriaAWS Lambda (Bref)Google Cloud RunAzure Functions (Flex)
Compute Cost (2M req/mo)$45 - $65$55 - $80$60 - $90
API Gateway / Load Balancer$35 (REST API v2)$18 (Global LB)$0 (Included)
NAT Gateway (VPC Access)$45 + $0.045/hr$0 (Serverless VPC)$0 (VNET Integration)
Cold Start Mitigation Cost$15 (Provisioned)$10 (Min Instances)$0 (Flex Auto)
Total Estimated Monthly$140 - $160$83 - $108$60 - $90
Best For ScaleBursty, Event-HeavySustained HTTP TrafficLow Volume Internal

Note the NAT Gateway trap on AWS. If your Lambda needs VPC access for RDS or ElastiCache, you pay ~$32/month just for the gateway plus hourly charges. Cloud Run's Serverless VPC Access eliminates this entirely, often making it cheaper despite higher base compute rates. For Nepal-based startups budgeting in NPR, this difference translates to significant savings when scaling. Always model costs with your specific traffic shape rather than relying on generic calculators.

Which serverless PHP option handles databases and state correctly?

Statelessness is the defining constraint of serverless PHP. Your application cannot rely on local sessions, uploaded files persisting between requests, or persistent database connections. Handling this incorrectly causes intermittent failures that are notoriously difficult to debug in production.

Session and Storage Patterns

  1. Sessions: Never use file-based sessions. Configure Redis (ElastiCache/Memorystore) or DynamoDB as the session driver. For Laravel, set SESSION_DRIVER=redis and ensure connection pooling is enabled to avoid exhausting file descriptors during concurrent invocations.
  2. File Uploads: Stream directly to S3 or Google Cloud Storage using presigned URLs. Never store uploads in /tmp expecting them to survive beyond the current request. If you need temporary processing space, Cloud Run's writable filesystem is safer than Lambda's limited /tmp.
  3. Database Connections: Use RDS Proxy (AWS) or Cloud SQL Proxy (GCP) to pool connections. Without proxying, each Lambda invocation opens a new TCP connection, quickly hitting database limits. Configure PERSISTENT_CONNECTIONS=false in PHP-FPM to prevent stale connection errors.

Monitoring becomes critical when state is externalized. Traditional APM tools struggle with serverless lifecycles. Implement structured logging and distributed tracing early — see OpenTelemetry observability standards for vendor-neutral instrumentation that works across all three platforms. Without proper tracing, debugging a failed transaction spanning Lambda → SQS → RDS is nearly impossible.

Stateless PHP Architecture PatternServerless PHP Function(Stateless / Ephemeral)Sessions & CacheRedis / DynamoDBExternalized State StoreObject StorageS3 / GCS / Azure BlobPresigned URL UploadsDatabase LayerRDS Proxy / Cloud SQLConnection Pooling RequiredAnti-Pattern WarningNever use local filesystem, file sessions, or direct DB connections without pooling
Required external state dependencies for production-grade Serverless PHP Options in 2026 Compared.

Making the Final Platform Decision

Selecting among Serverless PHP Options in 2026 Compared ultimately depends on your team's operational maturity and workload characteristics. Choose AWS Lambda with Bref if you need tight integration with the AWS ecosystem, event-driven architectures, or have existing expertise in CloudFormation/Terraform. Opt for Google Cloud Run if you want Docker portability, longer execution times, or simpler networking without NAT costs. Reserve Azure Functions for organizations with existing Microsoft commitments where PHP is a secondary concern.

Regardless of platform, invest in infrastructure-as-code from day one. Manual console clicks create unreproducible environments that fail audits and break during disaster recovery. If you're planning a migration or need help architecting a compliant serverless setup, reach out to discuss your specific requirements. The right choice saves thousands annually; the wrong one creates technical debt that compounds quarterly.

Frequently Asked Questions

AWS Lambda with SnapStart currently delivers the fastest cold starts for PHP 8.4, typically under 200ms. Cloudflare Workers and Vercel remain faster but lack full native PHP runtime support, requiring WebAssembly compilation or edge-compatible frameworks like Laravel Octane.

Not directly. You must use adapters like Laravel Vapor or Bref to bridge framework expectations with ephemeral execution models. These tools handle routing, storage proxies, and queue drivers specifically designed for stateless serverless PHP environments in 2026.

Serverless is cheaper for sporadic traffic but expensive at scale. A VPS costs fixed monthly fees regardless of usage, while serverless bills per millisecond. High-traffic apps often exceed VPS pricing due to invocation charges and data transfer fees.

Yes, via custom runtimes using the provided.al2023 base image. Official managed runtimes lag behind, so most teams use Bref or container images to deploy current PHP versions with full extension support and security patches.

Workers use V8 isolates, not Zend Engine, so many PHP extensions fail. Only subset-compatible code runs via WebAssembly. Database connections require HTTP-based drivers, and filesystem operations are impossible without external object storage integration.

Use connection pooling services like AWS RDS Proxy or Supavisor to prevent exhausting database limits during concurrent invocations. Traditional persistent connections fail in serverless because each function instance creates new connections that persist beyond request scope.

Yes, Bref remains actively maintained with PHP 8.4 support and Terraform integration. It provides optimized layers, CLI tooling, and local development emulation. Most production serverless PHP deployments in 2026 rely on Bref or commercial alternatives like Laravel Vapor.

No, serverless functions have hard timeout limits, typically 15 minutes maximum. Offload background processing to dedicated queue services like SQS or Redis-backed workers. Use serverless only for HTTP requests and lightweight event triggers requiring sub-second responses.

Lambda uses proprietary APIs and event sources tightly coupled to AWS ecosystem. Cloud Run accepts standard OCI containers, making migration easier. Both require adapter layers for PHP, but Cloud Run preserves more portability across cloud providers.

Minimize IAM permissions per function, never embed secrets in code, and use parameter stores. Audit third-party Composer dependencies regularly since supply chain attacks target serverless packages. Enable runtime monitoring to detect anomalous behavior in ephemeral executions.

Use Bref Local or SAM CLI to emulate Lambda environments with PHP 8.4. These tools replicate API Gateway events, environment variables, and layer configurations. Remote debugging requires Xdebug over SSH tunnels or structured logging with correlation IDs.

Poorly. WordPress assumes persistent filesystem and database connections incompatible with serverless. Specialized platforms like WP Cloud exist but add complexity. Traditional hosting remains superior for WordPress unless you accept significant architectural compromises and higher operational overhead.

Datadog, Lumigo, and AWS X-Ray provide end-to-end tracing for PHP Lambda functions. Configure OpenTelemetry SDKs for vendor-neutral observability. Standard APM agents often fail in serverless; use purpose-built integrations that understand ephemeral execution contexts and cold starts.

Install dependencies targeting the Lambda Linux environment using Docker or Bref CLI. Exclude dev dependencies to reduce package size. Use Lambda layers to share common libraries across functions and avoid hitting deployment artifact size limits repeatedly.

Yes, Scaleway Functions and OVHcloud offer EU-hosted serverless PHP runtimes with GDPR compliance. Both support custom containers and PHP 8.4. Performance lags behind AWS but satisfies strict data sovereignty requirements without cross-border transfer complications.