Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 62 ยท Caching, Performance and Testing

Performance and Deployment

Prepare a Symfony app for production with APP_ENV=prod, cache warmup, dump-env, OPcache, preloading, FrankenPHP workers and a simple CI/CD pipeline.

A Symfony application that feels fast in production is mostly one that does less work per request. In development the framework rebuilds caches, checks file timestamps and collects debug data so that you get helpful errors. In production all of that is done once, ahead of time, and every request starts from ready-made files.

This lesson covers the production switch (APP_ENV=prod), warming the cache, turning .env files into a PHP file, tuning OPcache and preloading, running Symfony in a long-lived worker with FrankenPHP, and a deployment pipeline you can copy. Deployment is about servers, so the real commands are read-only. Two runnable stand-ins show why the tricks work: a "compiled" container that avoids reflection, and a dump-env file that avoids parsing.

What changes in production

Setting APP_ENV=prod and APP_DEBUG=0 switches the kernel to its production behavior:

  • The service container is compiled once into plain PHP classes under var/cache/prod. It is never rebuilt unless you clear the cache.
  • Config files (YAML, XML) are not read at request time, only their compiled result.
  • The web debug toolbar and profiler are off, and exceptions render your own error pages, never a stack trace.
  • Logging goes to a handler suited to production (often php://stderr as JSON) instead of a dev file.
Terminal
# .env.local on the server, or real environment variables
APP_ENV=prod
APP_DEBUG=0

Never deploy with APP_ENV=dev. Besides being slow, it can expose source code, configuration and secrets through error pages and the profiler. Also keep /_profiler and /_wdt unreachable: they only exist when the dev routes are loaded.

The deploy checklist

A typical deployment script runs the same few commands every time, in this order:

Terminal
composer install --no-dev --optimize-autoloader --classmap-authoritative
php bin/console cache:clear --env=prod --no-debug
php bin/console cache:warmup --env=prod --no-debug
php bin/console doctrine:migrations:migrate --no-interaction --env=prod
php bin/console asset-map:compile      # only with AssetMapper

What each step buys you:

Step Why it matters
--no-dev Dev packages (profiler, maker, test tools) never reach the server.
--optimize-autoloader Composer builds a class map, so autoloading is an array lookup instead of file-system probing.
--classmap-authoritative Composer trusts the class map completely and never touches the disk for a class that is not listed.
cache:warmup Builds the compiled container, routes, Twig templates and Doctrine metadata before the first visitor arrives.
migrations Brings the schema in line with the code that is about to run (see Migrations).

Skipping the warmup is a classic mistake: the first request after a deploy then pays for everything, and under load many requests pay at the same time.

flowchart LR
    A["git push"] --> B["CI: tests, lint,<br/>static analysis"]
    B --> C["Build: composer install --no-dev,<br/>assets compile, cache:warmup"]
    C --> D["Release artifact<br/>or Docker image"]
    D --> E["Migrate database"]
    E --> F["Switch traffic<br/>to the new release"]

Do the expensive work in the build step, so that switching a release is fast and can be rolled back.

Environment variables: dump-env

Symfony reads .env, .env.local and .env.prod with a small parser on every request. That is fine in development, but in production you have two better options:

  1. Set real environment variables in the server, container or systemd unit. Nothing is parsed, and secrets stay out of the repository.
  2. Run composer dump-env prod, which merges the .env files into one PHP file, .env.local.php. Symfony loads it with a single include.
Terminal
composer dump-env prod
# creates .env.local.php (do not commit it)

The file is just a returned array, so reading it costs about as much as reading any config array. The stand-in below makes the saving visible by counting how many lines the parser has to look at on each request.

PHP dump-env stand-in: parse once, include forever

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real .env.local.php is an ordinary PHP file, and OPcache keeps it in memory after the first load, so the later requests are even cheaper than in our stand-in. Note that dump-env freezes the values: if you change a variable you must dump again (or use real environment variables, which do not have this problem). Variable handling in general is covered in Environment Variables and Secrets.

OPcache: the biggest single win

PHP normally compiles every script to opcodes on every request. OPcache stores those opcodes in shared memory, so a hot file is never parsed again. For a framework with thousands of classes, this alone can multiply throughput. A production php.ini for Symfony looks like this:

INI
; php.ini (production)
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=30000
opcache.validate_timestamps=0   ; never stat() files; reload on deploy
realpath_cache_size=4096K
realpath_cache_ttl=600

validate_timestamps=0 is the important line. PHP no longer checks whether a file changed, which is faster, but it means a new release is invisible until you reset OPcache: restart PHP-FPM (systemctl reload php8.4-fpm) or call opcache_reset() from a deploy script that runs inside the web SAPI. Forgetting this makes a deploy appear to do nothing, or worse, run a mix of old and new files.

Preloading

PHP can also preload a list of classes at server start, making them permanently available without autoloading. Symfony generates a preload file for you in the production cache:

INI
opcache.preload=/var/www/app/var/cache/prod/App_KernelProdContainer.preload.php
opcache.preload_user=www-data

Preloading helps the most when the preloaded set is exactly the code every request uses (the compiled container and core components). It has costs: the preload runs at server start, changing any preloaded file needs a full restart, and a wrong list can make things slower or break. Measure before and after. For most applications, OPcache with a classmap-authoritative autoloader gets you most of the benefit at no risk.

Why a compiled container is fast

The compiled container is the second big reason production is fast. The stand-in below builds an object graph two ways: by inspecting constructors with Reflection on every request (what a naive runtime container would do), and by running code that was generated once with the new calls already written out. Counting reflection calls shows the difference without needing a clock.

PHP Reflection per request vs a compiled container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real compiled container is written to var/cache/prod/ and is far more elaborate (lazy services, tagged iterators, parameters), but the idea is the same: figure everything out at build time, then run straight-line PHP.

Long-lived workers with FrankenPHP

PHP-FPM boots the framework on every request and throws it away at the end. Worker mode boots Symfony once and keeps the kernel in memory, handling many requests in a loop. FrankenPHP (a PHP application server built on Caddy) supports this, and the Symfony Runtime component lets the same public/index.php run either way.

Terminal
composer require runtime/frankenphp-symfony
DOCKERFILE
# Dockerfile (excerpt)
FROM dunglas/frankenphp
ENV APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime
ENV FRANKENPHP_CONFIG="worker ./public/index.php"
COPY . /app

Worker mode removes boot time from every request, often giving a large speedup. It also changes the rules, because state now survives between requests:

  • Services must not keep per-request data in properties. Symfony resets services that implement ResetInterface (tagged kernel.reset) between requests, but your own code must follow the same discipline.
  • Static properties and global variables leak from one request to the next.
  • Memory leaks become real problems; workers are usually restarted after a number of requests.
  • Database connections must handle being idle for a long time.

If you do not need the extra speed, PHP-FPM with OPcache is simpler and perfectly adequate for a large share of sites. Measure first.

Containers and CI/CD

A Docker image is the cleanest release artifact: the build stage installs dependencies and warms the cache, and the runtime stage only contains what runs.

DOCKERFILE
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock symfony.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist

FROM php:8.4-fpm AS app
WORKDIR /app
COPY --from=vendor /app/vendor ./vendor
COPY . .
ENV APP_ENV=prod APP_DEBUG=0
RUN composer dump-autoload --optimize --classmap-authoritative \
 && php bin/console cache:warmup

A CI pipeline (GitHub Actions, GitLab CI, anything) then runs checks before the build. These commands are worth gating on:

Terminal
composer validate --strict
php bin/console lint:yaml config
php bin/console lint:twig templates
php bin/console lint:container
vendor/bin/phpunit

lint:container is a particularly cheap safety net: it compiles the container and catches wiring mistakes that would otherwise appear only in production. See Testing with PHPUnit for the test side.

Other things that matter

  • Sessions and cache need a shared store (Redis, database) once you run more than one server, otherwise users lose their session when the load balancer switches machines.
  • Logs should go to stderr or a log service, not to files that fill the disk.
  • Static assets should be served by the web server or a CDN with long cache lifetimes; AssetMapper adds content hashes to file names so that is safe (see Assets, AssetMapper and Webpack Encore).
  • Profiling in production is best done with a tool such as Blackfire or an APM agent, not with the dev profiler.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command prepares the compiled container, routes and templates before the first visitor?

    cache:warmup builds the production cache ahead of time so the first requests do not pay for it. dump-env only handles environment variables.
  2. 2. You set opcache.validate_timestamps=0 and deploy new files, but the site still serves old code. What is the most likely cause?

    With timestamp validation off, PHP never checks for changes. You must reload PHP-FPM or reset OPcache as part of every deploy.
  3. 3. What is the main hazard of running Symfony in a FrankenPHP worker?

    The kernel stays in memory, so any per-request data stored in properties or statics leaks into the next request unless it is reset.
  4. 4. Why should you never deploy with APP_ENV=dev?

    Dev mode rebuilds caches, collects profiler data and shows detailed error pages that reveal internals.

Summary

  • Production means APP_ENV=prod, APP_DEBUG=0, no dev dependencies and a warmed, compiled cache.
  • Use composer install --no-dev --optimize-autoloader --classmap-authoritative, then cache:warmup and migrations in the build and release steps.
  • Real environment variables or composer dump-env prod avoid parsing .env files on each request.
  • OPcache is the largest win; with validate_timestamps=0 you must reset it on deploy. Preloading is an optional, measurable extra.
  • Worker mode (FrankenPHP) removes boot time but requires stateless services.
  • Run lint commands and tests in CI and ship one immutable artifact.

Now put the pieces together in a first complete application: Project: A Blog.