1. Harden the Configuration
The first line of defence is a clean, immutable configuration. Keep .env files out of version control and use a secrets manager (AWS Parameter Store, Vault, etc.) for production values. In config/app.php turn off debugging and enable HTTPS detection:
return [
'debug' => env('APP_DEBUG', false),
'url' => env('APP_URL'),
'asset_url' => env('ASSET_URL'),
'force_https' => true,
];
Set APP_DEBUG=false and APP_ENV=production. Never rely on the default APP_KEY generation; rotate keys regularly and store them securely.
2. Optimize Autoloading and Config Caching
Laravel provides two one‑click commands that shave milliseconds off every request:
php artisan config:cache # merges all config files into a single cached file
php artisan route:cache # caches route definitions (only for routes that don’t use closures)
php artisan view:cache # pre‑compiles Blade templates
Run these as part of every deployment pipeline. Remember that route:cache will fail if any route uses a closure, so refactor those into controller methods first.
3. Leverage Caching Strategically
A layered cache strategy prevents the database from becoming a bottleneck.
- Configuration & routes – already cached as above.
- Query results – use
Cache::remember()for expensive read‑only queries. - Full‑page cache – for pages that rarely change (e.g., marketing pages) wrap the response in a middleware that stores the rendered HTML in Redis or Memcached.
$posts = Cache::remember('latest_posts', now()->addMinutes(10), function () {
return Post::orderByDesc('created_at')->take(10)->get();
});
When you introduce a cache layer, always add an invalidation path. For the example above, fire an event after a new post is saved and clear the key.
4. Queue Long‑Running Work
Never let a user‑facing request wait for email delivery, PDF generation, or third‑party API calls. Move those tasks to Laravel’s queue system.
php artisan queue:work --daemon --tries=3 --timeout=60
Choose a driver that matches your scale: Redis for low‑latency needs, SQS or RabbitMQ for distributed workloads. Configure retry_after slightly higher than the longest expected job duration to avoid duplicate processing.
Queue Monitoring
Use Laravel Horizon (Redis only) or a simple health‑check endpoint that reports queue:work process counts. A missing worker should trigger an alert and auto‑restart via a process manager like Supervisor.
5. Centralised Logging & Error Reporting
Production logs should be shipped to a log aggregation service (Papertrail, Loggly, Elastic Stack). In config/logging.php set the default channel to stack with daily and a remote driver:
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily', 'papertrail'],
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
'papertrail' => [
'driver' => 'monolog',
'handler' => Monolog\Handler\SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_HOST'),
'port' => env('PAPERTRAIL_PORT'),
],
],
],
For uncaught exceptions, integrate Sentry or Bugsnag. They provide stack traces, request context, and release tracking, which is indispensable when debugging production incidents.
6. Secure the Application Surface
Security is non‑negotiable. Follow these concrete steps:
- HTTPS Everywhere – enforce
Illuminate\Http\Middleware\RedirectSecureor setAppServiceProvider::boot()to force HTTPS on production. - Content Security Policy – add the
spatie/laravel-csppackage and define a strict policy to mitigate XSS. - Rate Limiting – use Laravel’s built‑in throttling on authentication routes and any public API endpoints.
- Validate All Input – never rely on client‑side validation; always validate in Form Requests.
- Sanitize Uploaded Files – store uploads outside the web root, generate random filenames, and scan with ClamAV or a similar service.
7. Database Health Checks
A mis‑configured connection pool can cause cascading timeouts. In config/database.php set sensible options:
'options' => extension_loaded('pdo_mysql') ? [
PDO::ATTR_TIMEOUT => 5,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode='STRICT_ALL_TABLES'",
] : [],
Run periodic php artisan schedule:run jobs that execute a lightweight query (SELECT 1) against each replica. If a replica fails, failover to the primary or raise an alert.
8. Automated Deployments with Health Checks
Even a perfect codebase can break during deployment. Couple your CI pipeline with a post‑deploy health check that verifies:
- HTTP 200 on the home page.
- Critical background workers are alive.
- Cache warm‑up (e.g., seed the
latest_postscache key).
If any check fails, automatically roll back the release. Tools like Laravel Envoy, GitHub Actions, or Bitbucket Pipelines can orchestrate these steps.
9. Observability: Metrics & Alerts
Collect key performance indicators (KPIs) with Prometheus exporters or Laravel Telescope in a read‑only mode. Focus on:
- Request latency (p95, p99).
- Queue job duration and failures.
- Database query time distribution.
- Cache hit/miss ratios.
Set alert thresholds that reflect user impact (e.g., latency > 500 ms for more than 5 % of requests). Integrate alerts with Slack or PagerDuty so the on‑call engineer can act immediately.
10. Document the Runbook
All the technical safeguards mean little without a clear runbook. Keep a version‑controlled Markdown file that outlines:
- How to spin up a fresh environment.
- Steps to rotate secrets.
- Emergency rollback procedure.
- Contact points for infra, security, and dev teams.
Regularly rehearse the runbook during post‑mortems; it turns a chaotic outage into a predictable recovery.
By applying this checklist early—ideally during the first sprint—you avoid the most common production pitfalls that cost startups time and money. The effort is incremental: start with configuration and caching, then layer queues, logging, and security. Each addition brings measurable stability, and the cumulative effect is a Laravel application that scales with confidence.
- Laravel
- Security
- Devops
- Performance
- Production