Laravel Octane: Supercharging Application Performance
What is Octane?
Laravel Octane supercharges your application's performance by serving it using high-powered application servers like Swoole or RoadRunner. Instead of booting your application for every request, Octane boots it once and keeps it in memory, handling subsequent requests with minimal overhead.
The Performance Gains
In benchmarks, Octane can improve throughput by 10-20x compared to traditional PHP-FPM setups. Real-world improvements vary based on your application, but even modest gains can be significant at scale.
Installation
composer require laravel/octane
# For Swoole
pecl install swoole
php artisan octane:install --server=swoole
# For RoadRunner
php artisan octane:install --server=roadrunner
Understanding the Caveats
Octane keeps your application in memory between requests. This creates potential for memory leaks and state bleeding between requests:
// DANGER: Static state persists between requests
class RequestCounter
{
private static int $count = 0;
public static function increment(): void
{
self::$count++; // This accumulates across requests!
}
}
// SAFE: Use the container for request-scoped state
class RequestCounter
{
public function __construct(
private Request $request
) {}
}
Configuration
// config/octane.php
return [
'server' => env('OCTANE_SERVER', 'swoole'),
'workers' => env('OCTANE_WORKERS', cpu_count()),
'max_requests' => env('OCTANE_MAX_REQUESTS', 1000),
'listeners' => [
RequestReceived::class => [
// Reset state between requests
],
],
];
Flushing State
// In a listener
class FlushApplicationState
{
public function handle($event): void
{
// Clear any request-specific caches
app('cache')->forget('current_request_data');
// Reset singletons that hold request state
app()->forgetInstance(RequestContext::class);
}
}
Concurrent Tasks
Octane enables true concurrency:
use Laravel\Octane\Facades\Octane;
$results = Octane::concurrently([
'users' => fn () => User::count(),
'orders' => fn () => Order::sum('total'),
'products' => fn () => Product::where('active', true)->count(),
]);
// All three queries run simultaneously
Production Deployment
# Using Supervisor
[program:octane]
command=php /var/www/app/artisan octane:start --server=swoole --port=8000
autostart=true
autorestart=true
stdout_logfile=/var/www/app/storage/logs/octane.log
stderr_logfile=/var/www/app/storage/logs/octane-error.log
When to Use Octane
Octane is ideal for high-traffic applications where the performance gains justify the added complexity. For smaller applications, traditional PHP-FPM might be simpler to operate.
Conclusion
Octane can dramatically improve performance, but requires understanding its memory model. Profile your application, watch for memory leaks, and enjoy the speed boost.
Related Articles
Need Help With Your Project?
I respond to all inquiries within 24 hours. Let's discuss how I can help build your production-ready system.
Get In Touch