Scaling Strategies: Vertical, Horizontal, Diagonal, Stateless Design, Autoscaling
"Twelve-factor processes are stateless and share-nothing. Any data that needs to persist must be stored in a stateful backing service, typically a database." — The Twelve-Factor App, VI. Processes (12factor.net)
Summary: You scale a system in three ways: you make one machine bigger (vertical scaling), you add machines (horizontal scaling), or you do both in a planned order (diagonal scaling). Adding machines only works when the processes are stateless. Once they are, an autoscaler can add and remove replicas for you, as long as each replica starts fast, fails its readiness check before it stops, and drains cleanly. Focus: Scale up vs scale out and what limits each (NUMA, the cost curve, the single point of failure, the coordination tax), Amdahl's law and Gunther's Universal Scalability Law (contention σ, coherence κ, the retrograde peak), shared-nothing and 12-factor processes, externalised state and why sticky sessions are a smell, scaling reads vs writes, scale-up vs scale-out per tier, autoscaling (metrics, target tracking, step, predictive and scheduled policies, cooldowns, stabilization windows, flapping, warm pools, scale to zero and cold starts) on Kubernetes (HPA, VPA, KEDA, Cluster Autoscaler, Karpenter) and AWS (EC2 Auto Scaling), readiness probes and graceful shutdown, headroom and N+1/N+2, cost (right-sizing, spot, reserved, serverless), load testing to find the knee (k6, wrk, vegeta), Laravel Octane and Horizon balancing, and Conway's law. Learning goal: For any service, say which tier to scale first and in which direction, show with a USL fit where adding nodes stops paying, make the process stateless, configure an autoscaler with the right metric, bounds and stabilization, size headroom for N+2, and prove the numbers with an open-model load test.
This chapter opens the Traffic & Scale group. It owns the system-level decision: which direction to scale, the numbers that justify it and the trade-off tables. Mechanics live with the siblings: how requests are spread in Load Balancing; cache patterns in Caching and edge caching in CDNs; replicas and failover in Replication, Read Replicas & Failover and the topologies in Replication Topologies; partitioning in Sharding at System Level and Partitioning & Sharding in PostgreSQL; the database scale ladder in Storage & Data Scaling; write batching in Write Buffering & Sharded Counters; queue workers in Competing Consumers & Scaling Consumers; the estimation method in Capacity Estimation and the long-range plan in Capacity Planning & Disaster Recovery; Kubernetes objects in Containers & Kubernetes; functions in Serverless & Event-Driven Compute; overload in Load Shedding; queueing and the knee in Latency Budgets & Tail Latency; team boundaries in Service Boundaries.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why scaling is a design decision, not a purchase | Why it exists |
| Amdahl 1967, shared-nothing, Gunther, Conway, 12-factor, SRE | Where it comes from |
| Bigger machine, more machines, both | Vertical, Horizontal, Diagonal |
| The maths of diminishing returns | Amdahl's law, Universal Scalability Law |
| Making replicas interchangeable | Stateless design, Sticky sessions |
| Reads vs writes, per tier | Scaling reads, Scaling writes, Per tier, Database last |
| Autoscaling policies and their failure modes | Policies, Cooldowns and flapping, Kubernetes autoscalers, Cold starts |
| Replicas that can be killed safely | Readiness and graceful shutdown |
| How much spare capacity | Headroom and N+2 |
| The bill | Cost |
| Finding the limit | Load testing and the knee |
| Laravel specifics | Octane and Horizon |
| Teams | Conway's law |
| Formulas, knobs, defaults, events | Mechanics |
| Code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| Which strategy, which autoscaler | Choosing |
| Monolith to distributed system | In architecture |
| Run it | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three directions.
| Strategy | In plain words | Tiny example | Gives you | Costs you |
|---|---|---|---|---|
| Vertical scaling (scale up) | A bigger machine | PostgreSQL primary from 8 to 32 vCPU | No code change, no coordination | Ceiling, price curve, one failure domain, downtime to resize |
| Horizontal scaling (scale out) | More machines of the same kind | 4 to 12 stateless API pods behind an AWS ALB | Near-linear capacity, redundancy, autoscaling | State must move out, load balancing, coordination tax |
| Diagonal scaling | Grow each node to its sweet spot, then add nodes | Move from 2-vCPU to 8-vCPU pods, then scale out | Best cost per request, fewer nodes to coordinate | Two dimensions to tune |
| Autoscaling | Let a controller change the count (or size) | Kubernetes HPA on RPS per pod, min 3, max 40 | Pay for what you use, absorb peaks | Lag, flapping, cold starts, surprise bills |
What usually scales which way, per tier.
| Tier | Default direction | Why | Watch out for |
|---|---|---|---|
| CDN / edge | Out (provider does it) | Cache hits never reach you | Cache misses on purge, see CDN |
| Load balancer | Out (managed) or up (HAProxy/NGINX box) | Mostly network-bound | Connection limits, pre-warming for huge spikes |
| Web / API tier | Out, autoscaled | Stateless by design | Sessions, local files, in-memory caches |
| Queue workers | Out on queue depth | Jobs are independent | Ordering, DB connections, idempotency |
| Cache (Redis) | Up first, then out (Redis Cluster) | Single-threaded command loop, memory-bound | Hot keys, resharding |
| Message broker | Out by partitions (Kafka), up per node (RabbitMQ queue) | Throughput tied to partitions or queues | Partition count fixed in advance |
| Relational database | Up first, then read replicas, shard last | Writes need one owner per row | Replica lag, connection count, cross-shard queries |
The autoscaling toolbox.
| Tool | Scales | On | Reaction | Product |
|---|---|---|---|---|
| HPA | Pod count | CPU, memory, custom, external metrics | 15 s loop + pod start | Kubernetes |
| VPA | Pod requests (size) | Observed usage | Restart or in-place resize | Kubernetes add-on (CRD) |
| KEDA | Pod count, 0 to N | Queue length, lag, cron and many other event sources | Polls every 30 s by default | CNCF project on top of HPA |
| Cluster Autoscaler / Karpenter | Nodes | Pending pods, unneeded nodes | Node boot (minutes) | Kubernetes |
| EC2 Auto Scaling | Instances | Target tracking, step, predictive, scheduled | Instance boot, warm pools | AWS |
| Horizon balancing | Worker processes per queue, on one host | Queue size or estimated time to clear | balanceCooldown seconds | Laravel |
Why it exists
A single process on a single machine is the cheapest, fastest, most consistent system you can build: every piece of data is one memory access away and there is nothing to coordinate. Load grows, and at some point one machine is not enough: CPU saturates, memory runs out, one disk cannot do more IOPS, or one machine failing takes everything down. Scaling strategies are the set of answers to "what now?", and each answer moves a cost somewhere else.
| Scale up (vertical) | Scale out (horizontal) |
|---|---|
| No code change | Code must be stateless or partitioned |
| Strong consistency for free (one memory) | Consistency must be designed (replicas, caches) |
| Price grows faster than capacity at the top end | Price grows roughly linearly with nodes |
| Hard ceiling (largest instance) | Ceiling set by the coordination tax (USL) |
| One failure domain | Redundancy and rolling deploys come with it |
| Resize often means a restart | Add or remove nodes live |
An everyday picture: a restaurant kitchen. One cook with a bigger stove is vertical scaling: simpler, and the cook knows every order, but there is only so big a stove gets and if the cook is ill, nobody eats. Hiring more cooks is horizontal scaling: more meals per hour, but now the recipes and the order tickets must live on a shared board (externalised state) instead of in one cook's head, the cooks bump into each other at the single fridge (contention) and spend time telling each other what they changed (coherence). Diagonal scaling is giving each cook a proper station first and then hiring. Autoscaling is the shift manager calling in extra cooks when the ticket rail fills up; it works only if a new cook can start in minutes and nobody walks out mid-dish when sent home (graceful shutdown).
Three common misunderstandings, up front
- "Horizontal is always better." For the database tier, a bigger primary is usually cheaper and safer than a shard map for years. Scale out what is stateless; scale up what owns state until the numbers say otherwise.
- "Doubling nodes doubles throughput." Only with zero contention and zero coordination. The USL says the curve bends (contention) and eventually turns down (coherence); measure it.
- "Autoscaling makes capacity planning unnecessary." The autoscaler reacts after the metric moves and needs minutes for nodes. You still need headroom, sane min/max bounds, and a load test that shows where the knee is.
Where it comes from
- Amdahl, 1967. Gene Amdahl presented Validity of the single processor approach to achieving large scale computing capabilities at the AFIPS Spring Joint Computer Conference (1967, pp. 483–485). The formula now called Amdahl's law is a later formalisation of his argument; this page reads it through the Wikipedia summary (secondary source): "the overall performance improvement gained by optimizing a single part of a system is limited by the fraction of time that the improved part is actually used."
- Shared-nothing. According to Wikipedia (secondary), Tandem NonStop shipped a shared-nothing system in 1976, Teradata delivered the first shared-nothing database in 1983, and Michael Stonebraker used the term in The Case for Shared Nothing (1986).
- Conway, 1968. Melvin Conway's How Do Committees Invent?: "organizations which design systems (in the broad sense used here) are constrained to produce designs which are copies of the communication structures of these organizations."
- Gunther's Universal Scalability Law. Neil Gunther developed the USL for TPC benchmark scalability (Wikipedia, secondary) and proved its queueing basis in A General Theory of Computational Scalability Based on Rational Functions (arXiv 0808.1431, 2008): "Simpler rational functions, such as Amdahl's law and Gustafson speedup, are corollaries of this queue-theoretic bound."
- The Twelve-Factor App. Factor VI (Processes) and VIII (Concurrency, "Scale out via the process model") turned statelessness into a deployment contract; factor IX (Disposability) adds "Processes shut down gracefully when they receive a SIGTERM signal from the process manager."
- Google SRE Book. Service Best Practices defines the "N + 2" configuration; Addressing Cascading Failures works the arithmetic (5,000 QPS per cluster, 19,000 QPS peak, about six clusters at N + 2); Handling Overload warns against modelling capacity as raw QPS.
- Autoscalers. AWS EC2 Auto Scaling (target tracking, step, scheduled, predictive policies, warm pools), the Kubernetes HorizontalPodAutoscaler (a control loop with a 15-second default period), the VerticalPodAutoscaler and Cluster Autoscaler (kubernetes/autoscaler repository), KEDA for event-driven scaling and scale to zero, and Karpenter as a newer node provisioner.
The concept catalogue
Every block follows the same order: plain words, the usual misunderstanding, a definition, a timeline, real scenarios, what each product provides, and the fix.
Vertical scaling: bigger machines Must-know
In plain words: keep one machine and make it bigger: more vCPU, more RAM, faster disks, a bigger network pipe.
Common misunderstanding: "Vertical scaling is a beginner's move." It is the right first move for anything that owns state (a database primary, a Redis node, a single-writer broker queue), because it costs no design work and keeps strong consistency. It becomes wrong when you hit the ceiling, when the price per unit of capacity climbs, or when one failure domain is no longer acceptable.
Definition: increasing the resources of a single node. Limits:
- Ceiling: the largest instance type your provider sells, or the largest box you can buy.
- Cost curve: at the top end, the largest sizes and specialised hardware tend to cost more per unit of capacity than mid-size nodes (check your provider's price list; this is a common pattern, not a law).
- NUMA: large servers have several CPU sockets, each with local memory; Wikipedia (secondary): "a processor can access its own local memory faster than non-local memory." A process that was fast on 8 cores may not be 8 times faster on 64 cores, because threads now touch remote memory and contend on shared locks. Database engines and the JVM have NUMA settings for this reason.
- Single point of failure: one machine means one kernel, one disk controller, one rack. A bigger box makes the outage bigger, not rarer.
- Resize downtime: most cloud resizes stop the instance; a managed database resize is usually a failover to a resized standby.
Vertical resize of a PostgreSQL primary on a managed service (typical sequence)
1 t=0 resize requested: db.r-large -> db.r-4xlarge
2 t+1m standby is created or resized with the new class
3 t+8m standby catches up on WAL
4 t+9m failover: clients see connection resets for some seconds
5 t+10m old primary becomes the new standby (or is replaced)
cost: one failover, no code change; capacity: about 4x CPU and RAMReal scenario: a SaaS app whose PostgreSQL primary is at 80% CPU moves to a 4x larger instance and buys two years; a Redis node runs out of memory and gets a bigger node before anyone touches Redis Cluster; a single RabbitMQ queue is bounded by one core, so a faster CPU helps and more nodes do not (one queue lives on one node, see RabbitMQ); a reporting job that needs 400 GB in memory runs on one large instance instead of a cluster.
| Product | Vertical knob | Note |
|---|---|---|
| AWS EC2 | Change instance type | Requires stop/start for EBS-backed instances |
| AWS RDS / Aurora | Modify DB instance class | Multi-AZ applies it with a failover |
| Kubernetes | Change resources.requests/limits; VPA | In-place resize (VPA InPlaceOrRecreate/InPlace) avoids restarts where supported |
| Redis | Bigger node, maxmemory | Command execution is single-threaded per node |
| PostgreSQL | Bigger box; shared_buffers, max_connections, work_mem | Writes still go through one primary |
Fix / how to use it: scale up the stateful tier first and measure; set an explicit "next step" trigger (for example "when the largest affordable size is 70% busy at peak, plan replicas or partitioning"); keep a standby so the bigger box is not the only box.
Horizontal scaling and shared-nothing Must-know
In plain words: add more machines that do the same job and put a load balancer in front so each gets a share of the work.
Common misunderstanding: "Horizontal scaling is a deployment setting." It is a property of the code. If a replica keeps anything a later request needs (a session, an uploaded file, a counter, a lock), a second replica breaks correctness, not just performance.
Definition: increasing capacity by adding nodes. It requires either statelessness (any node can serve any request because state lives in shared backing services) or partitioning (each node owns a disjoint slice of the state, as in sharding). Shared-nothing is the architecture where nodes share no memory or disk and coordinate only over the network; 12-factor: "The share-nothing, horizontally partitionable nature of twelve-factor app processes means that adding more concurrency is a simple and reliable operation." The price is the coordination tax: load balancing, health checking, consistency of shared data, and the contention on whatever stays shared.
Scale-out of a stateless API tier
1 client -> AWS ALB -> pod-a (session read from Redis)
2 client -> AWS ALB -> pod-b (same session, same Redis key: works)
3 HPA adds pod-c; readinessProbe passes after warm-up
4 ALB target group / EndpointSlice includes pod-c -> it receives 1/3 of new requests
5 PostgreSQL primary now sees 3 pools of connections -> the shared part becomes the limitReal scenario: an API tier going from 3 to 30 pods for Black Friday; a fleet of image resizers that each take a job from a queue; Kafka consumers in one group, one per partition; a read path served from five PostgreSQL replicas; a Laravel app on Laravel Cloud or Forge with several web servers behind one load balancer.
| Product | Horizontal knob | The shared part you must watch |
|---|---|---|
| Kubernetes Deployment | replicas, HPA | Database connections, Redis, rate limits of third-party APIs |
| AWS EC2 Auto Scaling | Desired capacity, min/max | Same, plus instance boot time |
| Kafka | Partitions per topic, consumers per group | Consumers beyond partition count sit idle |
| Redis Cluster | Shards (16,384 hash slots) | Multi-key operations need hash tags |
| PostgreSQL | Read replicas, Citus shards | Writes still have one owner per row |
Fix / how to use it: make the tier stateless first (Stateless design), put an L7 load balancer in front (Load Balancing), size connection pools so replicas × pool stays under the database's limit (Connection Pooling), and measure the USL curve before promising linear growth.
Diagonal scaling Important
In plain words: first make each node the right size, then add more of them. You move up and out at the same time, along a diagonal.
Common misunderstanding: "Many tiny nodes are always the most elastic." Tiny nodes waste a bigger share of each node on the operating system, sidecars, agents and per-process baseline memory, and every extra node adds coordination (more connections to the database, more peers in a gossip ring, more targets per load balancer). Huge nodes make each failure and each autoscaling step coarse. The sweet spot is in between.
Definition: a scaling plan that combines vertical and horizontal steps, typically: scale up to the node size with the best price-performance and acceptable blast radius, then scale out with nodes of that size. Variants: scale out quickly with small nodes during a spike, then consolidate onto fewer larger nodes (Karpenter consolidation does this for Kubernetes nodes).
Diagonal plan for a Go API (back-of-envelope, labelled estimate)
1 today: 10 pods x 0.5 vCPU, each pod ~1,000 req/s at 70% CPU, Redis pool 10/pod
2 step 1: pods to 2 vCPU (GOMAXPROCS=2): ~3,600 req/s per pod measured, 3 pods do the job
3 step 2: autoscale 3..20 pods of 2 vCPU on RPS per pod
4 result: 3 to 20 DB/Redis pools instead of 10 to 70; same capacity, fewer connectionsReal scenario: JVM or PHP-FPM services whose per-process memory makes tiny pods wasteful; Kafka brokers where bigger disks and NICs per broker beat more brokers; Elasticsearch data nodes sized to a heap limit and then multiplied; a PostgreSQL primary scaled up, then read replicas of the same class added.
Fix / how to use it: load-test one node at three sizes, pick the size with the best requests per dollar at your latency target, then autoscale the count. Re-check after major releases.
Amdahl's law Must-know
In plain words: if part of the work can only be done by one worker at a time, adding workers speeds up only the rest. The serial part sets a ceiling.
Common misunderstanding: "5% serial code is negligible." With σ = 0.05 the maximum speedup is 1/0.05 = 20, no matter how many nodes you add. At 64 nodes you get about 15.4x.
Definition: with serial fraction σ (Gunther's notation; Wikipedia writes 1 − p), speedup on N workers is S(N) = N / (1 + σ(N − 1)), and S(N) → 1/σ as N grows. In Gunther's 2008 paper this is equation (2), the USL with κ = 0. In systems, the "serial part" is anything that serialises requests: one database primary, one lock, one Redis key, one partition, a global counter, a single leader.
Amdahl, sigma = 0.03, one node = 1,000 req/s (from this page's scalecalc)
N ideal Amdahl
1 1 1,000 1,000
2 8 8,000 6,612
3 32 32,000 16,580
4 128 128,000 26,611
ceiling 1/sigma = 33x = 33,333 req/s, never reachedReal scenario: a checkout that takes SELECT ... FOR UPDATE on one "inventory" row; a global rate limiter in one Redis key; a ledger with one sequence; a batch pipeline whose final merge runs on one node; a microservice whose every call goes through one auth service with a lock on token refresh.
Fix / how to use it: find the serial part with profiling and lock statistics (PostgreSQL pg_locks, pg_stat_activity.wait_event), then shrink it: partition the hot row (Sharded Counters), batch writes, move work out of the critical section, or accept the ceiling and stop adding nodes.
Universal Scalability Law: contention and coherence Must-know
In plain words: Amdahl explains why the curve flattens; the USL also explains why it can go down. Every extra node not only waits for the shared part (contention) but also has to keep its view of shared data in sync with every other node (coherence), and that second cost grows with the square of the node count.
Common misunderstanding: "If throughput stopped growing, add more nodes until it does." Past the USL peak, more nodes make throughput lower. Teams see this as "we scaled from 40 to 60 pods and got slower".
Definition: Gunther's relative capacity C(N) = X(N)/X(1) = N / (1 + σ(N − 1) + κN(N − 1)). In the 2008 paper the terms represent: "1. Ideal concurrency associated with linear scalability (σ,κ = 0) 2. Contention-limited scalability due to serialization or queueing (σ>0,κ = 0) 3. Coherency-limited scalability due to inconsistent copies of data (σ,κ>0)". The maximum is at N* = √((1 − σ)/κ); "beyond p* the throughput becomes retrograde". σ is contention (queueing for a shared resource); κ is coherence or coordination cost (pairwise exchange: cache invalidation, distributed locks, gossip, cross-shard queries, consensus round trips).
USL, sigma = 0.03, kappa = 0.0005, X(1) = 1,000 req/s (from scalecalc)
N USL X efficiency C(N)/N
1 8 6,462 81%
2 16 10,191 64%
3 32 13,190 41%
4 44 13,597 31% <- peak N* = sqrt(0.97/0.0005) = 44.0
5 64 13,045 20% <- retrograde
6 128 9,893 8%Real scenario: an app tier where every pod holds a local cache and broadcasts invalidations to all others (κ grows with pairs); a PostgreSQL primary where 60 pods × 20 connections means 1,200 backends fighting over locks and CPU; a Cassandra or Redis Cluster client fanning out multi-key reads to more nodes; a Kafka consumer group that rebalances on every scale event; a distributed lock that everyone polls.
| Source of σ (contention) | Source of κ (coherence) |
|---|---|
| One primary database, one hot row | Cache invalidation broadcast to all peers |
| A global lock or mutex | Distributed lock negotiation, consensus |
| One partition or one queue | Consumer-group rebalances, gossip |
| A rate-limited third-party API | Cross-shard joins and scatter-gather |
| Connection pool limits | Every node talking to every node (full mesh) |
Fix / how to use it: fit σ and κ to four or more load-test points (the usl package below does least squares), report N*, and set the autoscaler max below it. Reduce σ by partitioning and batching; reduce κ by removing all-to-all communication (subsetting in Google's load balancing, consistent hashing, local decisions).
Stateless design and externalised state Must-know
In plain words: a stateless process forgets everything between requests. Anything that must be remembered (who the user is, what is in the cart, the uploaded file) lives in a shared service that all replicas use.
Common misunderstanding: "Stateless means the system has no state." The state still exists; it moved down to Redis, the database and object storage. Those become the stateful tier you must scale, back up and make highly available. "Stateless" is a property of the process, not of the system.
Definition: a stateless service keeps no request-to-request data in process memory or on local disk; a stateful one does. Externalised state means: sessions in Redis, Memcached, DynamoDB or the database; caches in a shared cache (local caches only as an optimisation that tolerates misses); files in object storage (Amazon S3, GCS, Azure Blob); configuration in the environment; scheduled jobs owned by a single scheduler or a lock. 12-factor VI: "Twelve-factor processes are stateless and share-nothing." Two kinds of local state are fine: per-request scratch data and caches that are safe to lose.
One user, three replicas, externalised state
1 POST /cart/items (pod-a) -> RPUSH cart:7f3c... "book-42"; EXPIRE 1800
2 POST /cart/items (pod-b) -> RPUSH cart:7f3c... "pen-7" (atomic, no lost update)
3 HPA removes pod-a (scale-in); nothing is lost
4 GET /cart (pod-c, new) -> LRANGE cart:7f3c... 0 -1 -> ["book-42","pen-7"]Real scenario: Laravel sessions moved from the file driver to redis before adding a second server; user uploads moved from storage/app to an S3 disk; a Go service's in-memory rate limiter moved to Redis so limits hold across pods (Rate Limiting); WebSocket connections are inherently stateful, so presence moves to Redis and the connection tier is scaled separately (Real-Time Communication).
| State | Where it should live | Laravel 13 | Go |
|---|---|---|---|
| Session | Redis / database / signed cookie | SESSION_DRIVER=redis (drivers: file, cookie, database, memcached, redis, dynamodb, array) | Cookie with an opaque id + go-redis |
| Cache | Redis / Memcached | CACHE_STORE=redis | go-redis, local LRU only for safe-to-lose data |
| Files | Object storage | FILESYSTEM_DISK=s3, Storage::disk('s3') | AWS SDK for Go v2 S3 client |
| Locks | Redis, database, etcd | Cache::lock() | Redis SET NX PX, see Distributed Locking |
| Jobs | Queue (Redis, SQS, database) | QUEUE_CONNECTION=redis | A broker client |
| Config and secrets | Environment / secret store | config:cache at deploy | os.Getenv, flags |
Fix / how to use it: in SQL, the Laravel database session driver's table is the externalised session store when Redis is not available:
-- Laravel's sessions table (database session driver); every replica reads the same rows
CREATE TABLE sessions (
id varchar(255) PRIMARY KEY,
user_id bigint NULL,
ip_address varchar(45) NULL,
user_agent text NULL,
payload text NOT NULL,
last_activity integer NOT NULL
);
CREATE INDEX sessions_user_id_index ON sessions (user_id);
CREATE INDEX sessions_last_activity_index ON sessions (last_activity);
-- garbage collection of expired sessions (Laravel's lottery does the same)
DELETE FROM sessions WHERE last_activity < extract(epoch FROM now() - interval '2 hours');The Go and Laravel versions are in Go and Laravel.
Sticky sessions (session affinity) Important
In plain words: the load balancer remembers which server a user went to and keeps sending them there, so a server can keep that user's session in memory.
Common misunderstanding: "Sticky sessions solve the session problem." They hide it. When that server is removed by a scale-in, a deploy or a crash, its users lose their sessions; load spreads unevenly because heavy users stay on one node; and new nodes added by the autoscaler get only new users, so they take minutes to share the load. 12-factor: "Sticky sessions are a violation of twelve-factor and should never be used or relied upon."
Definition: session affinity binds a client to a backend by a cookie (AWS ALB stickiness cookie AWSALB, NGINX sticky, HAProxy cookie directive) or by source IP hash (Kubernetes Service sessionAffinity: ClientIP). It is a smell for application sessions. It is legitimate as a performance hint when losing it only costs a cache miss (for example, routing a tenant to a node with a warm local cache via consistent hashing), and unavoidable for protocols that are connection-bound (WebSockets, long polling, gRPC streams), where the fix is reconnect logic, not stickiness.
Sticky sessions during a scale-in
1 user U pinned to pod-b by cookie; cart kept in pod-b memory
2 traffic drops; HPA scales 6 -> 4; pod-b is chosen
3 pod-b gets SIGTERM; cart in memory is gone
4 next request: ALB picks pod-d; empty cart; user abandons checkoutReal scenario: a legacy Java app with HttpSession in memory behind sticky ALB cookies; a PHP app with the file session driver on two servers; a Socket.IO deployment that needs stickiness for its long-polling fallback; Kubernetes ClientIP affinity making one pod hot because a corporate NAT puts 5,000 users behind one IP.
Fix / how to use it: move sessions to Redis or the database, turn stickiness off, and treat any remaining affinity (cache locality, WebSockets) as optional with reconnect and rehydration paths. Mechanics of cookies, hashing and draining are in Load Balancing.
Scaling reads: replicas, caches, CDN Must-know
In plain words: most systems read far more than they write, and reads are easy to copy: serve them from copies of the data.
Common misunderstanding: "A read replica doubles database capacity." It adds read capacity only, with replica lag: a user who just wrote may read the old value from a replica. It does nothing for write load, and each replica still replays every write.
Definition: three layers, cheapest first: CDN for public, cacheable responses and static assets (CDN); cache (Redis, Memcached, in-process) for hot objects and computed results (Caching); read replicas for queries that need the database (Replication, Read Replicas & Failover). Measure the read/write ratio before choosing.
-- PostgreSQL: rough read vs write volume since stats reset (rows, not queries)
SELECT datname,
tup_returned + tup_fetched AS rows_read,
tup_inserted + tup_updated + tup_deleted AS rows_written,
round((tup_returned + tup_fetched)::numeric
/ nullif(tup_inserted + tup_updated + tup_deleted, 0), 1) AS read_write_ratio
FROM pg_stat_database
WHERE datname = current_database(); Read path after scaling reads
1 GET /products/42 -> Cloudflare/CloudFront: HIT (no origin request)
2 MISS -> API pod -> Redis GET product:42: HIT (0.3 ms)
3 MISS -> PostgreSQL replica SELECT ... (2 ms, possibly 100 ms stale)
4 write path: PUT /products/42 -> primary; DEL product:42; CDN purge
5 read-your-writes: the editor's next GET is pinned to the primary for 5 sReal scenario: a product catalogue at 200:1 reads to writes; a news site where the CDN absorbs 95% of requests; dashboards running on a replica so they cannot slow checkout; a social feed served from precomputed timelines in Redis (Feeds).
Fix / how to use it: cache first, replicas second; route by intent (Laravel read/write connections with sticky => true, Go two *sql.DB handles); design for staleness explicitly; remember the SRE book's warning that a "capacity cache" (one you cannot run without) is a hard dependency.
Scaling writes: sharding, queues, batching Must-know
In plain words: writes must land on the one place that owns the data, so you cannot just copy them. You either split the data so each owner gets fewer writes (sharding), smooth them out over time (queues), or make each write do more work (batching).
Common misunderstanding: "Add a queue and the database can take any write rate." A queue absorbs bursts, but if the average write rate exceeds what the consumers and the database can do, the queue grows without limit. It buys time, not capacity.
Definition: sharding partitions data by a key so each shard owns a slice (Sharding at System Level); a queue decouples the request from the write and lets workers process at a sustainable rate (Competing Consumers); batching and coalescing turn N small writes into one larger write (multi-row INSERT, COPY, Kafka producer linger.ms/batch.size, Redis pipelining) (Write Buffering).
-- Batching: one round trip and one commit instead of 500
INSERT INTO page_views (page_id, viewed_at)
SELECT unnest($1::bigint[]), unnest($2::timestamptz[]);
-- Coalescing a hot counter: many increments become one update per flush
UPDATE products SET view_count = view_count + $2 WHERE id = $1; Writes during a flash sale
1 10,000 orders/s arrive at the API tier (autoscaled to 40 pods)
2 API validates and enqueues OrderPlaced -> SQS / Kafka (accepts in 5 ms)
3 30 workers drain at 3,000/s, batching 50 rows per INSERT
4 queue depth peaks at 200,000, drains in ~3 min after the spike
5 if the spike lasted an hour, the queue would hold 25 M messages: you need shards, not a queueReal scenario: an analytics ingest that batches events into COPY; a like counter split into 16 sub-counters; a multi-tenant SaaS sharded by tenant_id; payments that must stay on one primary but move notifications and ledger exports to queues.
Fix / how to use it: batch first (cheapest), queue to absorb bursts, shard when one primary cannot take the steady-state write rate even after scaling up. Shard keys and rebalancing are owned by the sharding chapters.
Scale-up vs scale-out per tier Important
In plain words: each layer of the system has a natural direction. Stateless layers go out; layers that own state go up first.
Common misunderstanding: "We are a microservices shop, so everything scales horizontally." Your database, your cache and your broker each have their own rules; a Kafka topic scales out only up to its partition count, a RabbitMQ queue lives on one node, a Redis key lives on one shard.
Definition: a per-tier scaling decision, recorded in the design, with the trigger for the next step.
Scaling order for a typical web product (each step only when measured)
1 web/API: stateless + autoscale out (day 1)
2 cache: add Redis, scale up the node (when DB read CPU > 60%)
3 DB: scale up the primary; add 1-2 read replicas (when primary CPU > 60%)
4 queue workers: scale out on queue depth (KEDA / Horizon) (when async work appears)
5 cache: Redis Cluster; DB: partition big tables (when one node is not enough)
6 DB: shard writes by tenant or user (last, after 3 and 5)| Tier | Scale up when | Scale out when | Product notes |
|---|---|---|---|
| Web / API | Per-request CPU is high and pods are tiny | Always the default | Kubernetes HPA, EC2 ASG, Laravel Octane workers per pod |
| Queue workers | Jobs are memory-heavy | Queue depth or age grows | KEDA, Horizon maxProcesses |
| Redis | Memory or single-core CPU is the limit | Dataset or ops/s exceed one node | Redis Cluster, ElastiCache cluster mode |
| Kafka | Disk or NIC per broker is the limit | Partitions and brokers can grow | Partition count is hard to reduce |
| RabbitMQ | One queue is the bottleneck | Many queues, spread over nodes | Quorum queues replicate, they do not shard |
| PostgreSQL / MySQL | Almost always first | Reads: replicas; writes: shards (Citus, Vitess) | See Database last |
Fix / how to use it: write the table above for your system with real thresholds and owners, and revisit it after every load test.
Autoscaling policies: target tracking, step, predictive, scheduled Must-know
In plain words: autoscaling is a thermostat for capacity: pick a metric and a target, and a controller adds or removes capacity to keep the metric near the target. AWS's own words: target tracking "is similar to how a thermostat maintains a target temperature."
Common misunderstanding: "CPU is the metric." CPU is a good default for CPU-bound stateless services (the SRE book: "simply using CPU consumption as the signal for provisioning works well" in most cases), but it is the wrong signal for I/O-bound services, queue workers (scale on queue depth or age), and services limited by connections or memory.
Definition: the policy types, by product:
- Reactive target tracking: keep a metric at a target value (EC2 Auto Scaling
ASGAverageCPUUtilization,ALBRequestCountPerTarget; Kubernetes HPAaverageUtilizationoraverageValue). AWS recommends target tracking over step and simple scaling for proportional metrics. - Step scaling: CloudWatch alarm bands mapped to adjustments ("+2 instances at 70–85%, +4 above 85%"). Useful when the response must be non-linear.
- Simple scaling with cooldown: one adjustment, then wait; AWS: "we recommend that you do not use simple scaling policies and scaling cooldowns."
- Predictive scaling: AWS forecasts from history ("analyzing historical load data to detect daily or weekly patterns") and launches capacity before the forecasted load; best for cyclical traffic and slow-starting apps.
- Scheduled scaling: set min/desired/max at given times (AWS cron recurrence, KEDA
cronscaler, a Kubernetes CronJob that patches the HPAminReplicas). - Metrics: CPU, memory, requests per second per target, latency (careful: it lags and is noisy), queue depth or message age (best for workers), consumer lag (Kafka), connections, custom business metrics (orders in flight).
Target tracking on RPS per pod, target 50, HPA defaults
1 t=0s 6 pods, 300 req/s total = 50 per pod: within 10% tolerance, no change
2 t=15s traffic jumps to 600 req/s: 100 per pod -> ceil(6 x 100/50) = 12
3 t=15s scale-up allowed: max(100% of 6, 4 pods) per 15 s -> 12 pods requested
4 t=45s new pods pass readiness (start + warm-up 25 s); metric back to 50
5 t=60s traffic falls to 300 req/s: recommendation 6, but the 300 s scale-down window holds 12
6 t=360s no recommendation above 6 in the last 5 minutes -> scale to 6Real scenario: an e-commerce API with predictive scaling for the daily curve and target tracking for surprises; a video encoder pool that scales on queue depth with KEDA; a B2B app scheduled to 10 pods at 08:00 local time and 3 pods at 20:00; a Laravel app on EC2 that scales the web ASG on ALBRequestCountPerTarget and the worker ASG on SQS ApproximateNumberOfMessagesVisible.
| Product | Reactive | Step | Predictive | Scheduled |
|---|---|---|---|---|
| AWS EC2 Auto Scaling | Target tracking | Step / simple | Yes (forecast) | Yes (cron) |
| Kubernetes HPA | Resource, Pods, Object, External metrics | Via behavior.policies | No (third party) | No (use KEDA cron or a CronJob) |
| KEDA | Scalers (queue, lag, Prometheus) | Through HPA behavior | No | cron scaler |
| Laravel Horizon | Queue load per supervisor | No | No | No |
Fix / how to use it: pick the metric that rises before users suffer and falls when capacity is added (RPS per pod, queue depth per worker), set the target at the knee of your load test minus headroom (for example 60% CPU, not 85%), and combine predictive or scheduled minimums with reactive tracking.
Cooldowns, stabilization windows and flapping Must-know
In plain words: if the autoscaler reacts to every wiggle, it adds pods, the metric drops, it removes them, the metric rises, and so on. That is flapping. Cooldowns and stabilization windows make it wait before undoing a decision.
Common misunderstanding: "Set the cooldown to zero so we react fast." Fast scale-up is good; fast scale-down is what causes flapping, because a short dip removes capacity the next spike needs, and each new pod pays a cold start again.
Definition: the Kubernetes docs: replica counts that keep "fluctuating frequently due to the dynamic nature of the metrics evaluated. This is sometimes referred to as thrashing, or flapping." Remedies:
- HPA tolerance: ignore ratios within 10% of 1.0 by default (
--horizontal-pod-autoscaler-tolerance, per-HPAtolerancefield in recent versions). - HPA stabilization window: the HPA uses the highest recommendation within the window before scaling down; default
scaleDown.stabilizationWindowSecondsis 300;scaleUphas none by default. - HPA scaling policies: cap the rate, for example "at most 10% of pods per minute down".
- EC2 Auto Scaling: default cooldown 300 s for simple scaling; instance warmup for target tracking and step policies.
- KEDA:
cooldownPeriod(default 300 s) applies to scaling back to zero; 1-to-N is handled by the HPA. - Horizon:
balanceCooldown(seconds between adjustments) andbalanceMaxShift(processes per adjustment). - Hysteresis: different thresholds for up and down (scale up at 70%, down at 40%).
Same load, alternating 600 and 300 req/s every 15 s (from scalecalc, target 50/pod)
1 no window : [12 6 12 6 12 6 ...] 19 changes in 20 steps
2 5 min : [12 12 12 12 12 ...] 0 changes
every "6" above is a scale-in of 6 pods that the next 15 s step adds back, with cold startsReal scenario: a CPU-scaled service whose GC pauses spike CPU every minute; a queue worker scaled on instantaneous depth that empties and refills in bursts; a cron-driven traffic pattern (every hour on the hour) that confuses a short-window autoscaler; a Kafka consumer group that rebalances on every scale event, so flapping also stops consumption.
Fix / how to use it: keep scale-up fast, make scale-down slow (5–10 minutes window, small step size), smooth the metric (rate over 1–2 minutes), and alert on the number of scaling events per hour.
Kubernetes autoscalers: HPA, VPA, KEDA, Cluster Autoscaler, Karpenter Must-know
In plain words: Kubernetes has separate controllers for "how many pods", "how big each pod is" and "how many machines". They work in a chain, and each one can wait for the next.
Common misunderstanding: "The HPA added pods, so capacity is there." If no node has room, the new pods are Pending until Cluster Autoscaler or Karpenter adds a node, which takes minutes. During that time the HPA has done its job and users still see overload.
Definition:
- HorizontalPodAutoscaler (HPA): a control loop (default period 15 s) that computes
desiredReplicas = ceil[currentReplicas × (currentMetricValue / desiredMetricValue)]per metric and takes the maximum; it ignores not-yet-ready pods' CPU during--horizontal-pod-autoscaler-cpu-initialization-period(default 5 minutes) and treats pods as not ready for--horizontal-pod-autoscaler-initial-readiness-delay(default 30 s). Resource utilisation requires containerresources.requests. Scaling to and from zero withminReplicas: 0is beta since Kubernetes v1.37 (HPAScaleToZerofeature gate, enabled by default) and only for object or external metrics. - VerticalPodAutoscaler (VPA): a CRD installed separately; recommends and applies container requests.
updateMode:Off(recommend only),Initial(only at pod creation),Recreate(evict to apply),InPlaceOrRecreate,InPlace;Autois deprecated since VPA 1.4.0 and is an alias forRecreate. Its known limitations: VPA "should not be used with the Horizontal Pod Autoscaler (HPA) on the same resource metric (CPU or memory)"; it can be combined with an HPA on custom or external metrics. - KEDA: creates and drives an HPA from event sources (Redis lists, Kafka lag, SQS, RabbitMQ, Prometheus, cron and more) and owns the 0↔1 step;
pollingIntervaldefault 30 s,cooldownPerioddefault 300 s,minReplicaCountdefault 0,maxReplicaCountdefault 100;activationThreshold-style values decide when a scaler is active ("Activation only occurs when this value is greater than the set value"). - Cluster Autoscaler: "The main purpose of Cluster Autoscaler is to get pending pods a place to run"; removes nodes that are unneeded for
--scale-down-unneeded-time(default 10 minutes) and below--scale-down-utilization-threshold(default 0.5), not within--scale-down-delay-after-add(default 10 minutes) of a scale-up. It respects PodDisruptionBudgets. - Karpenter: provisions nodes directly from pending pods' requirements and consolidates under-used nodes; the Kubernetes docs list it and Cluster Autoscaler as the two node autoscalers sponsored by SIG Autoscaling.
A spike that outruns the nodes
1 t=0s HPA: 10 -> 20 pods
2 t=1s 10 new pods Pending: "0/8 nodes are available: Insufficient cpu"
3 t=10s Cluster Autoscaler: TriggeredScaleUp, node group +3
4 t=2m30s nodes Ready; image pull 20 s; app start + warm-up 25 s
5 t=3m20s 20 pods Ready; users saw overload for ~3 minutes
fix: overprovisioning with low-priority pause pods, warm pools, or a higher minReplicas# HPA on RPS per pod (custom metric via Prometheus Adapter) with explicit behavior
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: api }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: api }
minReplicas: 3 # N+1 at the quietest hour, never 1
maxReplicas: 40 # below the USL peak and the DB connection budget
metrics:
- type: Pods
pods:
metric: { name: http_requests_per_second }
target: { type: AverageValue, averageValue: "50" }
- type: Resource
resource:
name: cpu
target: { type: Utilization, averageUtilization: 60 }
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies: [ { type: Percent, value: 100, periodSeconds: 15 } ]
scaleDown:
stabilizationWindowSeconds: 300
policies: [ { type: Percent, value: 10, periodSeconds: 60 } ]# KEDA: queue workers on a Redis list (Laravel's redis queue uses lists), scale to zero
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: emails-worker }
spec:
scaleTargetRef: { name: emails-worker }
pollingInterval: 15
cooldownPeriod: 300
minReplicaCount: 0
maxReplicaCount: 30
triggers:
- type: redis
metadata:
address: redis.default.svc:6379
listName: queues:emails
listLength: "100" # target jobs per replica
activationListLength: "5" # stay at zero below 5 waiting jobsReal scenario: an API with HPA on RPS plus CPU as a safety net; workers on KEDA with Kafka lag; a batch namespace with VPA in Off mode to right-size requests from recommendations; a GPU inference service scaled to zero overnight with KEDA.
Fix / how to use it: set resources.requests on every container (HPA utilisation and the scheduler both depend on them), give HPAs explicit behavior, keep spare node capacity for the first scale-up step, and never point a VPA and an HPA at the same CPU metric.
Warm pools, scale to zero and cold starts Important
In plain words: a new replica is not useful the moment it is created: the machine boots, the image downloads, the runtime starts, caches are empty, connections are not open. That delay is the cold start. Warm pools keep pre-initialised capacity ready; scale to zero saves money by paying the cold start on the first request.
Common misunderstanding: "Scale to zero is free capacity." It is free idle capacity. The first request after idle waits for the whole start path, and if your timeout is shorter than that, the first users get errors.
Definition: cold start = time from "capacity requested" to "replica serving at full speed". Warm pool (EC2 Auto Scaling): "a pool of pre-initialized EC2 instances that sits alongside an Auto Scaling group", kept Stopped, Running or Hibernated (stopped instances cost only their volumes). Scale to zero: KEDA minReplicaCount: 0, HPA minReplicas: 0 (beta, external/object metrics), AWS Lambda and Cloud Run by design. Provisioned concurrency (Lambda): pre-initialised execution environments to avoid cold starts. Kubernetes equivalents: overprovisioning with low-priority pause pods (Cluster Autoscaler FAQ), image pre-pulling, and a startupProbe so slow starts are not killed by liveness.
Cold start budget of one Kubernetes pod (labelled estimate; measure your own)
1 node needed? 0 s (room) or 60-180 s (Cluster Autoscaler + node boot)
2 image pull 0 s (cached) or 5-60 s
3 process start Go 0.1 s; PHP-FPM 1 s; Octane boot 1-3 s; JVM 5-30 s
4 readiness: warm caches, open pools, JIT/opcache warm-up: 1-30 s
5 traffic arrives; first requests slower until caches fillReal scenario: a JVM service that needs 40 s before it is useful, so the ASG uses a warm pool and predictive scaling; a Lambda API with provisioned concurrency at business hours only; an internal tool on Cloud Run or KEDA at zero overnight; an ML model server whose image is 8 GB, so nodes pre-pull it.
Fix / how to use it: measure the cold start, then pick: keep min above zero for latency-critical paths, warm pools or overprovisioning for slow nodes, scale to zero only for queue consumers and tools where the first request may wait.
Readiness probes and graceful shutdown for autoscaled replicas Must-know
In plain words: an autoscaler adds and removes replicas all day. Each new replica must say "not ready" until it can serve, and each removed replica must stop taking new requests, finish the ones it has, and only then exit.
Common misunderstanding: "Kubernetes removes the pod from the Service before it sends SIGTERM." Both happen in parallel. Endpoint removal must travel to kube-proxy on every node, to Ingress controllers and to cloud load balancers; if the process stops listening immediately on SIGTERM, requests still in flight to it fail with 502 or connection refused.
Definition: readiness probe: "Readiness probes determine when a container is ready to accept traffic"; failing it removes the pod from Service endpoints without restarting it. Liveness probe: restarts a wedged container; it must not check dependencies, or one Redis outage restarts every pod. Startup probe: holds off liveness and readiness until a slow start finishes. Graceful shutdown: on SIGTERM, keep serving for a short drain delay (or do it in a preStop hook), then stop accepting, finish in-flight work, close pools, exit. Go: http.Server.Shutdown "works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down", so always pass a context with a timeout; it does not wait for hijacked connections such as WebSockets (RegisterOnShutdown). Kubernetes: "A Pod is granted a term to terminate gracefully, which defaults to 30 seconds", then KILL. AWS ALB: deregistration delay (300 s by default) drains a target.
Scale-in of one pod, done right (Go service from this page)
1 t=0s pod marked Terminating; preStop sleep / app sets readiness=503
2 t=0-3s EndpointSlice updated; kube-proxy, Ingress and ALB stop sending new requests
3 t=10s drain delay over; SIGTERM handling calls srv.Shutdown(ctx 15 s)
4 t=10-12s listener closed, idle keep-alive connections closed, 3 in-flight requests finish
5 t=12s process exits 0; terminationGracePeriodSeconds (30 s) never reachedReal scenario: 502 spikes on every deploy or scale-in that disappear after adding a 10 s preStop sleep; a queue worker killed mid-job by SIGKILL because its job takes 90 s and the grace period is 30 s (raise terminationGracePeriodSeconds or make jobs resumable); a liveness probe that checks PostgreSQL and restarts the entire fleet during a database failover; Laravel Octane under Supervisor that needs octane:stop-style graceful handling.
# Deployment fragment for an autoscaled replica
spec:
template:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: api
image: registry.example.com/api:1.42.0
resources: { requests: { cpu: "500m", memory: "256Mi" }, limits: { memory: "512Mi" } }
startupProbe: { httpGet: { path: /livez, port: 8080 }, periodSeconds: 2, failureThreshold: 30 }
livenessProbe: { httpGet: { path: /livez, port: 8080 }, periodSeconds: 10, failureThreshold: 3 }
readinessProbe: { httpGet: { path: /readyz, port: 8080 }, periodSeconds: 2, failureThreshold: 1 }
lifecycle:
preStop: { sleep: { seconds: 5 } } # or exec a drain command; app adds its own delay tooFix / how to use it: separate liveness from readiness, fail readiness first, delay, then shut down with a deadline shorter than the grace period. The Go stateless.Run and the Laravel app:drain command below implement this.
Capacity headroom and N+1 / N+2 Must-know
In plain words: never run at 100%. Keep enough spare capacity to survive losing a machine (or a zone) and the time it takes the autoscaler to react.
Common misunderstanding: "N+1 means one extra pod." It means you can lose the largest single unit of failure and still serve peak. If that unit is an availability zone holding a third of your pods, N+1 means surviving the loss of a whole zone.
Definition: headroom = capacity above expected peak, expressed as a percentage or a number of units. N+1 redundancy: peak is served by N units with one unit lost. N+2 (Google SRE): "Provision to handle a simultaneous planned and unplanned outage ... this results in an 'N + 2' configuration, where peak traffic can be handled by N instances (possibly in degraded mode) while the largest 2 instances are unavailable." Autoscaled tiers also need reaction headroom: the spare capacity that carries traffic during the minutes before new replicas are ready.
N+2 sizing (Google SRE, Addressing Cascading Failures, worked example)
1 breaking point per cluster (from load test): 5,000 QPS
2 peak load: 19,000 QPS -> N = ceil(19,000 / 5,000) = 4 clusters
3 N + 2 = 6 clusters; normal utilisation at peak = 19,000 / 30,000 = 63%
Same arithmetic for pods across 3 zones: survive one zone = run at most ~66% at peakReal scenario: a three-zone deployment with minReplicas: 6 so losing a zone leaves 4; a primary with a synchronous standby (N+1 for the database); a planned maintenance window that coincides with a failure (why N+2 exists); a CPU target of 60% that leaves room for both a zone loss and the scale-up lag.
Fix / how to use it: compute from the load test's breaking point, not from averages; spread replicas with topologySpreadConstraints across zones; set autoscaler targets so that target × (zones / (zones − 1)) stays below the knee.
Cost: right-sizing, spot, reserved, serverless Important
In plain words: scaling has a bill. Pay on-demand for the spiky part, commit to discounts for the steady part, use interruptible capacity for work that can be retried, and stop paying for requests you set but never use.
Common misunderstanding: "Autoscaling always saves money." It saves money only if the baseline is right-sized and scale-in actually happens. Oversized requests, min set to peak, and flapping (paying for cold starts repeatedly) cancel the savings.
Definition:
- Right-sizing: set instance types and pod
requestsfrom measured usage (VPA inOffmode gives recommendations; AWS Compute Optimizer does it for instances). - Spot instances: "spare EC2 capacity that is available for less than the On-Demand price"; EC2 sends "a two-minute warning" before interruption. Good for stateless replicas and retryable workers spread across instance types.
- Reserved Instances / Savings Plans: AWS: Standard RIs "provide the most significant discount (up to 72% off On-Demand)", Convertible "up to 66%"; for the steady baseline you will run for one or three years.
- Serverless pricing: AWS Lambda event functions "are priced per request and execution duration" (GB-seconds); free tier "one million requests and 400,000 GB-seconds per month" on the page read for this chapter. Cheap at low or spiky volume; at steady high volume, containers are usually cheaper (estimate; model your own numbers).
Blended capacity plan for an API tier (labelled estimate)
1 steady baseline 10 pods all day -> reserved / savings plan nodes
2 daily peak +15 pods for 8 h -> on-demand, autoscaled
3 batch and retryable workers -> spot across 3+ instance types, handle the 2-minute notice
4 rare internal tools -> scale to zero (KEDA) or serverlessReal scenario: a cluster where pods request 2 vCPU and use 0.3 (right-sizing cuts nodes by half); a CI fleet on spot; a nightly ETL on spot with checkpointing; a startup on Lambda until monthly invocations make Fargate or EKS cheaper.
Fix / how to use it: review requests vs usage monthly, keep a cost-per-request metric next to latency, and make every spot workload handle the interruption notice like a SIGTERM.
Load testing and finding the knee Must-know
In plain words: load testing increases traffic until something breaks, so you know the limit before your users find it. The knee is the point where latency starts climbing much faster than throughput.
Common misunderstanding: "Our load test of 1,000 virtual users passed." A closed-model test (fixed users that wait for each response) slows down with the system and hides overload; this is coordinated omission (Latency Budgets). Use an open model (fixed arrival rate) to find the real knee.
Definition: test types (k6 docs): "Stress tests assess how a system performs at its limits"; "Soak tests assess the reliability and performance of your system over extended periods"; "Spike tests validate the behavior and survival of your system in cases of sudden, short, and massive increases in activity"; "Breakpoint tests gradually increase load to identify the capacity limits of the system." Tools: k6 (ramping-arrival-rate is "an open-model executor, meaning iterations start independently of system response"), wrk ("Modern HTTP benchmarking tool"; closed model, --latency for the distribution), vegeta ("drill HTTP services with a constant request rate", and "Avoids nasty Coordinated Omission"). Report throughput (requests per second served), latency percentiles, error rate and saturation (CPU, connections, queue length) together.
Breakpoint test, one 2-vCPU pod (open model, labelled sample shape)
1 rate p50 p99 errors CPU
2 500/s 4 ms 12 ms 0% 35%
3 1,000/s 5 ms 18 ms 0% 62%
4 1,400/s 7 ms 45 ms 0% 81% <- knee: p99 x2.5 for +40% load
5 1,600/s 30 ms 900 ms 0.4% 97% <- saturation
6 1,800/s 2 s timeout 12% 100% <- breaking point
autoscaler target: ~60-65% CPU (about 1,000-1,100/s per pod); breaking point for N+2: 1,600/sReal scenario: the SRE book's advice that load testing "reveals where the breaking point is, knowledge that's fundamental to the capacity planning process"; a USL fit from tests at 1, 2, 4, 8 and 16 pods; a soak test that finds a memory leak in Octane workers after 3 hours; a spike test that shows the HPA reacting in 15 s but nodes arriving after 3 minutes.
Fix / how to use it: run breakpoint tests per tier with production-like data, record the knee and the breaking point, fit the USL to multi-node runs, and re-run after every major change. Scripts are in the Lab.
Laravel: Octane workers and Horizon balancing Important
In plain words: Octane keeps your Laravel app in memory and serves many requests per worker, so each pod does more work (scaling up the process); Horizon moves queue workers between queues on one machine according to load (autoscaling inside a host).
Common misunderstanding: "Octane is just faster PHP-FPM." It changes the state model: the application boots once per worker and stays in memory, so static properties, singletons that capture the request, and growing arrays leak between requests. Octane is a statelessness test you can fail.
Definition: Octane runs on FrankenPHP, Swoole/Open Swoole or RoadRunner; "By default, Octane will start an application request worker for each CPU core"; "Octane gracefully restarts any worker once it has handled 500 requests" (--max-requests); octane:reload gracefully restarts workers after a deploy. Its docs warn against injecting the container, request or config into singletons and show that "adding data to a statically maintained array will result in a memory leak". The container's scoped() bindings are "flushed whenever the Laravel application starts a new 'lifecycle', such as when a Laravel Octane worker processes a new request". Horizon offers three balancing strategies, auto, simple and false; with auto, autoScalingStrategy is time ("total estimated amount of time it will take to clear the queue"), size or log; minProcesses per queue (at least 1), maxProcesses in total, and balanceMaxShift/balanceCooldown set the speed ("a maximum of one new process will be created or destroyed every three seconds" in the docs' example). horizon:terminate finishes current jobs before stopping.
One Laravel pod under Octane + one Horizon host
1 pod: octane:start --workers=4 --max-requests=500 (4 vCPU)
2 request 1 on worker 2: scoped PriceCalculator built, flushed after the request
3 worker 2 reaches 500 requests -> graceful restart (bounds slow leaks)
4 Horizon: notifications queue 1,000 jobs, default queue 0 -> auto moves processes, +2 every 3 s
5 queue still growing at maxProcesses -> KEDA / ASG adds Horizon hosts (horizontal)Real scenario: an API moved from PHP-FPM to Octane that needed half the pods but leaked memory through a static cache; a Horizon supervisor with maxProcesses 24 whose spikes on the notifications queue starved payments until minProcesses and separate supervisors were set; Kubernetes using Laravel's /up route as liveness and a custom /ready route as readiness.
Fix / how to use it: run Octane only after removing static and request-capturing state; size --workers to the pod's vCPU; set --max-requests; split critical queues into their own supervisor with a guaranteed minProcesses; scale Horizon hosts horizontally on queue depth. Code below.
Scaling the organisation: Conway's law Good to know
In plain words: the system's structure tends to copy the team structure. If you want independently scalable parts, you need teams that can change and deploy them independently.
Common misunderstanding: "Split into microservices and each team will scale on its own." Services that must be released together, share a database, or need cross-team meetings for every change scale worse than the monolith they replaced (the distributed monolith).
Definition: Conway (1968): "organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations." The inverse manoeuvre shapes teams to get the architecture you want. Boundaries are covered in Service Boundaries.
Team growth vs service split
1 8 engineers, 1 modular monolith, 1 deploy pipeline: fine
2 40 engineers in 6 teams on one deploy pipeline: merge queues, release trains
3 split along domain lines (orders, catalogue, payments) with owned data
4 each service gets its own scaling policy; payments scales up, catalogue scales out behind a CDNReal scenario: a platform team owning autoscaling defaults for all services; a catalogue team that owns its cache and CDN rules; a payments team that keeps one strongly consistent database and refuses sharding.
Fix / how to use it: split services only where a team owns the code, the data and the scaling decision end to end.
Scale the database last Important
In plain words: the database is the hardest tier to scale out, so make every cheaper move first: fix queries, add indexes, cache, pool connections, scale up, add replicas, partition. Shard only when those are exhausted.
Common misunderstanding: "We will need sharding eventually, so let us start sharded." Sharding early fixes the shard key before you know the access patterns, makes every cross-tenant query and every migration harder, and you pay for it on day one.
Definition: the scale ladder (owned by Storage & Data Scaling): query and index fixes → connection pooling (PgBouncer, RDS Proxy) → caching → vertical scaling → read replicas → table partitioning → functional split (one database per service) → sharding (Citus, Vitess, application-level).
Why the app tier scales and the DB does not
1 API pods 3 -> 30 (autoscaled), each with a pool of 20 -> 600 PostgreSQL connections
2 PostgreSQL max_connections = 500 -> "FATAL: sorry, too many clients already"
3 fix order: PgBouncer transaction pooling; fewer, larger pods (diagonal); pool 10
4 then: bigger primary; replicas for reads; only then think about shardsReal scenario: the classic Black Friday outage where autoscaling the API exhausted database connections; a 2 TB table that needed partitioning, not sharding; a SaaS that sharded by tenant after the biggest tenant alone needed its own primary.
Fix / how to use it: include the database in every load test, set autoscaler maximums from the connection budget (max_connections minus admin reserve, divided by pool size), and add PgBouncer before adding pods.
Mechanics
Amdahl and USL arithmetic
| Quantity | Formula | Example (σ = 0.03, κ = 0.0005) |
|---|---|---|
| Amdahl speedup | S(N) = N / (1 + σ(N − 1)) | S(32) = 16.6 |
| Amdahl ceiling | 1/σ | 33.3x |
| USL capacity | C(N) = N / (1 + σ(N − 1) + κN(N − 1)) | C(32) = 13.2 |
| USL peak | N* = √((1 − σ)/κ) | 44.0 |
| Efficiency | C(N)/N | 41% at N = 32 |
| Fit | y = N/C − 1 = (σ + κ)x + κx², x = N − 1 | Least squares through the origin |
| Nodes needed for target X | Smallest N with X(1)·C(N) ≥ X | 10,000 req/s needs N = 16 |
Rules of thumb (estimates): σ of 0.01–0.05 is common for well-partitioned web tiers; κ above 0.001 means a peak below about 30 nodes, which you will hit in production.
Kubernetes HPA algorithm and knobs
| Knob | Default | Effect |
|---|---|---|
--horizontal-pod-autoscaler-sync-period | 15 s | Loop period |
--horizontal-pod-autoscaler-tolerance / spec.behavior.*.tolerance | 0.1 | Ignore ratio within ±10% |
--horizontal-pod-autoscaler-downscale-stabilization / scaleDown.stabilizationWindowSeconds | 300 s | Highest recommendation in window wins |
scaleUp.stabilizationWindowSeconds | 0 | Scale up immediately |
Default scaleUp policies | 100% or 4 pods per 15 s, selectPolicy: Max | Maximum growth rate |
Default scaleDown policy | 100% per 15 s (after the window) | Can drop to minReplicas |
--horizontal-pod-autoscaler-cpu-initialization-period | 5 min | Ignore CPU of pods that just started |
--horizontal-pod-autoscaler-initial-readiness-delay | 30 s | Treat recently started unready pods as not yet ready |
minReplicas: 0 | Beta since v1.37 (HPAScaleToZero) | Only with object/external metrics |
| Multiple metrics | Highest desired count wins | Scale-in only if all agree |
The formula: desiredReplicas = ceil[currentReplicas × (currentMetricValue / desiredMetricValue)]. A worked example from the docs: current 200m, target 100m doubles the replicas; 50m halves them. Missing metrics and not-ready pods are set aside and then counted conservatively (0% when scaling up, 100% when scaling down) so the HPA does not overreact.
KEDA, Cluster Autoscaler and EC2 Auto Scaling knobs
| Product | Knob | Default | Meaning |
|---|---|---|---|
| KEDA | pollingInterval | 30 s | How often triggers are checked |
| KEDA | cooldownPeriod | 300 s | Wait before scaling back to 0 (only 1→0) |
| KEDA | minReplicaCount / maxReplicaCount | 0 / 100 | Bounds |
| KEDA | idleReplicaCount | ignored | Only 0 is supported |
| KEDA | activation* (for example activationListLength) | 0 | Threshold for 0↔1 |
| Cluster Autoscaler | --scale-down-unneeded-time | 10 min | Node must be unneeded this long |
| Cluster Autoscaler | --scale-down-delay-after-add | 10 min | No scale-down right after scale-up |
| Cluster Autoscaler | --scale-down-utilization-threshold | 0.5 | Requests / allocatable below which a node may go |
| Cluster Autoscaler | --scale-down-delay-after-failure | 3 min | Back-off after a failed scale-down |
| Cluster Autoscaler | --new-pod-scale-up-delay | (unset) | Ignore very young pending pods |
| EC2 Auto Scaling | Default cooldown (simple scaling) | 300 s | Pause after a simple-scaling activity |
| EC2 Auto Scaling | Instance warmup | Group default instance warmup | New instances excluded from metrics until warm |
| EC2 Auto Scaling | Warm pool state | Stopped / Running / Hibernated | Pre-initialised instances |
| AWS ALB | Deregistration delay | 300 s | Draining time for a deregistering target |
| Kubernetes Pod | terminationGracePeriodSeconds | 30 s | SIGTERM to SIGKILL |
| Laravel Octane | --workers / --max-requests | 1 per CPU core / 500 | Workers per pod, restart to bound leaks |
| Laravel Horizon | balanceMaxShift / balanceCooldown | docs example: 1 / 3 s | Speed of rebalancing |
Shutdown and capacity arithmetic
| Rule | Formula | Example |
|---|---|---|
| Grace budget | drain delay + shutdown timeout + margin ≤ terminationGracePeriodSeconds | 10 + 15 + 5 = 30 s |
| Connection budget | maxReplicas × pool size ≤ max_connections − reserve | 40 × 10 ≤ 500 − 50 |
| Zone headroom | target ≤ knee × (zones − 1)/zones | 3 zones, knee 90% → target ≤ 60% |
| N+2 | units = ceil(peak / per-unit breaking point) + 2 | ceil(19,000 / 5,000) + 2 = 6 |
| Little's law for workers | workers ≥ arrival rate × job time | 50 jobs/s × 0.4 s = 20 workers |
| Queue drain time | backlog / (consumers × rate − arrival rate) | 200,000 / (3,000 − 2,000) = 200 s |
Events and messages you will see
| Where | Message (verbatim) | Meaning | Action |
|---|---|---|---|
| Scheduler event | FailedScheduling ... Insufficient cpu | No node has room for the new pod | Wait for Cluster Autoscaler or overprovision |
| Cluster Autoscaler event | TriggeredScaleUp / pod triggered scale-up | A node group is growing | Expect minutes |
| Cluster Autoscaler event | NotTriggerScaleUp / pod didn't trigger scale-up (it wouldn't fit if a new node is added) | Pod is larger than any node template | Fix requests or node groups |
| HPA condition | ScalingActive false | HPA is not scaling (for example target at 0 with minReplicas > 0) | Check metrics and targets |
Go net/http | http: Server closed (http.ErrServerClosed) | Normal result of Shutdown | Treat as success |
| PostgreSQL | FATAL: sorry, too many clients already | Replicas × pool exceeded max_connections | PgBouncer, smaller pools, lower maxReplicas |
| Load balancer | HTTP 502 / 503 during scale-in | Requests routed to a terminating pod | Readiness first, drain delay |
| Laravel | /up returns 500 | Boot failed or a DiagnosingHealth listener threw | Look at the exception, not the probe |
Go
The module academy/scaling-strategies uses the standard library plus github.com/redis/go-redis/v9 (pinned to v9.7.3 so the module stays on go 1.24; newer v9 releases require a newer Go). Every library package has tests.
Before
A stateful process: carts in a map, uploads on local disk, identity from a header, no readiness, no SIGTERM handling. It works on one machine and breaks with a second replica, an autoscaler or a deploy.
// Command before is a stateful web process: it works on one machine and
// breaks the moment a second replica or an autoscaler appears.
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"os"
"path/filepath"
"sync"
)
// carts lives in this process's memory. A second replica has its own map,
// so a user routed there sees an empty cart (the reason teams reach for
// sticky sessions).
var (
mu sync.Mutex
carts = map[string][]string{}
)
func main() {
http.HandleFunc("POST /cart/items", func(w http.ResponseWriter, r *http.Request) {
user := r.Header.Get("X-User") // identity trusted from a header, for brevity
mu.Lock()
carts[user] = append(carts[user], r.FormValue("sku"))
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
})
http.HandleFunc("GET /cart", func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
_ = json.NewEncoder(w).Encode(carts[r.Header.Get("X-User")])
})
// Uploads land on the local disk: lost when the instance is replaced,
// invisible to every other replica.
http.HandleFunc("POST /avatar", func(w http.ResponseWriter, r *http.Request) {
f, err := os.Create(filepath.Join("uploads", filepath.Base(r.Header.Get("X-User"))))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
_, _ = io.Copy(f, r.Body)
})
// No readiness endpoint, no SIGTERM handling: a scale-in or a rolling
// deploy cuts in-flight requests and drops every cart in memory.
log.Fatal(http.ListenAndServe(":8080", nil))
}After
Externalised session state. The Store interface forces atomic operations in the backing service (Redis RPUSH + EXPIRE in one MULTI), so two replicas appending to the same cart cannot lose an item. MemoryStore is the shared test double.
// Package session externalises per-user state so that any replica can
// serve any request.
package session
import (
"context"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
// Store is the only place request state may live. Append must be atomic in
// the backing service: two replicas adding to the same cart at the same
// moment must not lose an item (a read-modify-write in the app would).
type Store interface {
Append(ctx context.Context, key, item string, ttl time.Duration) error
List(ctx context.Context, key string) ([]string, error)
Ping(ctx context.Context) error
}
// RedisStore keeps carts as Redis lists: RPUSH is atomic and EXPIRE gives
// sessions a time-to-live, exactly what 12-factor suggests for session state.
type RedisStore struct{ C *redis.Client }
// NewRedisStore builds a client; it does not dial until the first command.
func NewRedisStore(addr string) *RedisStore {
return &RedisStore{C: redis.NewClient(&redis.Options{
Addr: addr,
DialTimeout: 500 * time.Millisecond,
ReadTimeout: 200 * time.Millisecond,
WriteTimeout: 200 * time.Millisecond,
PoolSize: 20, // per replica: total connections = replicas x PoolSize
})}
}
// Append pushes one item and refreshes the TTL in one MULTI/EXEC.
func (s *RedisStore) Append(ctx context.Context, key, item string, ttl time.Duration) error {
_, err := s.C.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.RPush(ctx, key, item)
p.Expire(ctx, key, ttl)
return nil
})
return err
}
// List returns the whole cart.
func (s *RedisStore) List(ctx context.Context, key string) ([]string, error) {
return s.C.LRange(ctx, key, 0, -1).Result()
}
// Ping is used by the readiness probe.
func (s *RedisStore) Ping(ctx context.Context) error { return s.C.Ping(ctx).Err() }
// MemoryStore is a test double that behaves like the shared service: one
// instance is shared by several App replicas inside a test.
type MemoryStore struct {
mu sync.Mutex
data map[string][]string
exp map[string]time.Time
Down bool // simulate the backing service being unreachable
Now func() time.Time
}
// NewMemoryStore returns an empty store.
func NewMemoryStore() *MemoryStore {
return &MemoryStore{data: map[string][]string{}, exp: map[string]time.Time{}, Now: time.Now}
}
// Append implements Store.
func (m *MemoryStore) Append(_ context.Context, key, item string, ttl time.Duration) error {
m.mu.Lock()
defer m.mu.Unlock()
m.expire(key)
m.data[key] = append(m.data[key], item)
m.exp[key] = m.Now().Add(ttl)
return nil
}
// List implements Store.
func (m *MemoryStore) List(_ context.Context, key string) ([]string, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.expire(key)
return append([]string(nil), m.data[key]...), nil
}
// Ping implements Store.
func (m *MemoryStore) Ping(context.Context) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.Down {
return context.DeadlineExceeded
}
return nil
}
func (m *MemoryStore) expire(key string) {
if t, ok := m.exp[key]; ok && m.Now().After(t) {
delete(m.data, key)
delete(m.exp, key)
}
}A stateless replica with readiness and a bounded drain. /livez never checks dependencies; /readyz fails when the store is unreachable or the replica is draining. Run serves until SIGTERM, fails readiness, keeps serving for Drain.Delay, then calls Shutdown with Drain.Timeout.
// Package stateless is a web process that can be cloned, autoscaled and
// killed at any moment: no state in memory, readiness that turns off before
// shutdown, and a bounded graceful drain.
package stateless
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"sync/atomic"
"time"
"academy/scaling-strategies/session"
)
// SessionTTL is how long an idle cart lives in the shared store.
const SessionTTL = 30 * time.Minute
// App holds only immutable configuration and handles to backing services.
type App struct {
Store session.Store
Replica string // reported in a header, to show any replica can answer
draining atomic.Bool
}
// Handler wires the routes (Go 1.22+ method patterns).
func (a *App) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /cart/items", a.addItem)
mux.HandleFunc("GET /cart", a.getCart)
mux.HandleFunc("GET /livez", func(w http.ResponseWriter, _ *http.Request) {
// Liveness: "is this process wedged?" Never check dependencies here,
// or a Redis blip restarts every replica at once.
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("GET /readyz", a.ready)
return mux
}
// StartDraining makes /readyz fail so the load balancer and Kubernetes
// endpoints stop routing new requests to this replica.
func (a *App) StartDraining() { a.draining.Store(true) }
func (a *App) ready(w http.ResponseWriter, r *http.Request) {
if a.draining.Load() {
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 300*time.Millisecond)
defer cancel()
if err := a.Store.Ping(ctx); err != nil {
http.Error(w, "session store unreachable", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}
func (a *App) addItem(w http.ResponseWriter, r *http.Request) {
sid := sessionID(w, r)
sku := r.FormValue("sku")
if sku == "" {
http.Error(w, "sku required", http.StatusUnprocessableEntity)
return
}
if err := a.Store.Append(r.Context(), "cart:"+sid, sku, SessionTTL); err != nil {
http.Error(w, "store unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("X-Replica", a.Replica)
w.WriteHeader(http.StatusNoContent)
}
func (a *App) getCart(w http.ResponseWriter, r *http.Request) {
sid := sessionID(w, r)
items, err := a.Store.List(r.Context(), "cart:"+sid)
if err != nil {
http.Error(w, "store unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("X-Replica", a.Replica)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(items)
}
// sessionID reads the opaque cookie or issues a new one. The cookie holds
// only a random id; the state itself lives in the shared store.
func sessionID(w http.ResponseWriter, r *http.Request) string {
if c, err := r.Cookie("sid"); err == nil && len(c.Value) == 32 {
return c.Value
}
b := make([]byte, 16)
_, _ = rand.Read(b)
id := hex.EncodeToString(b)
http.SetCookie(w, &http.Cookie{
Name: "sid", Value: id, Path: "/", HttpOnly: true,
Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode,
MaxAge: int(SessionTTL.Seconds()),
})
return id
}
// Drain describes the shutdown sequence of one replica.
type Drain struct {
// Delay keeps serving after readiness fails, long enough for the
// endpoint removal to reach every load balancer (Kubernetes endpoints,
// kube-proxy, an AWS ALB target group). Typically 5 to 15 s.
Delay time.Duration
// Timeout bounds http.Server.Shutdown. Delay + Timeout must stay below
// the pod's terminationGracePeriodSeconds (default 30 s) or SIGKILL wins.
Timeout time.Duration
}
// Run serves on ln until ctx is cancelled (SIGTERM), then fails readiness,
// waits Drain.Delay, and calls Shutdown, which closes listeners and idle
// connections and waits for in-flight requests.
func Run(ctx context.Context, srv *http.Server, ln net.Listener, a *App, d Drain) error {
errCh := make(chan error, 1)
go func() { errCh <- srv.Serve(ln) }()
select {
case err := <-errCh:
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
a.StartDraining()
select {
case <-time.After(d.Delay):
case err := <-errCh:
return fmt.Errorf("serve during drain: %w", err)
}
sctx, cancel := context.WithTimeout(context.Background(), d.Timeout)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
if err := <-errCh; !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("serve: %w", err)
}
return nil
}The tests prove the three properties an autoscaler relies on: any replica serves any session, readiness reflects draining and dependencies while liveness stays green, and an in-flight request survives SIGTERM.
package stateless
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"academy/scaling-strategies/session"
)
// Two replicas, one shared store: a request may land on either replica and
// the cart is still there. This is what makes round robin (no affinity) and
// autoscaling safe.
func TestAnyReplicaServesAnySession(t *testing.T) {
store := session.NewMemoryStore()
a := httptest.NewServer((&App{Store: store, Replica: "a"}).Handler())
defer a.Close()
b := httptest.NewServer((&App{Store: store, Replica: "b"}).Handler())
defer b.Close()
jar, _ := cookiejar.New(nil)
c := &http.Client{Jar: jar}
// The cookie is issued by replica a; copy it to b's URL as a browser
// would for the same site behind one load balancer.
resp, err := c.PostForm(a.URL+"/cart/items", url.Values{"sku": {"book-42"}})
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
ua, _ := url.Parse(a.URL)
ub, _ := url.Parse(b.URL)
jar.SetCookies(ub, jar.Cookies(ua))
resp, err = c.PostForm(b.URL+"/cart/items", url.Values{"sku": {"pen-7"}})
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
resp, err = c.Get(a.URL + "/cart")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var items []string
if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
t.Fatal(err)
}
if strings.Join(items, ",") != "book-42,pen-7" {
t.Fatalf("items = %v, want both items regardless of replica", items)
}
}
func TestReadinessFailsWhenStoreDownOrDraining(t *testing.T) {
store := session.NewMemoryStore()
app := &App{Store: store}
srv := httptest.NewServer(app.Handler())
defer srv.Close()
check := func(want int) {
t.Helper()
resp, err := http.Get(srv.URL + "/readyz")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != want {
t.Fatalf("readyz = %d, want %d", resp.StatusCode, want)
}
}
check(http.StatusOK)
store.Down = true
check(http.StatusServiceUnavailable)
// Liveness must stay green while a dependency is down.
resp, _ := http.Get(srv.URL + "/livez")
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("livez = %d, want 200", resp.StatusCode)
}
store.Down = false
app.StartDraining()
check(http.StatusServiceUnavailable)
}
// SIGTERM arrives while a slow request is in flight: readiness fails during
// the drain delay, the request still completes, Run returns nil.
func TestGracefulDrainFinishesInFlight(t *testing.T) {
app := &App{Store: session.NewMemoryStore()}
mux := http.NewServeMux()
mux.Handle("/", app.Handler())
mux.HandleFunc("GET /slow", func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(300 * time.Millisecond)
w.WriteHeader(http.StatusOK)
})
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
base := "http://" + ln.Addr().String()
srv := &http.Server{Handler: mux, ReadHeaderTimeout: time.Second}
ctx, sigterm := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- Run(ctx, srv, ln, app, Drain{Delay: 150 * time.Millisecond, Timeout: 2 * time.Second})
}()
slow := make(chan int, 1)
go func() {
resp, err := http.Get(base + "/slow")
if err != nil {
slow <- -1
return
}
resp.Body.Close()
slow <- resp.StatusCode
}()
time.Sleep(50 * time.Millisecond)
sigterm()
time.Sleep(50 * time.Millisecond)
resp, err := http.Get(base + "/readyz")
if err != nil {
t.Fatalf("listener closed too early (during drain delay): %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("readyz during drain = %d, want 503", resp.StatusCode)
}
if code := <-slow; code != http.StatusOK {
t.Fatalf("in-flight request = %d, want 200", code)
}
if err := <-done; err != nil {
t.Fatalf("Run = %v, want nil", err)
}
}The binary: configuration from the environment, signal.NotifyContext for SIGTERM, timeouts on the server, and a drain budget that fits the 30 s grace period.
// Command web runs one stateless replica. Configuration comes from the
// environment (12-factor), state lives in Redis, SIGTERM triggers a drain.
package main
import (
"context"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"academy/scaling-strategies/session"
"academy/scaling-strategies/stateless"
)
func main() {
addr := envOr("LISTEN_ADDR", ":8080")
redisAddr := envOr("REDIS_ADDR", "redis:6379")
host, _ := os.Hostname()
app := &stateless.App{Store: session.NewRedisStore(redisAddr), Replica: host}
srv := &http.Server{
Handler: app.Handler(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
ln, err := net.Listen("tcp", addr)
if err != nil {
slog.Error("listen", "err", err)
os.Exit(1)
}
// Kubernetes sends SIGTERM; Ctrl-C sends SIGINT locally.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
slog.Info("serving", "addr", addr, "replica", host)
// 10 s drain + 15 s shutdown = 25 s < terminationGracePeriodSeconds 30 s.
if err := stateless.Run(ctx, srv, ln, app, stateless.Drain{Delay: 10 * time.Second, Timeout: 15 * time.Second}); err != nil {
slog.Error("stopped with error", "err", err)
os.Exit(1)
}
slog.Info("drained cleanly")
}
func envOr(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}A USL calculator. Amdahl, USL capacity, peak, efficiency and a least-squares fit from load-test points.
// Package usl implements Amdahl's law and Gunther's Universal Scalability
// Law (USL), and fits the USL to load-test measurements.
//
// C(N) = N / (1 + sigma*(N-1) + kappa*N*(N-1))
//
// sigma is contention (the serial fraction: locks, a single queue, one
// primary database), kappa is coherency (pairwise coordination: cache
// invalidation, cross-node chatter). kappa = 0 gives Amdahl's law.
package usl
import (
"errors"
"math"
)
// Amdahl returns the speedup of n workers when a fraction sigma of the work
// is serial: n / (1 + sigma*(n-1)). It approaches 1/sigma as n grows.
func Amdahl(n, sigma float64) float64 { return n / (1 + sigma*(n-1)) }
// Capacity is the USL relative capacity C(N) = X(N)/X(1).
func Capacity(n, sigma, kappa float64) float64 {
return n / (1 + sigma*(n-1) + kappa*n*(n-1))
}
// Throughput scales a single-node throughput x1 by Capacity.
func Throughput(n, x1, sigma, kappa float64) float64 { return x1 * Capacity(n, sigma, kappa) }
// PeakN is where throughput stops growing, sqrt((1-sigma)/kappa). Beyond it
// the curve is retrograde: adding nodes lowers throughput. +Inf when kappa = 0.
func PeakN(sigma, kappa float64) float64 {
if kappa <= 0 {
return math.Inf(1)
}
return math.Sqrt((1 - sigma) / kappa)
}
// Efficiency is C(N)/N: the share of each added node you actually get.
func Efficiency(n, sigma, kappa float64) float64 { return Capacity(n, sigma, kappa) / n }
// Point is one load-test measurement: N nodes (or workers, or VUs at the
// saturation plateau) and the measured throughput X.
type Point struct{ N, X float64 }
// ErrNoBaseline means no measurement at N = 1 was supplied.
var ErrNoBaseline = errors.New("usl: need a measurement at N = 1")
// Fit estimates sigma and kappa by least squares. With C = X/X(1) and
// x = N-1, the USL rearranges to y = N/C - 1 = (sigma+kappa)*x + kappa*x^2,
// a quadratic through the origin solved here with the 2x2 normal equations.
func Fit(points []Point) (sigma, kappa float64, err error) {
var x1 float64
for _, p := range points {
if p.N == 1 {
x1 = p.X
}
}
if x1 <= 0 {
return 0, 0, ErrNoBaseline
}
var s2, s3, s4, sxy, sx2y float64
for _, p := range points {
if p.N <= 1 || p.X <= 0 {
continue
}
x := p.N - 1
y := p.N/(p.X/x1) - 1
s2 += x * x
s3 += x * x * x
s4 += x * x * x * x
sxy += x * y
sx2y += x * x * y
}
det := s2*s4 - s3*s3
if det == 0 {
return 0, 0, errors.New("usl: need at least two distinct N > 1")
}
a := (sxy*s4 - sx2y*s3) / det // sigma + kappa
b := (s2*sx2y - s3*sxy) / det // kappa
return a - b, b, nil
}package usl
import (
"math"
"testing"
)
func near(a, b, eps float64) bool { return math.Abs(a-b) <= eps }
func TestOneNodeIsBaseline(t *testing.T) {
if c := Capacity(1, 0.1, 0.01); c != 1 {
t.Fatalf("C(1) = %v, want 1", c)
}
}
func TestKappaZeroIsAmdahl(t *testing.T) {
for _, n := range []float64{2, 8, 64, 1024} {
if !near(Capacity(n, 0.05, 0), Amdahl(n, 0.05), 1e-12) {
t.Fatalf("N=%v: USL with kappa=0 must equal Amdahl", n)
}
}
}
func TestAmdahlCeiling(t *testing.T) {
// 5% serial work caps speedup at 1/0.05 = 20, no matter how many nodes.
if s := Amdahl(1e9, 0.05); !near(s, 20, 1e-6) {
t.Fatalf("Amdahl(inf, 0.05) = %v, want 20", s)
}
}
func TestPeakAndRetrograde(t *testing.T) {
sigma, kappa := 0.03, 0.0005
p := PeakN(sigma, kappa) // sqrt(0.97/0.0005) = 44.05
if !near(p, 44.05, 0.01) {
t.Fatalf("PeakN = %v, want about 44.05", p)
}
if !(Capacity(44, sigma, kappa) > Capacity(30, sigma, kappa)) {
t.Fatal("capacity should still grow below the peak")
}
if !(Capacity(100, sigma, kappa) < Capacity(44, sigma, kappa)) {
t.Fatal("capacity should fall (retrograde) beyond the peak")
}
if !math.IsInf(PeakN(0.1, 0), 1) {
t.Fatal("no coherency cost means no peak")
}
}
func TestFitRecoversParameters(t *testing.T) {
const sigma, kappa, x1 = 0.04, 0.0008, 950.0
var pts []Point
for _, n := range []float64{1, 2, 4, 8, 16, 24, 32} {
pts = append(pts, Point{N: n, X: Throughput(n, x1, sigma, kappa)})
}
s, k, err := Fit(pts)
if err != nil {
t.Fatal(err)
}
if !near(s, sigma, 1e-9) || !near(k, kappa, 1e-9) {
t.Fatalf("Fit = (%v, %v), want (%v, %v)", s, k, sigma, kappa)
}
}
func TestFitNeedsBaseline(t *testing.T) {
if _, _, err := Fit([]Point{{N: 2, X: 10}, {N: 4, X: 18}}); err != ErrNoBaseline {
t.Fatalf("err = %v, want ErrNoBaseline", err)
}
}The HPA decision, testable. Desired is the documented formula with tolerance; Stabilizer is the scale-down window; Simulate shows flapping with and without it.
// Package autoscale reproduces the Kubernetes HorizontalPodAutoscaler
// decision so its behaviour (tolerance, min/max, scale-down stabilization)
// can be tested without a cluster.
package autoscale
import (
"math"
"time"
)
// Desired is the HPA formula from the Kubernetes docs:
//
// desiredReplicas = ceil(currentReplicas * currentMetricValue / desiredMetricValue)
//
// If the ratio is within tolerance (default 0.1) of 1.0, nothing changes.
func Desired(current int32, metric, target, tolerance float64) int32 {
if current == 0 || target <= 0 {
return current
}
ratio := metric / target
if math.Abs(ratio-1) <= tolerance {
return current
}
return int32(math.Ceil(float64(current) * ratio))
}
// Clamp applies minReplicas and maxReplicas.
func Clamp(n, minR, maxR int32) int32 {
return max(minR, min(n, maxR))
}
// Stabilizer implements behavior.scaleDown.stabilizationWindowSeconds: the
// HPA uses the highest recommendation seen inside the window, so a short dip
// does not remove pods that the next spike needs again (flapping).
type Stabilizer struct {
Window time.Duration
recs []rec
}
type rec struct {
at time.Time
n int32
}
// Recommend records desired and returns the replica count to apply.
func (s *Stabilizer) Recommend(now time.Time, desired int32) int32 {
s.recs = append(s.recs, rec{now, desired})
keep := s.recs[:0]
best := desired
for _, r := range s.recs {
if now.Sub(r.at) <= s.Window {
keep = append(keep, r)
best = max(best, r.n)
}
}
s.recs = keep
return best
}
// Policy bundles the knobs of one HPA.
type Policy struct {
Min, Max int32
Target float64 // per-pod target, e.g. 60 (% CPU) or 50 (RPS)
Tolerance float64 // 0.1 by default
ScaleDownWindow time.Duration
}
// Simulate runs the controller once per period over a series of total load
// values (the metric per pod is load/replicas) and returns the replica count
// after each step.
func Simulate(p Policy, start int32, period time.Duration, load []float64) []int32 {
st := &Stabilizer{Window: p.ScaleDownWindow}
now := time.Unix(0, 0)
cur := start
out := make([]int32, 0, len(load))
for _, l := range load {
perPod := l / float64(cur)
d := Clamp(Desired(cur, perPod, p.Target, p.Tolerance), p.Min, p.Max)
if p.ScaleDownWindow > 0 {
d = st.Recommend(now, d)
}
cur = d
out = append(out, cur)
now = now.Add(period)
}
return out
}
// Changes counts how many times the replica count moved (a flapping score).
func Changes(series []int32) int {
n := 0
for i := 1; i < len(series); i++ {
if series[i] != series[i-1] {
n++
}
}
return n
}package autoscale
import (
"testing"
"time"
)
func TestDesiredMatchesDocsExamples(t *testing.T) {
// Kubernetes docs: 200m used with a 100m target doubles the replicas;
// 50m halves them.
if got := Desired(4, 200, 100, 0.1); got != 8 {
t.Fatalf("got %d, want 8", got)
}
if got := Desired(4, 50, 100, 0.1); got != 2 {
t.Fatalf("got %d, want 2", got)
}
}
func TestToleranceIgnoresSmallDrift(t *testing.T) {
if got := Desired(10, 108, 100, 0.1); got != 10 {
t.Fatalf("8%% over target should be ignored, got %d", got)
}
if got := Desired(10, 115, 100, 0.1); got != 12 {
t.Fatalf("15%% over target: ceil(11.5) = 12, got %d", got)
}
}
func TestClamp(t *testing.T) {
if Clamp(1, 3, 20) != 3 || Clamp(50, 3, 20) != 20 || Clamp(7, 3, 20) != 7 {
t.Fatal("clamp wrong")
}
}
func TestStabilizationWindowStopsFlapping(t *testing.T) {
// Load alternates between 600 and 300 RPS every 15 s step.
var load []float64
for i := 0; i < 40; i++ {
if i%2 == 0 {
load = append(load, 600)
} else {
load = append(load, 300)
}
}
base := Policy{Min: 2, Max: 20, Target: 50, Tolerance: 0.1}
flappy := Simulate(base, 6, 15*time.Second, load)
base.ScaleDownWindow = 5 * time.Minute
stable := Simulate(base, 6, 15*time.Second, load)
if Changes(flappy) < 30 {
t.Fatalf("expected flapping without a window, got %d changes", Changes(flappy))
}
if Changes(stable) > 1 {
t.Fatalf("expected at most one change with a 5 min window, got %d: %v", Changes(stable), stable)
}
if stable[len(stable)-1] != 12 {
t.Fatalf("stable size = %d, want 12 (600 RPS / 50 per pod)", stable[len(stable)-1])
}
}The numbers on this page come from this program (deterministic):
// Command scalecalc prints the numbers used on the scaling-strategies page:
// Amdahl vs USL capacity, the USL peak, a fit from load-test points, and an
// HPA simulation with and without a scale-down stabilization window.
package main
import (
"fmt"
"time"
"academy/scaling-strategies/autoscale"
"academy/scaling-strategies/usl"
)
func main() {
const sigma, kappa, x1 = 0.03, 0.0005, 1000.0
fmt.Printf("1) Amdahl vs USL, X(1) = %.0f req/s, sigma = %.2f, kappa = %.4f\n", x1, sigma, kappa)
fmt.Println(" N Amdahl X USL X efficiency")
for _, n := range []float64{1, 2, 4, 8, 16, 32, 44, 64, 128} {
fmt.Printf(" %-5.0f %-10.0f %-9.0f %.0f%%\n", n,
x1*usl.Amdahl(n, sigma), usl.Throughput(n, x1, sigma, kappa),
100*usl.Efficiency(n, sigma, kappa))
}
fmt.Printf(" peak N* = sqrt((1-sigma)/kappa) = %.1f; Amdahl ceiling = 1/sigma = %.0fx\n",
usl.PeakN(sigma, kappa), 1/sigma)
pts := []usl.Point{{N: 1, X: 955}, {N: 2, X: 1840}, {N: 4, X: 3420}, {N: 8, X: 5800}, {N: 16, X: 8300}}
s, k, err := usl.Fit(pts)
if err != nil {
panic(err)
}
fmt.Printf("2) Fit of 5 load-test points: sigma = %.4f, kappa = %.5f, peak N* = %.0f, predicted X(32) = %.0f\n",
s, k, usl.PeakN(s, k), usl.Throughput(32, 955, s, k))
var load []float64
for i := 0; i < 20; i++ {
if i%2 == 0 {
load = append(load, 600)
} else {
load = append(load, 300)
}
}
p := autoscale.Policy{Min: 2, Max: 20, Target: 50, Tolerance: 0.1}
flappy := autoscale.Simulate(p, 6, 15*time.Second, load)
p.ScaleDownWindow = 5 * time.Minute
stable := autoscale.Simulate(p, 6, 15*time.Second, load)
fmt.Println("3) HPA, target 50 RPS per pod, load alternating 600/300 RPS every 15 s")
fmt.Printf(" no window : %v (%d changes)\n", flappy, autoscale.Changes(flappy))
fmt.Printf(" 5 min : %v (%d changes)\n", stable, autoscale.Changes(stable))
}The Go angle
| Go feature | Use for scaling | Note |
|---|---|---|
http.Server.Shutdown(ctx) | Graceful drain | Closes listeners, then idle connections, waits for active ones; always pass a deadline |
http.ErrServerClosed | Normal exit of Serve after Shutdown | Do not log it as an error |
Server.RegisterOnShutdown | Tell WebSocket/hijacked connections to close | Shutdown does not wait for them |
signal.NotifyContext | Turn SIGTERM into context cancellation | Kubernetes sends SIGTERM first |
ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout | Bound per-connection cost | Slow clients otherwise pin goroutines |
GOMAXPROCS | Match CPU limits | Go 1.25+ reads the container CPU limit by default; check your version |
runtime/debug.SetMemoryLimit / GOMEMLIMIT | Keep GC under the pod memory limit | Avoid OOM kills during spikes |
sync/atomic.Bool | Readiness flag | Cheap and race-free |
database/sql SetMaxOpenConns | Connection budget per replica | replicas × max must fit the database |
github.com/redis/go-redis/v9 PoolSize | Redis connections per replica | Same budget rule |
net/http/pprof, runtime/trace | Find σ (locks) and κ (chatter) | Profile at the knee, not at idle |
Laravel
Before
File sessions, local uploads and a static array: stateful on three axes. It passes on one server and breaks behind a load balancer, under Octane, or on scale-in.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// Stateful by accident: works on one server, breaks behind a load balancer,
// leaks memory under Octane, and loses files on every scale-in.
class CartControllerBefore extends Controller
{
// Static state survives between requests in an Octane worker: it grows
// forever and differs per worker and per replica.
private static array $recentlyViewed = [];
public function add(Request $request)
{
// SESSION_DRIVER=file: the session lives in storage/framework/sessions
// on THIS machine only. The next request may land elsewhere.
$cart = $request->session()->get('cart', []);
$cart[] = $request->string('sku')->toString();
$request->session()->put('cart', $cart);
self::$recentlyViewed[] = $request->string('sku')->toString();
return response()->noContent();
}
public function uploadReceipt(Request $request)
{
// The default local disk: gone when the instance is replaced,
// invisible to every other replica.
$path = $request->file('receipt')->store('receipts');
return ['path' => $path];
}
}After
Stateless controller. Sessions and cache in Redis (SESSION_DRIVER=redis, CACHE_STORE=redis), files on S3 with temporary URLs, so any replica and any Octane worker can serve any request.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
// Stateless: every replica and every Octane worker can serve every request.
// .env: SESSION_DRIVER=redis, CACHE_STORE=redis, FILESYSTEM_DISK=s3.
class CartController extends Controller
{
public function add(Request $request)
{
$sku = $request->validate(['sku' => ['required', 'string', 'max:64']])['sku'];
// Session payload lives in Redis, keyed by the session cookie id.
$request->session()->push('cart', $sku);
// Shared counters go to the shared cache, not to a static array.
Cache::increment("views:{$sku}");
return response()->noContent();
}
public function uploadReceipt(Request $request)
{
$request->validate(['receipt' => ['required', 'file', 'max:5120']]);
// Object storage is the shared, durable home for user files.
$path = Storage::disk('s3')->putFile('receipts', $request->file('receipt'));
// Clients download directly from S3 (or a CDN in front of it), so the
// web tier never streams large files.
return [
'path' => $path,
'url' => Storage::disk('s3')->temporaryUrl($path, now()->addMinutes(10)),
];
}
}# .env for every replica (12-factor config; config:cache at deploy)
APP_ENV=production
SESSION_DRIVER=redis
CACHE_STORE=redis
QUEUE_CONNECTION=redis
FILESYSTEM_DISK=s3
REDIS_HOST=redis.internal
AWS_BUCKET=app-uploads
# deploy step, once per release
php artisan optimize # caches config, events, routes, viewsOctane-safe container bindings and a cheap health check. scoped() instead of a singleton that captures the request; a DiagnosingHealth listener for Laravel's /up route.
<?php
namespace App\Providers;
use App\Services\PriceCalculator;
use Illuminate\Container\Container;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// Octane boots the app once per worker. A singleton that captured the
// request or the container at boot would serve stale state forever;
// scoped() is flushed at the start of every Octane request or queue job.
$this->app->scoped(PriceCalculator::class, function () {
return new PriceCalculator(fn () => Container::getInstance()->make('request'));
});
}
public function boot(): void
{
// Laravel's /up health route dispatches DiagnosingHealth; throwing here
// turns /up into a 500. Keep it cheap: it is polled every few seconds
// by every load balancer and probe.
Event::listen(DiagnosingHealth::class, function () {
DB::connection()->getPdo();
});
}
}<?php
namespace App\Services;
use Closure;
use Illuminate\Http\Request;
// Receives a resolver, not the Request itself, so it never holds a stale
// request across Octane requests.
class PriceCalculator
{
public function __construct(private Closure $request)
{
}
public function currency(): string
{
/** @var Request $request */
$request = ($this->request)();
return $request->header('X-Currency', 'EUR');
}
}Readiness separate from liveness, and a drain command for the preStop hook:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Throwable;
// Readiness for a Kubernetes readinessProbe or an AWS ALB target group:
// "can this replica serve traffic right now?". Liveness stays on Laravel's
// built-in /up route, which must not check dependencies.
class ReadinessController extends Controller
{
public function __invoke()
{
// Set by the preStop hook (php artisan app:drain) before SIGTERM. A
// local file is right here: draining is a fact about THIS pod only.
if (is_file(storage_path('framework/draining'))) {
return response('draining', 503);
}
try {
DB::select('select 1');
Redis::connection()->ping();
} catch (Throwable $e) {
report($e);
return response('dependency unavailable', 503);
}
return response('ready', 200);
}
}<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
// Run from the Kubernetes preStop hook: fail readiness first, then give the
// load balancers time to stop routing here before SIGTERM reaches Octane.
class DrainCommand extends Command
{
protected $signature = 'app:drain {--wait=10 : Seconds to keep serving after readiness fails}';
protected $description = 'Fail the readiness probe and wait for endpoints to update';
public function handle(): int
{
touch(storage_path('framework/draining'));
$this->info('readiness now returns 503; waiting '.$this->option('wait').'s');
sleep((int) $this->option('wait'));
return self::SUCCESS;
}
}<?php
use App\Http\Controllers\CartController;
use App\Http\Controllers\ReadinessController;
use Illuminate\Support\Facades\Route;
Route::post('/cart/items', [CartController::class, 'add']);
Route::post('/receipts', [CartController::class, 'uploadReceipt']);
// Readiness probe target. Liveness uses the framework's /up route, declared
// in bootstrap/app.php with ->withRouting(health: '/up').
Route::get('/ready', ReadinessController::class);Queue autoscaling with Horizon: auto balancing with the time strategy, a floor per queue and a ceiling per host.
<?php
// config/horizon.php (excerpt): queue autoscaling inside one Horizon
// supervisor. Horizon balances processes between queues on this host;
// adding hosts (horizontal scaling) is the job of KEDA, an ASG or Forge.
return [
'defaults' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['payments', 'notifications', 'default'],
'balance' => 'auto',
'autoScalingStrategy' => 'time', // or 'size', or 'log'
'minProcesses' => 1, // per queue, must be >= 1
'maxProcesses' => 12, // total across all queues
'balanceMaxShift' => 2, // add or remove at most 2 processes ...
'balanceCooldown' => 3, // ... every 3 seconds
'tries' => 3,
'timeout' => 60,
],
],
'environments' => [
'production' => [
'supervisor-1' => [
'maxProcesses' => 24,
],
],
'local' => [
'supervisor-1' => [
'maxProcesses' => 3,
],
],
],
];# Laravel pod under Octane (FrankenPHP); liveness on /up, readiness on /ready
containers:
- name: web
image: registry.example.com/shop:2026.11.1
command: ["php", "artisan", "octane:frankenphp", "--workers=4", "--max-requests=500", "--port=8000"]
resources: { requests: { cpu: "2", memory: "512Mi" }, limits: { memory: "1Gi" } }
livenessProbe: { httpGet: { path: /up, port: 8000 }, periodSeconds: 10 }
readinessProbe: { httpGet: { path: /ready, port: 8000 }, periodSeconds: 2 }
lifecycle:
preStop: { exec: { command: ["php", "artisan", "app:drain", "--wait=10"] } }The Laravel angle
| Laravel feature | Role in scaling | Note |
|---|---|---|
Session drivers (redis, database, memcached, dynamodb, cookie) | Externalised sessions | Default is database; file is single-server |
CACHE_STORE=redis | Shared cache, Cache::lock() | array and file stores are per process / per host |
Storage::disk('s3'), temporaryUrl() | Shared files, direct downloads | Needs league/flysystem-aws-s3-v3 |
php artisan optimize / config:cache | Fast boot for new replicas | After caching, env() outside config returns null |
/up health route, DiagnosingHealth | Liveness / LB health | Keep listeners cheap |
Octane (--workers, --max-requests, octane:reload) | More throughput per pod | One worker per core by default; restart after 500 requests |
$this->app->scoped() | Per-request instances under Octane | Avoid singletons capturing request/config |
| Octane cache (Swoole tables) | Per-server cache shared by workers | Not shared across replicas, flushed on restart |
Horizon balance: auto, autoScalingStrategy, minProcesses, maxProcesses | Queue autoscaling on one host | Scale hosts with KEDA/ASG |
horizon:terminate | Graceful worker stop | Finishes current jobs |
Read/write DB connections with sticky | Read replicas with read-your-writes | See Replication |
Solving the classic problems
Users are logged out at random after adding a second server
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Shared session store | Redis or database session driver | Any server serves any user | Redis becomes a dependency to make HA |
| Signed cookie sessions | Laravel cookie driver, JWT-like cookies | No server state | Size limit (~4 KB), revocation is hard |
| Sticky sessions | ALB AWSALB cookie | No code change | Lost on scale-in, uneven load, a 12-factor violation |
Prefer the shared store; keep stickiness off.
502s on every deploy and scale-in
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Readiness first, then drain | preStop delay or app drain flag, then Shutdown | No dropped requests | Slower rollouts by ~10 s per pod |
| ALB deregistration delay tuned | Shorter than grace period for short requests | Matches app behaviour | Long requests need a longer grace period |
| Connection draining in proxies | Envoy/NGINX graceful reload | Covers the proxy tier | Configuration per proxy |
The autoscaler flaps
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Scale-down stabilization | stabilizationWindowSeconds: 300 or more | Stops scale-in on dips | Pays for idle pods a bit longer |
| Rate limits on scale-down | Percent 10 per 60 s | Gentle shrink | Slower savings |
| Smoother metric | Rate over 2 minutes, not instantaneous | Less noise | Slower reaction |
| Hysteresis | Different up/down thresholds (step scaling) | Predictable | More policy to maintain |
Scaling the API made the database fall over
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Connection pooler | PgBouncer, RDS Proxy | Thousands of clients → hundreds of server connections | Transaction pooling breaks session features |
Cap maxReplicas from the budget | max_connections / pool | No surprise exhaustion | A ceiling on app scale |
| Diagonal app tier | Fewer, larger pods | Fewer pools | Coarser scaling steps |
| Cache and replicas | Move reads away | Real capacity | Staleness |
Autoscaling is too slow for spikes
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Higher minimum + headroom | minReplicas from N+2, CPU target 60% | Instant capacity | Paying for idle |
| Predictive / scheduled scaling | AWS predictive policy, KEDA cron | Capacity before the spike | Needs regular patterns |
| Warm pools / overprovisioning | EC2 warm pool, pause pods | Minutes become seconds | Some idle cost |
| Faster start | Smaller images, Go/Octane, optimize, startupProbe | Every scale event gets faster | Engineering time |
| Load shedding | Reject early while scaling | Protects the healthy part | Some users see 503 (Load Shedding) |
Throughput went down after adding nodes
Fit the USL to your test points, find N*, and look for κ sources: all-to-all cache invalidation, distributed locks, consumer rebalances, scatter-gather queries. Cap maxReplicas below N* until κ is reduced.
Queue backlog grows during peaks
| Solution | How | Advantage | Cost |
|---|---|---|---|
| KEDA on queue depth | listLength / lag target per replica | Scales on the real signal | Needs metrics access |
Horizon auto + more hosts | Balance per host, scale hosts | Fair use of workers | Two levels to tune |
| Batch inside jobs | Process 50 items per job | Higher throughput per worker | Larger retries |
| Priority split | Separate supervisors for critical queues | Payments never starve | More processes |
Choosing
Which direction
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Stateless web/API tier | Scale out, autoscale | Diagonal sizing, N+2 | Cheap, redundant, elastic |
| Database primary under load | Scale up first | Pooling, caching, replicas | No design change, strong consistency |
| Read-heavy product (catalogue, news) | CDN + cache + replicas | Read-your-writes routing | Reads are copyable |
| Write-heavy ingest | Batch + queue, then shard | Sharded counters | Writes need an owner |
| Spiky queue work | Scale out workers on depth | KEDA, scale to zero | Jobs are independent |
| WebSocket / real-time tier | Scale out with connection-aware balancing | Presence in Redis, reconnect | Connections are state |
| One big in-memory job | Scale up | Spot + checkpointing | Coordination would dominate |
| Throughput flat after adding nodes | Stop scaling out; reduce σ/κ | USL fit | Retrograde zone |
Which autoscaler and metric
| Workload | Autoscaler | Metric | Bounds and windows |
|---|---|---|---|
| HTTP API on Kubernetes | HPA | RPS per pod (custom), CPU as backup | min from N+2, max from DB budget, 5 min down window |
| Queue workers on Kubernetes | KEDA | Queue length or lag per replica | min 0–1, cooldown 300 s |
| Laravel queues on one VM | Horizon auto | Time to clear (time) | minProcesses for critical queues |
| EC2 web fleet | ASG target tracking + predictive | ALBRequestCountPerTarget or CPU | Warm pool for slow boots |
| Business-hours internal app | Scheduled scaling | Time | min high by day, 0–1 at night |
| Pods with unknown sizes | VPA Off → Initial | Usage recommendations | Never with HPA on the same resource |
| Nodes | Cluster Autoscaler or Karpenter | Pending pods | Overprovision for the first step |
Which pricing model
| Capacity slice | Pricing | Why |
|---|---|---|
| Always-on baseline | Reserved Instances / Savings Plans | Up to 72% off for steady use |
| Daily peak | On-demand, autoscaled | Pay only while needed |
| Retryable, stateless | Spot across instance types | Deep discount; two-minute notice |
| Rare or spiky, small | Serverless (Lambda) or scale to zero | No idle cost |
In architecture: from a single process to a distributed system
Scaling is not a property you add at the end; each step of the architecture changes what can be scaled and how.
Monolith: one process, one database
A single Laravel or Go monolith on one VM scales up first: bigger instance, Octane or more PHP-FPM workers, a cache. The first horizontal step is to run two copies behind a load balancer, which forces the stateless checklist: sessions in Redis or the database, files on S3, scheduled jobs on one node (onOneServer() in Laravel's scheduler needs a shared cache lock), config from the environment. Example: a shop at 50 req/s on one 4-vCPU VM moves to two 2-vCPU VMs behind an ALB, SESSION_DRIVER=redis, uploads to S3; it gains redundancy before it needs capacity.
Modular monolith: boundaries without the network
Modules share one deployable but can have their own workers and queues. Scale per workload, not per module: the web process scales out on RPS, the reports queue gets its own Horizon supervisor and its own hosts, the payments module keeps a strongly consistent schema on the primary. Example: one Laravel codebase deployed as three process types (12-factor "process formation"): web (Octane, HPA on RPS), worker-default (Horizon, KEDA on depth), worker-reports (spot nodes, scale to zero at night).
Microservices: every arrow is a decision
Each service gets its own scaling policy, and the weakest dependency sets the ceiling. When orders scales from 10 to 40 pods, inventory sees 4x the calls; if inventory scales on CPU with a 3-minute node lag, orders must have timeouts, retries with budgets and a circuit breaker (Service Communication, Cascading Failures). Prefer asynchronous edges for work that can wait, so a queue absorbs the mismatch. Example flow: POST /orders → orders (HPA on RPS) writes the order and an outbox row → Kafka OrderPlaced → payments consumers (KEDA on lag, max = partitions) → notifications (scale to zero).
Distributed data: replicas, caches, regions
Stateless tiers push the state down, and the data tier scales by copying (replicas, caches, CDN) and splitting (partitions, shards). Each copy brings staleness: a replica lags, a cache serves an old value, a region sees a write later. Scale reads with explicit consistency choices (Consistency Models); scale writes by giving every key one owner. Multi-region adds the coordination tax at its most expensive: every cross-region consensus round trip is tens of milliseconds, a large κ. Example: a global app serves reads from regional replicas and Redis, writes to one home region per user, and autoscales each region independently.
Scaling path: 1x, 10x, 100x
| Load | Web/API | Data | Operations |
|---|---|---|---|
| 1x (100 req/s) | 2 replicas (N+1), stateless | One primary + standby, Redis | Health checks, graceful shutdown |
| 10x (1,000 req/s) | HPA 3..20, diagonal sizing, Octane | Bigger primary, PgBouncer, 2 replicas, CDN | Load tests per release, USL fit, N+2 |
| 100x (10,000 req/s) | Multiple node pools, predictive + reactive, warm capacity | Partitioned tables, sharded writes, Redis Cluster, queues everywhere | Cost per request, spot for workers, per-team scaling ownership |
Lab: USL fit, flapping and a graceful drain, with numbers
Steps 1 and 2 are single-process Go programs and were run on the author's machine; the output is copied from those runs. Steps 3 to 6 need a running stack and are expected, not run.
- Run the tests (stateless replicas sharing a store, readiness, drain, USL, HPA):
cd docs/snippets/system-design/scaling-strategies/go
go test ./...
# ok academy/scaling-strategies/autoscale
# ok academy/scaling-strategies/stateless
# ok academy/scaling-strategies/usl- Print the page's numbers:
go run ./cmd/scalecalc
# 1) Amdahl vs USL, X(1) = 1000 req/s, sigma = 0.03, kappa = 0.0005
# N Amdahl X USL X efficiency
# 1 1000 1000 100%
# 8 6612 6462 81%
# 32 16580 13190 41%
# 44 19214 13597 31%
# 64 22145 13045 20%
# 128 26611 9893 8%
# peak N* = sqrt((1-sigma)/kappa) = 44.0; Amdahl ceiling = 1/sigma = 33x
# 2) Fit of 5 load-test points: sigma = 0.0342, kappa = 0.00136, peak N* = 27, predicted X(32) = 8949
# 3) HPA, target 50 RPS per pod, load alternating 600/300 RPS every 15 s
# no window : [12 6 12 6 12 6 12 6 12 6 12 6 12 6 12 6 12 6 12 6] (19 changes)
# 5 min : [12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12] (0 changes)The five points in step 2 are synthetic sample measurements hard-coded in scalecalc; their fit says: stop at about 27 replicas, because at 32 you would get less than at 27.
- Find the knee with an open-model test (k6
ramping-arrival-rate; expected, not run):
// knee.js: run with k6 run knee.js
import http from 'k6/http';
export const options = {
scenarios: {
breakpoint: {
executor: 'ramping-arrival-rate',
startRate: 100, timeUnit: '1s',
preAllocatedVUs: 200, maxVUs: 2000,
stages: [ { target: 2000, duration: '10m' } ], // +200 req/s per minute
},
},
thresholds: { http_req_failed: [ { threshold: 'rate<0.01', abortOnFail: true } ] },
};
export default function () { http.get('http://localhost:8080/cart'); }
// expected: p99 roughly flat until ~1,400 req/s per pod, then a knee; abort near 1,800 req/s- Cross-check with vegeta (constant rate) and wrk (closed model) (expected, not run):
echo "GET http://localhost:8080/cart" | vegeta attack -rate=1000 -duration=60s | tee r.bin | vegeta report
# Latencies [min, mean, 50, 95, 99, max] ... 99th around 18ms at 1,000/s (one 2-vCPU pod)
wrk -t4 -c64 -d30s --latency http://localhost:8080/cart
# Requests/sec reported is what 64 connections can push, not the rate users would send- Watch the HPA and the drain on a cluster (expected, not run):
kubectl apply -f hpa.yaml
kubectl get hpa api --watch
# NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
# api Deployment/api 48/50, 41%/60% 3 40 6
kubectl describe hpa api | grep -A5 Events
# Normal SuccessfulRescale New size: 12; reason: pods metric http_requests_per_second above target
kubectl rollout restart deploy/api &
vegeta attack -rate=500 -duration=90s < targets.txt | vegeta report -type=text | grep 'Status Codes'
# Status Codes [code:count] 200:45000 <- with readiness + drain; without it, expect some 502s- Measure the cold start (expected, not run): scale a deployment from 3 to 13 with
kubectl scale, and record the time untilkubectl get deployshows 13 ready replicas, once with spare node capacity and once without. Without spare nodes, expect the node provisioning time (minutes) to dominate; with spare capacity, expect seconds.
Common misconceptions
| Belief | Reality |
|---|---|
| Horizontal scaling is always better than vertical | For stateful tiers, scale up first; scale out what is stateless |
| N nodes give N times the throughput | Contention bends the curve, coherence turns it down (USL) |
| Stateless means no state | State moves to Redis, the database and S3, which you must now scale |
| Sticky sessions are a fine fix for sessions | They break on scale-in and deploys and skew load; 12-factor forbids relying on them |
| A read replica doubles database capacity | Only reads, with lag; every replica still replays every write |
| A queue increases write capacity | It absorbs bursts; average rate must still fit the consumers |
| Autoscaling replaces capacity planning | It reacts late; you still need headroom, bounds and load tests |
| HPA scaled up, so users are fine | New pods may be Pending until nodes arrive |
| Faster cooldowns are always better | Fast scale-down causes flapping and repeated cold starts |
| Liveness probes should check the database | That restarts the whole fleet on a database blip |
| Kubernetes stops routing before SIGTERM | Endpoint removal and SIGTERM race; add a drain delay |
| Scale to zero is free | The first request pays the full cold start |
| Octane is just faster PHP | It keeps the app in memory; static and captured state leak across requests |
| Sharding early saves work later | It freezes a shard key before you know the access patterns |
Cheat sheet
| Topic | Remember |
|---|---|
| Vertical | First for stateful tiers; ceiling, cost curve, NUMA, one failure domain |
| Horizontal | Needs statelessness or partitioning; pay the coordination tax |
| Diagonal | Right-size the node, then multiply it |
| Amdahl | N/(1+σ(N−1)), ceiling 1/σ |
| USL | N/(1+σ(N−1)+κN(N−1)), peak √((1−σ)/κ), retrograde after |
| Stateless | Sessions → Redis/DB, files → S3, cache → shared, config → env |
| Sticky sessions | A smell for app state; OK only as a cache-locality hint |
| Reads | CDN → cache → replicas; design for staleness |
| Writes | Batch → queue → shard |
| HPA | ceil(cur × metric/target), 15 s loop, 10% tolerance, 5 min down window |
| KEDA | Event metrics, 0↔1, poll 30 s, cooldown 300 s |
| Nodes | Cluster Autoscaler / Karpenter react to Pending pods; minutes |
| Graceful shutdown | Readiness 503 → delay → Shutdown(ctx) → exit before 30 s |
| Headroom | N+2 from the breaking point; ~60% CPU target across 3 zones |
| Cost | Reserved for baseline, on-demand for peaks, spot for retryable, zero for idle |
| Load test | Open model (k6 arrival rate, vegeta); find the knee and the breaking point |
| Laravel | Octane workers = cores, --max-requests, scoped(); Horizon auto + time |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Your PostgreSQL primary is at 75% CPU at peak and the app tier is autoscaled. What is your first scaling move, and why not sharding? Must-know
Answer
Answer: Fix the top queries and add pooling, then scale the primary up (and add a read replica for read-heavy paths). Scaling up needs no design change and keeps strong consistency; sharding freezes a shard key, complicates every cross-shard query and migration, and is the last rung of the ladder.
2 — With σ = 0.05, what is the best speedup you can ever get, and what do you get at 64 nodes? Must-know
Answer
Answer: The Amdahl ceiling is 1/σ = 20x. At 64 nodes: 64 / (1 + 0.05 × 63) = 64 / 4.15 ≈ 15.4x.
3 — A USL fit gives σ = 0.02 and κ = 0.0004. Where is the peak, and what does that mean for maxReplicas? Good to know
Answer
Answer: N* = √(0.98/0.0004) ≈ 49.5. Beyond about 49 replicas throughput falls, so set maxReplicas below that (with margin) until κ is reduced.
4 — Name three things that make a web process stateful and where each should go. Must-know
Answer
Answer: In-memory or file sessions → Redis or the database session driver; uploaded files on local disk → object storage (S3); in-process counters or caches that must be consistent → Redis. Also scheduled jobs (one scheduler or a lock) and config (environment).
5 — Why are sticky sessions a smell in an autoscaled tier, and when is affinity acceptable? Must-know
Answer
Answer: Scale-in, deploys and crashes drop the sessions held on a node; heavy users skew load; new nodes only receive new users. Affinity is acceptable as a performance hint when losing it only costs a cache miss, or for connection-bound protocols with reconnect logic.
6 — HPA: 8 pods, target 60% CPU, current average 90%. What does it request? And at 64%? Important
Answer
Answer: ceil(8 × 90/60) = 12. At 64%, the ratio is 1.067, within the 10% tolerance, so nothing changes.
7 — Your pods scale up within 15 s of a spike, but users see errors for three minutes. What is happening? Important
Answer
Answer: The new pods are Pending ("Insufficient cpu") until Cluster Autoscaler or Karpenter adds nodes and the image is pulled. Fix with overprovisioning (low-priority pause pods), warm pools, a higher minReplicas, predictive or scheduled scaling, and faster starts.
8 — Describe a correct shutdown sequence for an autoscaled Go replica with a 30 s grace period. Important
Answer
Answer: On termination, fail readiness (or preStop sleep), keep serving ~5–10 s while endpoints are removed, then call http.Server.Shutdown with a ~15 s context so listeners and idle connections close and in-flight requests finish, then exit well before 30 s, when SIGKILL would arrive.
9 — Peak is 19,000 QPS and one cluster breaks at 5,000 QPS. How many clusters for N+2, and what is the utilisation at peak? Must-know
Answer
Answer: ceil(19,000/5,000) = 4, plus 2 = 6 clusters; 19,000 / 30,000 ≈ 63% at peak.
10 — Why does a closed-model load test (fixed virtual users) overstate capacity, and which tools avoid it? Important
Answer
Answer: When the system slows down, each virtual user sends fewer requests, so the offered load falls exactly when it should not (coordinated omission). Open-model tools keep the arrival rate: k6 ramping-arrival-rate/constant-arrival-rate and vegeta's -rate.
11 — What changes when a Laravel app moves from PHP-FPM to Octane, from a scaling point of view? Important
Answer
Answer: Each worker serves many requests from one booted application, so throughput per pod rises, but static properties and singletons that capture the request, container or config now persist across requests. Use scoped() bindings or resolver closures, avoid static arrays, set --max-requests, and reload workers on deploy.
12 — Why should a VPA and an HPA not both act on CPU for the same Deployment? Important
Answer
Answer: The VPA changes the CPU request, which changes the HPA's utilisation percentage, so each controller's action moves the other's input; the VPA's known limitations say not to combine them on the same resource metric. Use VPA on memory or in Off mode, or HPA on custom/external metrics.
Glossary
| Term | Meaning |
|---|---|
| Vertical scaling (scale up) | Adding resources to one node |
| Horizontal scaling (scale out) | Adding nodes that share the work |
| Diagonal scaling | Right-sizing nodes, then adding more of them |
| Shared-nothing | Nodes share no memory or disk; they coordinate over the network |
| Stateless | A process that keeps no data between requests |
| Stateful | A process or tier that owns data across requests |
| Externalised state | Session, cache, files and locks kept in shared backing services |
| 12-factor | The Twelve-Factor App methodology (processes, concurrency, disposability) |
| Sticky session | Load-balancer affinity binding a client to one backend |
| Amdahl's law | Speedup limited by the serial fraction σ, ceiling 1/σ |
| Universal Scalability Law | Gunther's model adding coherence κ to Amdahl; has a peak |
| Contention | Queueing for a shared resource (σ) |
| Coherence / coordination cost | Pairwise work to keep shared data consistent (κ) |
| Retrograde scaling | Throughput falling as nodes are added past the peak |
| NUMA | Non-uniform memory access: local memory is faster than remote memory |
| Read replica | A copy of the database that serves reads, with lag |
| Cache | A fast copy of data to serve repeated reads |
| CDN | Edge caches that serve content close to users |
| Sharding | Splitting data by key so each shard owns a slice of writes |
| Queue | A buffer that decouples producers from consumers |
| Batching | Combining many small operations into one |
| Autoscaling | A controller changing capacity from a metric |
| Target tracking | Keep a metric at a target value (thermostat) |
| Step scaling | Alarm bands mapped to fixed adjustments |
| Predictive scaling | Capacity launched ahead of a forecast |
| Scheduled scaling | Capacity changed at fixed times |
| Cooldown | A wait after a scaling action before the next |
| Stabilization window | HPA's look-back that picks the highest recommendation before scaling down |
| Flapping (thrashing) | Capacity oscillating up and down |
| HPA | Kubernetes HorizontalPodAutoscaler (pod count) |
| VPA | Kubernetes VerticalPodAutoscaler (pod requests) |
| KEDA | Kubernetes Event-driven Autoscaling, including scale to zero |
| Cluster Autoscaler | Adds or removes nodes for pending or unneeded pods |
| Karpenter | Node provisioner that creates right-sized nodes for pending pods |
| Warm pool | Pre-initialised instances ready to join an Auto Scaling group |
| Scale to zero | Running no replicas when idle |
| Cold start | Time from requesting capacity to serving at full speed |
| Readiness probe | Check that decides whether a pod receives traffic |
| Liveness probe | Check that decides whether a container is restarted |
| Graceful shutdown | Stop accepting, finish in-flight work, then exit |
| Headroom | Capacity above expected peak |
| N+1 redundancy | Peak served with one unit lost |
| N+2 | Peak served with two units lost (planned + unplanned) |
| Right-sizing | Matching instance types and requests to real usage |
| Spot instance | Discounted spare capacity that can be interrupted with notice |
| Reserved instance | Discount for a one- or three-year commitment |
| Load testing | Generating traffic to measure limits |
| k6 | Load-testing tool with open-model executors |
| wrk | Closed-model HTTP benchmarking tool |
| vegeta | Constant-rate HTTP load tool |
| Knee | The load where latency starts rising much faster than throughput |
| Throughput | Requests completed per unit of time |
| Saturation | How full a resource is (CPU, connections, queue) |
| Octane | Laravel's long-running application server integration |
| Horizon balance | Horizon's worker balancing strategy (auto, simple, false) |
| Conway's law | Systems mirror the communication structure of their organisation |
References
- The Twelve-Factor App — VI. Processes: https://12factor.net/processes
- The Twelve-Factor App — VIII. Concurrency: https://12factor.net/concurrency
- The Twelve-Factor App — IX. Disposability: https://12factor.net/disposability
- The Twelve-Factor App — IV. Backing services: https://12factor.net/backing-services
- Neil J. Gunther — A General Theory of Computational Scalability Based on Rational Functions (arXiv 0808.1431): https://arxiv.org/abs/0808.1431 (full text read from https://arxiv.org/pdf/0808.1431)
- Neil J. Gunther — A New Interpretation of Amdahl's Law and Geometric Scalability (arXiv cs/0210017): https://arxiv.org/abs/cs/0210017
- Wikipedia (secondary) — Amdahl's law (summary of Amdahl 1967, AFIPS): https://en.wikipedia.org/wiki/Amdahl's_law
- Wikipedia (secondary) — Neil J. Gunther: https://en.wikipedia.org/wiki/Neil_J._Gunther
- Wikipedia (secondary) — Shared-nothing architecture: https://en.wikipedia.org/wiki/Shared-nothing_architecture
- Wikipedia (secondary) — Non-uniform memory access: https://en.wikipedia.org/wiki/Non-uniform_memory_access
- Melvin E. Conway — How Do Committees Invent? (1968): https://www.melconway.com/Home/Committees_Paper.html
- Google SRE Book — Service Best Practices (N + 2): https://sre.google/sre-book/service-best-practices/
- Google SRE Book — Addressing Cascading Failures: https://sre.google/sre-book/addressing-cascading-failures/
- Google SRE Book — Handling Overload: https://sre.google/sre-book/handling-overload/
- Google SRE Book — Load Balancing in the Datacenter: https://sre.google/sre-book/load-balancing-datacenter/
- Google SRE Book — Software Engineering in SRE (Auxon, intent-based capacity planning): https://sre.google/sre-book/software-engineering-in-sre/
- Kubernetes — Autoscaling Workloads: https://kubernetes.io/docs/concepts/workloads/autoscaling/
- Kubernetes — Horizontal Pod Autoscaling: https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/
- Kubernetes — Vertical Pod Autoscaling: https://kubernetes.io/docs/concepts/workloads/autoscaling/vertical-pod-autoscale/
- Kubernetes — Node Autoscaling: https://kubernetes.io/docs/concepts/cluster-administration/node-autoscaling/
- Kubernetes — Liveness, Readiness, and Startup Probes: https://kubernetes.io/docs/concepts/configuration/liveness-readiness-startup-probes/
- Kubernetes — Pod Lifecycle: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
- Kubernetes — Container Lifecycle Hooks: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/
- kubernetes/autoscaler — Cluster Autoscaler FAQ: https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md
- kubernetes/autoscaler — VPA README: https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/README.md
- kubernetes/autoscaler — VPA known limitations: https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/docs/known-limitations.md
- KEDA — Concepts: https://keda.sh/docs/2.18/concepts/
- KEDA — Scaling Deployments: https://keda.sh/docs/2.18/concepts/scaling-deployments/
- KEDA — ScaledObject specification: https://keda.sh/docs/2.18/reference/scaledobject-spec/
- KEDA — Redis Lists scaler: https://keda.sh/docs/2.18/scalers/redis-lists/
- AWS — Target tracking scaling policies: https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-target-tracking.html
- AWS — Step and simple scaling policies: https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html
- AWS — Scaling cooldowns: https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scaling-cooldowns.html
- AWS — Warm pools: https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html
- AWS — Predictive scaling: https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-predictive-scaling.html
- AWS — Scheduled scaling: https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html
- AWS — Spot Instances: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html
- AWS — EC2 Reserved Instances: https://aws.amazon.com/ec2/pricing/reserved-instances/
- AWS — Lambda pricing: https://aws.amazon.com/lambda/pricing/
- AWS — Lambda provisioned concurrency: https://docs.aws.amazon.com/lambda/latest/dg/provisioned-concurrency.html
- AWS — ALB sticky sessions: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html
- AWS — ALB target group attributes (deregistration delay): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/edit-target-group-attributes.html
- Redis — Cluster specification (16384 hash slots): https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/
- Laravel 13 — Octane: https://laravel.com/docs/13.x/octane
- Laravel 13 — Horizon: https://laravel.com/docs/13.x/horizon
- Laravel 13 — Deployment (health route, optimize): https://laravel.com/docs/13.x/deployment
- Laravel 13 — Session: https://laravel.com/docs/13.x/session
- Laravel 13 — Cache: https://laravel.com/docs/13.x/cache
- Laravel 13 — File Storage: https://laravel.com/docs/13.x/filesystem
- Laravel 13 — Service Container (
scoped): https://laravel.com/docs/13.x/container - Grafana k6 — Load test types: https://grafana.com/docs/k6/latest/testing-guides/test-types/
- Grafana k6 — Stress testing: https://grafana.com/docs/k6/latest/testing-guides/test-types/stress-testing/
- Grafana k6 — Ramping arrival rate executor: https://grafana.com/docs/k6/latest/using-k6/scenarios/executors/ramping-arrival-rate/
- wrk: https://github.com/wg/wrk
- vegeta: https://github.com/tsenart/vegeta
- Go —
net/http(Server.Shutdown): https://pkg.go.dev/net/http - Go —
os/signal(NotifyContext): https://pkg.go.dev/os/signal - Go 1.25 release notes (container-aware
GOMAXPROCS): https://go.dev/doc/go1.25 - Go —
github.com/redis/go-redis/v9: https://pkg.go.dev/github.com/redis/go-redis/v9