Website Speed Optimization: PHP-FPM, OPcache, Redis, HTTP/3
Website speed optimization on a server comes down to four things: less work per request (PHP-FPM, OPcache, Redis), smaller responses (gzip or Brotli), fewer round trips (HTTP/2 and HTTP/3), and a shorter physical path to your users. Fix them in that order, and measure after each change so you know what actually helped.
This guide assumes a Linux VDS or dedicated server running Nginx and PHP 8.x. The commands work on Ubuntu and Debian. Adjust package names for AlmaLinux or Rocky.
Step 0: Measure Before You Change Anything
Start with a baseline. curl can split a request into phases:
curl -o /dev/null -s -w \
"dns: %{time_namelookup}\nconnect: %{time_connect}\ntls: %{time_appconnect}\nttfb: %{time_starttransfer}\ntotal: %{time_total}\n" \
https://example.com/
How to read it:
- connect is mostly network latency (one round trip).
- tls minus connect is the handshake cost (one or two more round trips).
- ttfb minus tls is server processing time. This is where PHP-FPM, OPcache, and Redis help.
- total minus ttfb is download time. This is where compression and caching help.
Run it from at least two places, including one near your real users. Run each test five or more times and compare medians, not single results.
Step 1: Tune PHP-FPM
The default pool settings are conservative and rarely match your workload. The key setting is pm.max_children. Too low and requests queue. Too high and the server swaps.
Estimate the average PHP worker size:
ps --no-headers -o rss -C php-fpm8.3 | awk '{s+=$1; n++} END {printf "avg MB: %.1f\n", s/n/1024}'
Then divide the RAM you can spare for PHP by that number. On a 4 GB VDS that also runs MySQL and Redis, you might give PHP 2 GB. With 60 MB workers, that is about 30 children.
Example pool file, /etc/php/8.3/fpm/pool.d/www.conf:
pm = dynamic
pm.max_children = 30
pm.start_servers = 8
pm.min_spare_servers = 6
pm.max_spare_servers = 12
pm.max_requests = 500
pm.status_path = /fpm-status
request_terminate_timeout = 60s
Notes:
pm.max_requestsrecycles workers and limits slow memory leaks from extensions.- On a busy, steady site,
pm = staticremoves the cost of spawning workers. It uses more memory all the time. - Use a Unix socket (
listen = /run/php/php8.3-fpm.sock) when Nginx and PHP are on the same host. It skips TCP overhead. - Check the log for
server reached pm.max_children. If you see it often and RAM is available, raise the limit. If RAM is not available, fix the slow code or add cache instead.
Enable the slow log to find the real bottleneck:
slowlog = /var/log/php8.3-fpm.slow.log
request_slowlog_timeout = 3s
Step 2: Configure OPcache Properly
OPcache stores compiled PHP bytecode in shared memory, so PHP doesn't re-parse your files on every request. It ships with PHP but is often under-sized. Put this in /etc/php/8.3/fpm/conf.d/10-opcache.ini:
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=1
opcache.revalidate_freq=60
For a production site with controlled deployments, set opcache.validate_timestamps=0 and reload PHP-FPM after each deploy (systemctl reload php8.3-fpm). PHP then never stats files on disk. If you forget the reload, you will serve old code, so put it in your deploy script.
Check usage with opcache_get_status() or a tool such as an OPcache status page restricted to your IP. If cache_full is true or the hit rate is below about 99%, raise memory_consumption or max_accelerated_files. The JIT gives little benefit for typical CMS and framework workloads, so don't spend time on it first.
Step 3: Add Redis for Object Cache and Sessions
Database queries are the next common cost. Redis keeps repeated query results and sessions in memory. WordPress, Magento, Laravel, and Drupal all have Redis drivers.
apt install redis-server php-redis
In /etc/redis/redis.conf:
bind 127.0.0.1 ::1
protected-mode yes
maxmemory 256mb
maxmemory-policy allkeys-lru
unixsocket /run/redis/redis-server.sock
unixsocketperm 770
Common mistakes:
- Exposing Redis to the internet. Bind to localhost or a private address and block port 6379 in your firewall. Open Redis instances get abused quickly.
- No
maxmemory. Redis grows until the OOM killer picks something, often MySQL. - Using
allkeys-lrufor sessions and cache in the same instance. Eviction can log users out. Use a separate instance or database, or avolatile-lrupolicy with TTLs, for sessions. - Expecting Redis to fix slow queries. Check
slow_query_login MySQL too.
Verify the cache works: redis-cli info stats | grep keyspace should show hits growing relative to misses.
Step 4: Compress Responses with gzip and Brotli
Text assets (HTML, CSS, JS, JSON, SVG) compress very well. Images, video, and archives do not, so skip them.
Gzip in Nginx:
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_vary on;
gzip_proxied any;
gzip_types text/css application/javascript application/json image/svg+xml application/xml text/plain;
Brotli typically produces smaller files than gzip at similar CPU cost and is supported by all current browsers over HTTPS. It needs the ngx_brotli module (a package such as libnginx-mod-http-brotli-filter on some distributions, or a dynamic build):
brotli on;
brotli_comp_level 5;
brotli_types text/css application/javascript application/json image/svg+xml application/xml text/plain;
Keep the level moderate. Levels 9-11 cost a lot of CPU for dynamic responses. If you want maximum compression, precompress static files at build time and serve them with brotli_static on; and gzip_static on;.
Also set long cache headers on versioned static files:
location ~* \.(css|js|woff2|jpg|png|webp|avif|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
Only use immutable if filenames change when content changes (for example app.3f9c1a.js).
Step 5: Enable HTTP/2 and HTTP/3
HTTP/2 multiplexes many requests over one TCP connection. HTTP/3 runs over QUIC (UDP), which avoids TCP head-of-line blocking and handles lossy mobile networks better. Nginx 1.25.0 and later supports QUIC. The configuration needs a build with QUIC support, which the official nginx.org packages include.
server {
listen 443 ssl;
listen [::]:443 ssl;
listen 443 quic reuseport;
listen [::]:443 quic reuseport;
http2 on;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Alt-Svc 'h3=":443"; ma=86400' always;
}
Then open UDP 443. This is the most common reason HTTP/3 silently fails:
ufw allow 443/udp
Test with curl --http3 -I https://example.com/ (needs a curl build with HTTP/3) or check the protocol column in your browser's network tab. Browsers fall back to HTTP/2 if QUIC is blocked, so nothing breaks, but you get no benefit. If you use a DDoS filter or firewall in front of the server, make sure it passes UDP 443 too.
Don't bother with HTTP/2 server push. Browsers have removed support for it.
Step 6: Server Location and Latency
Network distance sets a floor that no tuning can remove. Light in fiber travels about 200 km per millisecond, so each 100 km of fiber path adds roughly 1 ms to the round trip, and real routes are longer than straight lines. A new HTTPS connection needs several round trips before the first byte arrives: TCP, TLS, then the request. A 150 ms round trip can add 300-450 ms before your application does any work.
Practical rules:
- Place the origin near the majority of your users, not near you.
- Use a CDN for static assets if your audience is global. Keep the dynamic origin in one region.
- For game servers, VoIP, and trading-style workloads, latency matters more than throughput. Choose by round-trip time.
- Test the routes, not just the distance. Two locations 500 km apart can behave differently depending on peering.
Nixcon Group LLC runs its own network (AS40368) with a data center in İzmir, Turkey, and points of presence in Frankfurt, Germany, and Fremont, California. That lets you place a server near Turkey and the Eastern Mediterranean, Central Europe, or the US West Coast. Before you commit, use the public looking glass to run ping and traceroute from İzmir, Frankfurt, and the US toward your own users' networks.
If you want root access to tune all of the above, a VDS or VPS with full control fits most sites. Heavy databases and high-traffic stores that need dedicated CPU and disk are better on dedicated servers.
Common Mistakes Checklist
- Tuning PHP when the real delay is a slow database query or an external API call.
- Setting
pm.max_childrenby guess and pushing the server into swap. - Leaving OPcache at defaults on a large codebase, so the cache fills and thrashes.
- Running Redis without
maxmemoryor exposing it publicly. - Compressing images or using gzip level 9 on dynamic pages.
- Enabling HTTP/3 without opening UDP 443.
- Testing only from the server itself, where latency is near zero.
Recommended Order of Work
- Take a baseline with
curltiming from two locations. - Size PHP-FPM and enable OPcache. Re-measure TTFB.
- Add Redis object cache. Re-measure.
- Enable compression and cache headers. Check transfer size.
- Turn on HTTP/2 and HTTP/3. Check connection time on mobile and distant clients.
- Review location and CDN if distant users still see slow connect and TLS times.
Each step is small and reversible. Together they usually matter far more than a hardware upgrade.
Frequently asked questions
How many PHP-FPM max_children should I set?
Divide the RAM you can dedicate to PHP by the average memory of one PHP-FPM worker. Measure the worker size with ps, leave room for the database, Redis, and the OS, and watch the PHP-FPM log for 'reached pm.max_children' warnings.
Is Brotli better than gzip?
Brotli usually gives smaller text files than gzip at a similar moderate compression level, and all current browsers support it over HTTPS. Keep gzip enabled as a fallback and use a moderate level for dynamic content.
Why is HTTP/3 not working after I enabled it in Nginx?
The usual cause is that UDP port 443 is blocked by the host firewall, a network firewall, or a filtering layer. Also confirm your Nginx build includes QUIC support and that the Alt-Svc header is being sent.
Does server location really affect website speed?
Yes. Every new HTTPS connection needs multiple round trips before the first byte, so a distant server adds latency that code tuning cannot remove. Choose a location near most of your users and use a CDN for static files if your audience is global.