Lesson 4 of 9 · 23m
Horizontal Scaling PHP: Make the App Stateless Before Buying More Servers
The constraints that decide whether ten PHP nodes behave like ten times capacity — sessions, uploads, cron, deploy consistency, and shared state.
PHP scales horizontally better than its reputation suggests, but only if the application behaves like a replaceable process rather than a pet. The first time traffic lands on two nodes, hidden local state turns into a production bug: sessions disappear, uploads 404, cron jobs run twice, and deployments behave differently depending on which server answers.
Move state out of the node
Local filesystem sessions are the classic trap:
session.save_handler = files
session.save_path = "/var/lib/php/sessions"That works until a user's second request reaches another node. Use Redis or the database for sessions:
session.save_handler = redis
session.save_path = "tcp://redis.internal:6379?database=2&prefix=sess:"The same rule applies to uploaded files. Write directly to object storage or queue a post-processing pipeline. If the file must touch local disk, treat it as a transient cache and remove it after upload succeeds.
Node-local caches are not shared truth
APCu is excellent for hot metadata because it is process-local and fast. It is not a coherence layer. On ten nodes, each node can hold a different value until TTL expiry. That may be fine for feature flags or schema metadata; it is unacceptable for inventory, authorization decisions, or anything requiring immediate global correctness.
Cron and singletons need explicit leadership
When you clone a node, you clone its crontab. Decide which jobs may run concurrently and which require a lock:
$lock = $redis->set('lock:rebuild-feed', $nodeId, ['nx', 'ex' => 300]);
if (!$lock) {
exit(0); // another node owns the job
}For critical jobs use a scheduler that understands distributed execution rather than a shell script and hope. Locks need expiry, job heartbeats need monitoring, and lock release should use a compare-and-delete token pattern.
Deploys are part of scaling
During a rolling deployment, old and new code coexist. Database migrations must be backward-compatible: add columns before writing them, deploy readers before dropping old behavior, and avoid cache keys whose meaning changes incompatibly between versions. Ten nodes do not deploy atomically.
Field notes
- Sticky sessions hide statelessness bugs and make load balancing lumpy. Use them only as a temporary migration aid.
- Hostnames, machine IDs, and local random files leak into application behavior more often than teams expect.
- Autoscaling on CPU alone fails when workers are blocked on I/O; queue depth and busy workers are better signals.
- A horizontally scaled app with one overloaded primary database is still vertically constrained at the bottleneck.
Was this lesson helpful?