Skip to content

PHP in Production: What Mid and Senior Engineers Must Know

The core concepts behind running PHP in production, from PHP-FPM sizing and OPcache to sessions, workers, databases, timeouts and caching.

15 min read8 conceptsTechnical testsPHP in production

Interviewers who ask about PHP in production are not checking whether you know the syntax. They want to know whether you understand what happens when real traffic hits your code. That means how PHP-FPM hands out workers, why a deploy can leave old code running, why a dashboard freezes when one request holds the session, and why a queue worker slowly eats memory until the kernel kills it. This guide covers the concepts behind strong answers. Each one comes with a small invented scenario, a runnable PHP snippet and the traps that catch people out. Learn the reasoning, not the phrasing. Situational questions are built to punish memorised answers.

Study order

If time is short, go in this order.

  1. PHP-FPM and the shared-nothing request model

    Almost every production question about capacity, 502s or latency comes back to how FPM workers are counted and sized.

  2. Timeouts and outbound calls

    Misaligned timeouts and slow dependencies are the most common way a healthy PHP app gets taken down, and interviewers probe the max_execution_time trap.

  3. OPcache, preloading and safe deploys

    Explains the stale-code-after-deploy class of incidents and shows you understand how PHP actually runs your code.

  4. PDO, transactions and deadlock retries

    Data correctness under concurrency separates senior answers from mid-level ones.

  5. Error handling, fatal errors and structured logs

    You cannot debug production without clean error handling, fatal-error capture and structured logs.

  6. Sessions, locking and horizontal scaling

    Session locking is a subtle, PHP-specific latency cause, and it ties into horizontal scaling.

  7. Long-running CLI workers and memory

    Queue workers break the shared-nothing model, so memory and signal handling come up whenever async processing is discussed.

  8. Caching with APCu and Redis, and avoiding stampedes

    Caching questions test whether you think about failure modes, not just hit rates.

PHP-FPM and the shared-nothing request model

PHP-FPM runs a pool of worker processes. Each worker handles one request at a time, and PHP tears down all request state when the request ends: globals, objects and open handles. This shared-nothing model is why a bug in one request rarely corrupts another. It also means your concurrency ceiling is the number of workers, not the number of CPU cores.

The key setting is pm.max_children. Size it from memory, not guesswork. Measure the average resident memory of a worker under real load, subtract what the container needs for everything else, then divide. If you set it too high, the box swaps or the OOM killer steps in. If you set it too low, requests queue up in the listen backlog and nginx eventually returns 502 or 504.

pm = dynamic suits most web pools, pm = static suits dedicated boxes with predictable load, and pm = ondemand suits low-traffic pools where idle memory matters. Set pm.max_requests so workers recycle periodically. That caps damage from slow leaks in extensions or in your own code.

PHP

<?php
// Sizing the FPM pool for the Larkspur checkout service.
// Measured under load: 4 GB container, ~60 MB per worker,
// 800 MB reserved for nginx, the OPcache shared segment and headroom.
$containerMb = 4096;
$reservedMb = 800;
$avgWorkerMb = 60;

$maxChildren = intdiv($containerMb - $reservedMb, $avgWorkerMb);

printf("pm.max_children = %d\n", $maxChildren); // 54

Derive max_children from measured worker memory, then confirm it with a load test.

Traps

  • Sizing workers by CPU count. PHP requests spend much of their time waiting on I/O, so the real limit is usually memory.
  • Counting OPcache memory per worker. It lives in shared memory and is paid once, so including it per worker overstates RSS.
  • Forgetting that memory_limit is a per-request cap, not the worker's real footprint. A 256M limit does not mean each worker uses 256 MB.
  • Leaving the FPM status page disabled. Without pm.status_path you cannot see active workers, idle workers or the listen queue during an incident.

OPcache, preloading and safe deploys

OPcache stores compiled opcodes in shared memory, so PHP skips parsing and compiling on every request. In production you normally set opcache.validate_timestamps=0 so PHP never checks files for changes. The consequence is that new code is only picked up after you reload FPM or reset the cache from inside the FPM pool. Interviewers love this one: "we deployed, but the old code is still running."

Size the cache so it never fills. Watch opcache.memory_consumption, opcache.interned_strings_buffer and opcache.max_accelerated_files. A full cache either stops caching new scripts or triggers restarts, and both show up as latency spikes. Preloading (opcache.preload) loads framework classes once at FPM start. That can shave time off each request, but any change to preloaded files requires a full FPM restart.

Deploy an immutable artifact. Build with composer install --no-dev --optimize-autoloader (add --classmap-authoritative if you never generate classes at runtime), and never run composer update on a server. Then either switch a symlink and reload FPM, or ship a new container image. Release a symlinked deploy only after the realpath cache and OPcache are refreshed.

PHP

<?php
// health/opcache.php, served through FPM (not the CLI) for the Ferngate API.
$status = function_exists('opcache_get_status') ? opcache_get_status(false) : false;

if ($status === false) {
    http_response_code(503);
    echo "OPcache disabled\n";
    exit;
}

$mem = $status['memory_usage'];
$stats = $status['opcache_statistics'];

printf(
    "used %.1f MB, free %.1f MB, cached scripts %d, hit rate %.2f%%\n",
    $mem['used_memory'] / 1048576,
    $mem['free_memory'] / 1048576,
    $stats['num_cached_scripts'],
    $stats['opcache_hit_rate']
);

Expose OPcache stats through the web SAPI so you can see the cache the workers actually use.

Traps

  • Running opcache_reset() or checking status from the CLI. The CLI has its own cache (and opcache.enable_cli is off by default), so you reset nothing that FPM uses.
  • Switching a symlink without reloading FPM while validate_timestamps=0. Workers keep serving the previous release, sometimes mixing old and new files.
  • Leaving max_accelerated_files below the real file count of a large Composer vendor tree, which silently stops caching new scripts.
  • Shipping dev dependencies or a non-optimised autoloader, which costs filesystem lookups on every class load.

Error handling, fatal errors and structured logs

Production PHP must never show errors to users. Set display_errors=Off and log_errors=On, and keep error_reporting=E_ALL so nothing is hidden from the logs. In containers, send logs to stderr so the platform collects them. Turn on catch_workers_output in the FPM pool if workers write there directly.

PHP still has two error worlds: exceptions and legacy warnings or notices. A common production pattern converts warnings into ErrorException with set_error_handler, so a failed file_get_contents cannot slip through as a warning followed by a broken false value. Use a top-level exception handler to log the full context and return a clean 500.

True fatal errors, such as running out of memory or hitting the execution time limit, bypass exception handlers. Catch them in a shutdown function with error_get_last(). Log in a structured form (JSON with request id, route and user id) so you can correlate a spike in errors with one endpoint or one deploy.

PHP

<?php
declare(strict_types=1);

$requestId = bin2hex(random_bytes(8));

set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
    if (!(error_reporting() & $severity)) {
        return false; // respect the @ operator and the configured level
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
});

set_exception_handler(function (Throwable $e) use ($requestId): void {
    error_log(json_encode([
        'level' => 'error',
        'request_id' => $requestId,
        'type' => get_class($e),
        'message' => $e->getMessage(),
        'at' => $e->getFile() . ':' . $e->getLine(),
    ]));
    if (PHP_SAPI !== 'cli' && !headers_sent()) {
        http_response_code(500);
    }
    echo "Something went wrong. Reference: {$requestId}\n";
});

register_shutdown_function(function () use ($requestId): void {
    $err = error_get_last();
    if ($err !== null && in_array($err['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE], true)) {
        error_log(json_encode(['level' => 'fatal', 'request_id' => $requestId] + $err));
    }
});

// Example: a missing file now throws instead of returning false with a warning.
$config = file_get_contents('/etc/pinecrest/missing.json');

Warnings become exceptions, uncaught exceptions get a reference id, and fatals are still logged.

Traps

  • Leaving display_errors=On in production. It leaks file paths, SQL and sometimes credentials.
  • Catching Exception instead of Throwable, which misses Error subclasses like TypeError.
  • Assuming set_exception_handler sees memory-limit or timeout fatals. Only a shutdown function can log those.
  • Swallowing exceptions with an empty catch block to make a page load. The bug moves somewhere harder to trace.

Sessions, locking and horizontal scaling

The default file session handler takes an exclusive lock on the session file from session_start() until the script ends or calls session_write_close(). Two requests from the same user therefore run one after another. On a dashboard that fires six parallel AJAX calls, each taking 400 ms, the user waits about 2.4 seconds instead of 400 ms.

The fix is to hold the lock only as long as you need it. Read what you need and close the session early, or open it with read_and_close when the request never writes. Write to the session only in the requests that actually change it, such as login, logout or cart updates.

Once you run more than one app server, file sessions on local disk break: a user logged in on server A looks anonymous on server B. Move sessions to a shared store like Redis or Memcached, or go stateless with signed tokens. Sticky sessions hide the problem but make deploys and failover worse. Also harden cookies: session.cookie_secure, session.cookie_httponly, session.cookie_samesite, session.use_strict_mode, and call session_regenerate_id(true) on login.

PHP

<?php
// Tallyhub dashboard widget: reads the session, never writes it.
session_start(['read_and_close' => true]);

$userId = $_SESSION['user_id'] ?? null;
if ($userId === null) {
    http_response_code(401);
    exit;
}

// The session lock is already released, so sibling widget requests run in parallel.
usleep(400_000); // stands in for a 400 ms report query

header('Content-Type: application/json');
echo json_encode(['user' => $userId, 'widget' => 'revenue', 'value' => 18250]);

Releasing the session lock early lets parallel requests from the same user run concurrently.

Traps

  • Blaming the database for a slow dashboard when the real cause is requests queuing on the session lock.
  • Writing to $_SESSION after session_write_close(). The change silently never persists.
  • Storing large objects in the session, which are serialised and unserialised on every request.
  • Forgetting that some Redis session handlers lock and others do not. Check the handler settings rather than assuming either behaviour.

Long-running CLI workers and memory

Queue consumers and daemons break the shared-nothing assumption. The process lives for hours, so anything that accumulates, such as static caches, ORM identity maps, query loggers or event listeners, grows without bound. PHP's reference counting frees most memory right away, but circular references wait for the cycle collector, and some extensions leak.

The robust pattern is to let workers die on purpose. Stop after N jobs or above a memory threshold, and let the supervisor (systemd, Supervisor or Kubernetes) start a fresh process. Handle SIGTERM so a deploy or scale-down finishes the current job instead of killing it halfway. Async signals via pcntl_async_signals(true) keep the handler responsive without manual pcntl_signal_dispatch() calls.

Inside the job, stream instead of loading everything. Generators let you process a 2 million row export with constant memory. Database connections can time out between jobs on a quiet queue, so reconnect or ping before use.

PHP

<?php
declare(strict_types=1);

// Simplified Orbitline invoice worker. A real one pulls from Redis, SQS or similar.
$queue = new SplQueue();
foreach (range(1, 1200) as $id) {
    $queue->enqueue(['invoice_id' => $id]);
}

pcntl_async_signals(true);
$shouldStop = false;
pcntl_signal(SIGTERM, function () use (&$shouldStop): void {
    $shouldStop = true; // finish the current job, then exit
});

$maxJobs = 500;
$maxMemory = 128 * 1024 * 1024;
$processed = 0;

while (!$shouldStop && $processed < $maxJobs && !$queue->isEmpty()) {
    $job = $queue->dequeue();
    // processInvoice($job) would go here.
    $processed++;

    if (memory_get_usage(true) > $maxMemory) {
        fwrite(STDERR, "memory threshold reached, exiting for restart\n");
        break;
    }
}

fwrite(STDERR, sprintf("processed %d jobs, exiting cleanly\n", $processed));
exit(0);

Bounded workers exit after a job budget, a memory threshold or SIGTERM, and the supervisor restarts them.

Traps

  • Running a worker with memory_limit=-1 and no job cap. The leak turns into a kernel OOM kill mid-job.
  • Ignoring SIGTERM, so every deploy interrupts jobs and leaves half-written state.
  • Holding one database connection for days without handling server-side idle timeouts such as MySQL's wait_timeout.
  • Using fetchAll() on huge result sets instead of iterating or yielding rows.

PDO, transactions and deadlock retries

Use prepared statements for every value that comes from outside. Since PHP 8.0, PDO's default error mode is ERRMODE_EXCEPTION, but set it explicitly so the intent is clear. With MySQL, disable emulated prepares if you want real server-side prepares and native types. Be aware that native prepares do not allow the same named parameter to appear twice.

Keep transactions short and never call an external HTTP API while one is open. Each open transaction holds locks, and a slow remote call turns into lock waits across the whole table. Always roll back on any throwable, not just PDOException. Otherwise a domain error leaves the connection inside an open transaction.

Under concurrency, deadlocks and serialization failures are normal, not bugs. The database aborts one transaction with SQLSTATE 40001 (and MySQL error 1213). Retry the whole transaction a small number of times with backoff. Persistent connections (PDO::ATTR_PERSISTENT) save connect time but can leak session state between requests and multiply connections by the number of FPM workers. A pooler like ProxySQL or PgBouncer is often the better tool.

PHP

<?php
declare(strict_types=1);

function transferCredits(PDO $pdo, int $fromId, int $toId, int $amount, int $maxAttempts = 3): void
{
    for ($attempt = 1; ; $attempt++) {
        try {
            $pdo->beginTransaction();

            $debit = $pdo->prepare('UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?');
            $debit->execute([$amount, $fromId, $amount]);
            if ($debit->rowCount() !== 1) {
                throw new DomainException('Insufficient balance');
            }

            $credit = $pdo->prepare('UPDATE wallets SET balance = balance + ? WHERE id = ?');
            $credit->execute([$amount, $toId]);

            $pdo->commit();
            return;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $retryable = $e instanceof PDOException && $e->getCode() === '40001';
            if (!$retryable || $attempt >= $maxAttempts) {
                throw $e;
            }
            usleep(50_000 * $attempt); // 50 ms, then 100 ms
        }
    }
}

$pdo = new PDO('mysql:host=127.0.0.1;dbname=quillpay;charset=utf8mb4', 'app', getenv('DB_PASSWORD') ?: '', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

transferCredits($pdo, 41, 97, 250);

Roll back on any failure and retry only on a serialization or deadlock error, with a bounded attempt count.

Traps

  • Retrying only the failed statement instead of the whole transaction. After a deadlock the database has already rolled the transaction back.
  • Building SQL with string concatenation for identifiers or ORDER BY clauses taken from input. Prepared parameters cannot bind identifiers, so you need an allowlist.
  • Using charset=utf8 with MySQL instead of utf8mb4, which breaks on emoji and some CJK characters.
  • Enabling persistent connections without counting them. 20 servers with 50 workers each can hold 1,000 database connections.

Timeouts and outbound calls

PHP has several timeouts, and they measure different things. On Linux, max_execution_time counts only script execution time. Time spent in system calls, sleeping, streams and database queries does not count, so a request stuck on a slow socket can run far past it. FPM's request_terminate_timeout is wall-clock and kills the worker outright. Nginx's fastcgi_read_timeout decides when the client gets a 504. Line these up from the inside out: the HTTP client timeout is shortest, then FPM, then nginx.

Every outbound call needs explicit connect and total timeouts. default_socket_timeout defaults to 60 seconds and does not apply to cURL. Suppose a shipping-rate API normally answers in 120 ms. Without a timeout, a slow spell there holds every FPM worker, and your whole site goes down even though your own code is fine.

Pair timeouts with a fallback, such as cached rates or a default option, and with bounded retries only for idempotent requests. For work the user does not need to wait for, push it to a queue. Use fastcgi_finish_request() only for small cleanups, because the worker stays busy until the code after it finishes.

PHP

<?php
declare(strict_types=1);

function fetchShippingQuote(string $url, array $payload): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT_MS => 300,
        CURLOPT_TIMEOUT_MS => 1500,
    ]);

    $body = curl_exec($ch);
    if ($body === false) {
        throw new RuntimeException(sprintf('Quote request failed (%d): %s', curl_errno($ch), curl_error($ch)));
    }

    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    if ($status !== 200) {
        throw new RuntimeException("Quote service returned HTTP {$status}");
    }

    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

try {
    $quote = fetchShippingQuote('https://rates.boxwren.example/v1/quote', ['weight_g' => 1800, 'zip' => '30301']);
} catch (RuntimeException | JsonException $e) {
    error_log($e->getMessage());
    $quote = ['carrier' => 'standard', 'price_cents' => 799]; // fallback rate
}

printf("%s: %d cents\n", $quote['carrier'], $quote['price_cents']);

Explicit connect and total timeouts plus a fallback keep one slow dependency from exhausting the FPM pool.

Traps

  • Believing max_execution_time=30 caps the wall-clock time of a request on Linux. It does not count time spent waiting on I/O.
  • Setting nginx's read timeout shorter than FPM's. The client gets a 504 while the worker keeps running and may still commit side effects.
  • Retrying non-idempotent POSTs on timeout, which can charge a card or create an order twice.
  • Relying on default_socket_timeout for cURL or SDK clients that ignore it.

Caching with APCu and Redis, and avoiding stampedes

APCu is an in-memory cache shared by the FPM workers of one pool on one machine. It is very fast, but it is not shared across servers, it is lost on FPM restart, and it is separate from the CLI. Use it for small, read-heavy data that can tolerate brief inconsistency between servers. Feature flags and config lookups are typical. Use Redis or Memcached when every server must see the same value or when you need explicit invalidation.

The classic production failure is a cache stampede. A popular key expires, and hundreds of concurrent requests all miss and all run the expensive query at once. Common defences are a short lock so only one request rebuilds while others serve stale data or wait briefly, jittered TTLs so keys do not expire together, and early background refresh for very hot keys.

Decide up front what happens when the cache itself is down. A cache should make the app faster, not become a hard dependency that takes the site down. Wrap cache calls so a Redis outage degrades to slower direct reads.

PHP

<?php
declare(strict_types=1);

// Bramblehouse catalogue: cache the top-sellers list with a rebuild lock.
function topSellers(Redis $redis, callable $loadFromDb): array
{
    $key = 'catalog:top_sellers:v3';
    $cached = $redis->get($key);
    if ($cached !== false) {
        return json_decode($cached, true, 512, JSON_THROW_ON_ERROR);
    }

    $lockKey = $key . ':lock';
    $gotLock = $redis->set($lockKey, '1', ['nx', 'ex' => 10]);

    if (!$gotLock) {
        usleep(100_000); // another request is rebuilding; wait 100 ms and retry once
        $cached = $redis->get($key);
        if ($cached !== false) {
            return json_decode($cached, true, 512, JSON_THROW_ON_ERROR);
        }
        return $loadFromDb(); // still missing: fall back to the database
    }

    try {
        $data = $loadFromDb();
        $ttl = 300 + random_int(0, 60); // jitter so keys do not expire together
        $redis->set($key, json_encode($data, JSON_THROW_ON_ERROR), ['ex' => $ttl]);
        return $data;
    } finally {
        $redis->del($lockKey);
    }
}

One request rebuilds the cache under a short lock while the others wait briefly or fall back.

Traps

  • Using APCu as if it were shared across servers, which leaves different nodes serving different values.
  • Giving every key the same fixed TTL, so a whole category expires in the same second.
  • Caching per-user data under a global key and leaking one user's data to another.
  • Letting a Redis outage throw on every request instead of degrading to direct reads.

Common questions

Short answers to the usual doubts.

Do I need to know exact php.ini default values for an interview?

Know the ones that change behaviour: display_errors should be off in production, max_execution_time does not count I/O time on Linux, default_socket_timeout is 60 seconds, and opcache.validate_timestamps controls whether code changes are picked up. Being able to explain why a setting matters is worth more than reciting numbers.

How should I answer a question about a PHP app returning 502 or 504 errors?

Walk the request path. Check whether nginx can reach FPM, whether the pool is saturated (status page: active workers and listen queue), whether workers are being killed by request_terminate_timeout or the OOM killer, and which downstream call is slow. Then propose both an immediate fix and a structural fix, such as timeouts, a fallback or queueing the slow work.

Is PHP 8 JIT relevant for typical web apps?

Usually only a little. Most web requests are dominated by I/O and framework bootstrapping, where OPcache already gives the main gain. JIT helps CPU-bound work such as heavy math or image processing. A good answer says to measure before enabling it and to stay alert to edge-case bugs.

Should long-running runtimes like RoadRunner, FrankenPHP or Swoole change my answers?

Yes. They keep the application in memory between requests, so the shared-nothing guarantee disappears. Static state, singletons and open connections persist across requests. Apply the same discipline you would use for queue workers: reset state per request, watch memory and recycle workers.

What is the quickest way to show seniority on these questions?

Talk about failure modes and trade-offs. Say what happens when the cache, database or remote API is slow or down. Say how you would detect it with logs, metrics or the FPM status page. Say what you would set or change, and what that change costs.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide6 of 7 · Languages and runtimesGo in Production: Concurrency, Shutdown, Errors and Runtime TuningRead the next one