Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why scaling is a design decision, not a purchaseWhy it exists
Amdahl 1967, shared-nothing, Gunther, Conway, 12-factor, SREWhere it comes from
Bigger machine, more machines, bothVertical, Horizontal, Diagonal
The maths of diminishing returnsAmdahl's law, Universal Scalability Law
Making replicas interchangeableStateless design, Sticky sessions
Reads vs writes, per tierScaling reads, Scaling writes, Per tier, Database last
Autoscaling policies and their failure modesPolicies, Cooldowns and flapping, Kubernetes autoscalers, Cold starts
Replicas that can be killed safelyReadiness and graceful shutdown
How much spare capacityHeadroom and N+2
The billCost
Finding the limitLoad testing and the knee
Laravel specificsOctane and Horizon
TeamsConway's law
Formulas, knobs, defaults, eventsMechanics
CodeGo, Laravel
Classic failures and fixesSolving the classic problems
Which strategy, which autoscalerChoosing
Monolith to distributed systemIn architecture
Run itLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three directions.

StrategyIn plain wordsTiny exampleGives youCosts you
Vertical scaling (scale up)A bigger machinePostgreSQL primary from 8 to 32 vCPUNo code change, no coordinationCeiling, price curve, one failure domain, downtime to resize
Horizontal scaling (scale out)More machines of the same kind4 to 12 stateless API pods behind an AWS ALBNear-linear capacity, redundancy, autoscalingState must move out, load balancing, coordination tax
Diagonal scalingGrow each node to its sweet spot, then add nodesMove from 2-vCPU to 8-vCPU pods, then scale outBest cost per request, fewer nodes to coordinateTwo dimensions to tune
AutoscalingLet a controller change the count (or size)Kubernetes HPA on RPS per pod, min 3, max 40Pay for what you use, absorb peaksLag, flapping, cold starts, surprise bills

What usually scales which way, per tier.

TierDefault directionWhyWatch out for
CDN / edgeOut (provider does it)Cache hits never reach youCache misses on purge, see CDN
Load balancerOut (managed) or up (HAProxy/NGINX box)Mostly network-boundConnection limits, pre-warming for huge spikes
Web / API tierOut, autoscaledStateless by designSessions, local files, in-memory caches
Queue workersOut on queue depthJobs are independentOrdering, DB connections, idempotency
Cache (Redis)Up first, then out (Redis Cluster)Single-threaded command loop, memory-boundHot keys, resharding
Message brokerOut by partitions (Kafka), up per node (RabbitMQ queue)Throughput tied to partitions or queuesPartition count fixed in advance
Relational databaseUp first, then read replicas, shard lastWrites need one owner per rowReplica lag, connection count, cross-shard queries

The autoscaling toolbox.

ToolScalesOnReactionProduct
HPAPod countCPU, memory, custom, external metrics15 s loop + pod startKubernetes
VPAPod requests (size)Observed usageRestart or in-place resizeKubernetes add-on (CRD)
KEDAPod count, 0 to NQueue length, lag, cron and many other event sourcesPolls every 30 s by defaultCNCF project on top of HPA
Cluster Autoscaler / KarpenterNodesPending pods, unneeded nodesNode boot (minutes)Kubernetes
EC2 Auto ScalingInstancesTarget tracking, step, predictive, scheduledInstance boot, warm poolsAWS
Horizon balancingWorker processes per queue, on one hostQueue size or estimated time to clearbalanceCooldown secondsLaravel

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 changeCode 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 endPrice grows roughly linearly with nodes
Hard ceiling (largest instance)Ceiling set by the coordination tax (USL)
One failure domainRedundancy and rolling deploys come with it
Resize often means a restartAdd 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 ​

  1. "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.
  2. "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.
  3. "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.
text
     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 RAM

Real 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.

ProductVertical knobNote
AWS EC2Change instance typeRequires stop/start for EBS-backed instances
AWS RDS / AuroraModify DB instance classMulti-AZ applies it with a failover
KubernetesChange resources.requests/limits; VPAIn-place resize (VPA InPlaceOrRecreate/InPlace) avoids restarts where supported
RedisBigger node, maxmemoryCommand execution is single-threaded per node
PostgreSQLBigger box; shared_buffers, max_connections, work_memWrites 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.

text
     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 limit

Real 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.

ProductHorizontal knobThe shared part you must watch
Kubernetes Deploymentreplicas, HPADatabase connections, Redis, rate limits of third-party APIs
AWS EC2 Auto ScalingDesired capacity, min/maxSame, plus instance boot time
KafkaPartitions per topic, consumers per groupConsumers beyond partition count sit idle
Redis ClusterShards (16,384 hash slots)Multi-key operations need hash tags
PostgreSQLRead replicas, Citus shardsWrites 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.

Vertical (scale up)4 vCPU16 vCPU64 vCPU, 512 GBno code changeone failure domain, ceilingHorizontal (scale out)load balancerappappapp+1externalised stateRedis: session, cache, locksPostgreSQL + replicas, S3 for filesstateless replicas, N+1coordination tax, state moves downDiagonal1. grow2. clone at sweet spotfewer, larger nodesbest cost per request

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).

text
     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 connections

Real 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.

text
     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 reached

Real 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).

0k10k20k30k11632446496128nodes Nthroughput X(N), req/sUSL peak N*=44, 13.6klinear (ideal)Amdahl, sigma=0.03USL, kappa=0.0005retrograde: more nodes, less workcontention bends the curve; coherency turns it down
text
     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 rowCache invalidation broadcast to all peers
A global lock or mutexDistributed lock negotiation, consensus
One partition or one queueConsumer-group rebalances, gossip
A rate-limited third-party APICross-shard joins and scatter-gather
Connection pool limitsEvery 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.

text
     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).

StateWhere it should liveLaravel 13Go
SessionRedis / database / signed cookieSESSION_DRIVER=redis (drivers: file, cookie, database, memcached, redis, dynamodb, array)Cookie with an opaque id + go-redis
CacheRedis / MemcachedCACHE_STORE=redisgo-redis, local LRU only for safe-to-lose data
FilesObject storageFILESYSTEM_DISK=s3, Storage::disk('s3')AWS SDK for Go v2 S3 client
LocksRedis, database, etcdCache::lock()Redis SET NX PX, see Distributed Locking
JobsQueue (Redis, SQS, database)QUEUE_CONNECTION=redisA broker client
Config and secretsEnvironment / secret storeconfig:cache at deployos.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:

sql
-- 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.

text
     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 checkout

Real 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.

sql
-- 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();
text
     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 s

Real 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).

sql
-- 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;
text
     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 queue

Real 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.

text
     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)
TierScale up whenScale out whenProduct notes
Web / APIPer-request CPU is high and pods are tinyAlways the defaultKubernetes HPA, EC2 ASG, Laravel Octane workers per pod
Queue workersJobs are memory-heavyQueue depth or age growsKEDA, Horizon maxProcesses
RedisMemory or single-core CPU is the limitDataset or ops/s exceed one nodeRedis Cluster, ElastiCache cluster mode
KafkaDisk or NIC per broker is the limitPartitions and brokers can growPartition count is hard to reduce
RabbitMQOne queue is the bottleneckMany queues, spread over nodesQuorum queues replicate, they do not shard
PostgreSQL / MySQLAlmost always firstReads: 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 HPA averageUtilization or averageValue). 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 cron scaler, a Kubernetes CronJob that patches the HPA minReplicas).
  • 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).
text
     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 6

Real 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.

ProductReactiveStepPredictiveScheduled
AWS EC2 Auto ScalingTarget trackingStep / simpleYes (forecast)Yes (cron)
Kubernetes HPAResource, Pods, Object, External metricsVia behavior.policiesNo (third party)No (use KEDA cron or a CronJob)
KEDAScalers (queue, lag, Prometheus)Through HPA behaviorNocron scaler
Laravel HorizonQueue load per supervisorNoNoNo

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-HPA tolerance field in recent versions).
  • HPA stabilization window: the HPA uses the highest recommendation within the window before scaling down; default scaleDown.stabilizationWindowSeconds is 300; scaleUp has 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) and balanceMaxShift (processes per adjustment).
  • Hysteresis: different thresholds for up and down (scale up at 70%, down at 40%).
text
     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 starts

Real 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 container resources.requests. Scaling to and from zero with minReplicas: 0 is beta since Kubernetes v1.37 (HPAScaleToZero feature 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; Auto is deprecated since VPA 1.4.0 and is an alias for Recreate. 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; pollingInterval default 30 s, cooldownPeriod default 300 s, minReplicaCount default 0, maxReplicaCount default 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.
Metrics ServerCPU, memoryPrometheus Adaptercustom: RPS, p99KEDAqueue depth, 0 to NHPAceil(cur x metric/target)min/max, 10%, windowsreplicasDeploymentReplicaSetpodreadiness okpodPendingCluster Autoscaleror Karpenter: add nodeVPA (separate CRD)changes requests, not countresizescale-up: new pod gets trafficonly after readinessProbe passes;node boot + image pull + warm-upis the real reaction timeEvery 15 s: measure, compute, apply, then wait for capacity to exist
text
     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
yaml
# 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 } ]
yaml
# 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 jobs

Real 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.

text
     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 fill

Real 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.

0 s10 s25 s30 sdrain delay (preStop)still serving, readiness 503SIGTERM: Server.Shutdown(ctx 15 s)close listener, close idle, finish in-flightexit 0, marginSIGKILLpod Terminating: removed fromEndpointSlices, ALB target drainingLBs have stopped sendingWithout the delay, SIGTERM and endpoint removal race: the LB still routesto a closed listener and users see 502s during every scale-in and deploy.Rule: drain delay + shutdown timeout < terminationGracePeriodSeconds.
text
     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 reached

Real 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.

yaml
# 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 too

Fix / 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.

text
     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 peak

Real 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 requests from measured usage (VPA in Off mode 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).
text
     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 serverless

Real 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.

text
     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/s

Real 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.

text
     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.

text
     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 CDN

Real 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).

text
     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 shards

Real 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 ​

QuantityFormulaExample (σ = 0.03, κ = 0.0005)
Amdahl speedupS(N) = N / (1 + σ(N − 1))S(32) = 16.6
Amdahl ceiling1/σ33.3x
USL capacityC(N) = N / (1 + σ(N − 1) + κN(N − 1))C(32) = 13.2
USL peakN* = √((1 − σ)/κ)44.0
EfficiencyC(N)/N41% at N = 32
Fity = N/C − 1 = (σ + κ)x + κx², x = N − 1Least squares through the origin
Nodes needed for target XSmallest N with X(1)·C(N) ≥ X10,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 ​

KnobDefaultEffect
--horizontal-pod-autoscaler-sync-period15 sLoop period
--horizontal-pod-autoscaler-tolerance / spec.behavior.*.tolerance0.1Ignore ratio within ±10%
--horizontal-pod-autoscaler-downscale-stabilization / scaleDown.stabilizationWindowSeconds300 sHighest recommendation in window wins
scaleUp.stabilizationWindowSeconds0Scale up immediately
Default scaleUp policies100% or 4 pods per 15 s, selectPolicy: MaxMaximum growth rate
Default scaleDown policy100% per 15 s (after the window)Can drop to minReplicas
--horizontal-pod-autoscaler-cpu-initialization-period5 minIgnore CPU of pods that just started
--horizontal-pod-autoscaler-initial-readiness-delay30 sTreat recently started unready pods as not yet ready
minReplicas: 0Beta since v1.37 (HPAScaleToZero)Only with object/external metrics
Multiple metricsHighest desired count winsScale-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 ​

ProductKnobDefaultMeaning
KEDApollingInterval30 sHow often triggers are checked
KEDAcooldownPeriod300 sWait before scaling back to 0 (only 1→0)
KEDAminReplicaCount / maxReplicaCount0 / 100Bounds
KEDAidleReplicaCountignoredOnly 0 is supported
KEDAactivation* (for example activationListLength)0Threshold for 0↔1
Cluster Autoscaler--scale-down-unneeded-time10 minNode must be unneeded this long
Cluster Autoscaler--scale-down-delay-after-add10 minNo scale-down right after scale-up
Cluster Autoscaler--scale-down-utilization-threshold0.5Requests / allocatable below which a node may go
Cluster Autoscaler--scale-down-delay-after-failure3 minBack-off after a failed scale-down
Cluster Autoscaler--new-pod-scale-up-delay(unset)Ignore very young pending pods
EC2 Auto ScalingDefault cooldown (simple scaling)300 sPause after a simple-scaling activity
EC2 Auto ScalingInstance warmupGroup default instance warmupNew instances excluded from metrics until warm
EC2 Auto ScalingWarm pool stateStopped / Running / HibernatedPre-initialised instances
AWS ALBDeregistration delay300 sDraining time for a deregistering target
Kubernetes PodterminationGracePeriodSeconds30 sSIGTERM to SIGKILL
Laravel Octane--workers / --max-requests1 per CPU core / 500Workers per pod, restart to bound leaks
Laravel HorizonbalanceMaxShift / balanceCooldowndocs example: 1 / 3 sSpeed of rebalancing

Shutdown and capacity arithmetic ​

RuleFormulaExample
Grace budgetdrain delay + shutdown timeout + margin ≤ terminationGracePeriodSeconds10 + 15 + 5 = 30 s
Connection budgetmaxReplicas × pool size ≤ max_connections − reserve40 × 10 ≤ 500 − 50
Zone headroomtarget ≤ knee × (zones − 1)/zones3 zones, knee 90% → target ≤ 60%
N+2units = ceil(peak / per-unit breaking point) + 2ceil(19,000 / 5,000) + 2 = 6
Little's law for workersworkers ≥ arrival rate × job time50 jobs/s × 0.4 s = 20 workers
Queue drain timebacklog / (consumers × rate − arrival rate)200,000 / (3,000 − 2,000) = 200 s

Events and messages you will see ​

WhereMessage (verbatim)MeaningAction
Scheduler eventFailedScheduling ... Insufficient cpuNo node has room for the new podWait for Cluster Autoscaler or overprovision
Cluster Autoscaler eventTriggeredScaleUp / pod triggered scale-upA node group is growingExpect minutes
Cluster Autoscaler eventNotTriggerScaleUp / pod didn't trigger scale-up (it wouldn't fit if a new node is added)Pod is larger than any node templateFix requests or node groups
HPA conditionScalingActive falseHPA is not scaling (for example target at 0 with minReplicas > 0)Check metrics and targets
Go net/httphttp: Server closed (http.ErrServerClosed)Normal result of ShutdownTreat as success
PostgreSQLFATAL: sorry, too many clients alreadyReplicas × pool exceeded max_connectionsPgBouncer, smaller pools, lower maxReplicas
Load balancerHTTP 502 / 503 during scale-inRequests routed to a terminating podReadiness first, drain delay
Laravel/up returns 500Boot failed or a DiagnosingHealth listener threwLook 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.

go
// 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.

go
// 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.

go
// 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.

go
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.

go
// 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.

go
// 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
}
go
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.

go
// 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
}
go
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):

go
// 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 featureUse for scalingNote
http.Server.Shutdown(ctx)Graceful drainCloses listeners, then idle connections, waits for active ones; always pass a deadline
http.ErrServerClosedNormal exit of Serve after ShutdownDo not log it as an error
Server.RegisterOnShutdownTell WebSocket/hijacked connections to closeShutdown does not wait for them
signal.NotifyContextTurn SIGTERM into context cancellationKubernetes sends SIGTERM first
ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeoutBound per-connection costSlow clients otherwise pin goroutines
GOMAXPROCSMatch CPU limitsGo 1.25+ reads the container CPU limit by default; check your version
runtime/debug.SetMemoryLimit / GOMEMLIMITKeep GC under the pod memory limitAvoid OOM kills during spikes
sync/atomic.BoolReadiness flagCheap and race-free
database/sql SetMaxOpenConnsConnection budget per replicareplicas × max must fit the database
github.com/redis/go-redis/v9 PoolSizeRedis connections per replicaSame budget rule
net/http/pprof, runtime/traceFind σ (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
<?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
<?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)),
        ];
    }
}
bash
# .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, views

Octane-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
<?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
<?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
<?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
<?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
<?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
<?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,
            ],
        ],
    ],
];
yaml
# 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 featureRole in scalingNote
Session drivers (redis, database, memcached, dynamodb, cookie)Externalised sessionsDefault is database; file is single-server
CACHE_STORE=redisShared cache, Cache::lock()array and file stores are per process / per host
Storage::disk('s3'), temporaryUrl()Shared files, direct downloadsNeeds league/flysystem-aws-s3-v3
php artisan optimize / config:cacheFast boot for new replicasAfter caching, env() outside config returns null
/up health route, DiagnosingHealthLiveness / LB healthKeep listeners cheap
Octane (--workers, --max-requests, octane:reload)More throughput per podOne worker per core by default; restart after 500 requests
$this->app->scoped()Per-request instances under OctaneAvoid singletons capturing request/config
Octane cache (Swoole tables)Per-server cache shared by workersNot shared across replicas, flushed on restart
Horizon balance: auto, autoScalingStrategy, minProcesses, maxProcessesQueue autoscaling on one hostScale hosts with KEDA/ASG
horizon:terminateGraceful worker stopFinishes current jobs
Read/write DB connections with stickyRead replicas with read-your-writesSee Replication

Solving the classic problems ​

Users are logged out at random after adding a second server ​

SolutionHowAdvantageCost / limitation
Shared session storeRedis or database session driverAny server serves any userRedis becomes a dependency to make HA
Signed cookie sessionsLaravel cookie driver, JWT-like cookiesNo server stateSize limit (~4 KB), revocation is hard
Sticky sessionsALB AWSALB cookieNo code changeLost on scale-in, uneven load, a 12-factor violation

Prefer the shared store; keep stickiness off.

502s on every deploy and scale-in ​

SolutionHowAdvantageCost
Readiness first, then drainpreStop delay or app drain flag, then ShutdownNo dropped requestsSlower rollouts by ~10 s per pod
ALB deregistration delay tunedShorter than grace period for short requestsMatches app behaviourLong requests need a longer grace period
Connection draining in proxiesEnvoy/NGINX graceful reloadCovers the proxy tierConfiguration per proxy

The autoscaler flaps ​

SolutionHowAdvantageCost
Scale-down stabilizationstabilizationWindowSeconds: 300 or moreStops scale-in on dipsPays for idle pods a bit longer
Rate limits on scale-downPercent 10 per 60 sGentle shrinkSlower savings
Smoother metricRate over 2 minutes, not instantaneousLess noiseSlower reaction
HysteresisDifferent up/down thresholds (step scaling)PredictableMore policy to maintain

Scaling the API made the database fall over ​

SolutionHowAdvantageCost
Connection poolerPgBouncer, RDS ProxyThousands of clients → hundreds of server connectionsTransaction pooling breaks session features
Cap maxReplicas from the budgetmax_connections / poolNo surprise exhaustionA ceiling on app scale
Diagonal app tierFewer, larger podsFewer poolsCoarser scaling steps
Cache and replicasMove reads awayReal capacityStaleness

Autoscaling is too slow for spikes ​

SolutionHowAdvantageCost
Higher minimum + headroomminReplicas from N+2, CPU target 60%Instant capacityPaying for idle
Predictive / scheduled scalingAWS predictive policy, KEDA cronCapacity before the spikeNeeds regular patterns
Warm pools / overprovisioningEC2 warm pool, pause podsMinutes become secondsSome idle cost
Faster startSmaller images, Go/Octane, optimize, startupProbeEvery scale event gets fasterEngineering time
Load sheddingReject early while scalingProtects the healthy partSome 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 ​

SolutionHowAdvantageCost
KEDA on queue depthlistLength / lag target per replicaScales on the real signalNeeds metrics access
Horizon auto + more hostsBalance per host, scale hostsFair use of workersTwo levels to tune
Batch inside jobsProcess 50 items per jobHigher throughput per workerLarger retries
Priority splitSeparate supervisors for critical queuesPayments never starveMore processes

Choosing ​

Which direction ​

SituationRecommendationExtra techniqueReason
Stateless web/API tierScale out, autoscaleDiagonal sizing, N+2Cheap, redundant, elastic
Database primary under loadScale up firstPooling, caching, replicasNo design change, strong consistency
Read-heavy product (catalogue, news)CDN + cache + replicasRead-your-writes routingReads are copyable
Write-heavy ingestBatch + queue, then shardSharded countersWrites need an owner
Spiky queue workScale out workers on depthKEDA, scale to zeroJobs are independent
WebSocket / real-time tierScale out with connection-aware balancingPresence in Redis, reconnectConnections are state
One big in-memory jobScale upSpot + checkpointingCoordination would dominate
Throughput flat after adding nodesStop scaling out; reduce σ/κUSL fitRetrograde zone

Which autoscaler and metric ​

WorkloadAutoscalerMetricBounds and windows
HTTP API on KubernetesHPARPS per pod (custom), CPU as backupmin from N+2, max from DB budget, 5 min down window
Queue workers on KubernetesKEDAQueue length or lag per replicamin 0–1, cooldown 300 s
Laravel queues on one VMHorizon autoTime to clear (time)minProcesses for critical queues
EC2 web fleetASG target tracking + predictiveALBRequestCountPerTarget or CPUWarm pool for slow boots
Business-hours internal appScheduled scalingTimemin high by day, 0–1 at night
Pods with unknown sizesVPA Off → InitialUsage recommendationsNever with HPA on the same resource
NodesCluster Autoscaler or KarpenterPending podsOverprovision for the first step

Which pricing model ​

Capacity slicePricingWhy
Always-on baselineReserved Instances / Savings PlansUp to 72% off for steady use
Daily peakOn-demand, autoscaledPay only while needed
Retryable, statelessSpot across instance typesDeep discount; two-minute notice
Rare or spiky, smallServerless (Lambda) or scale to zeroNo 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 ​

LoadWeb/APIDataOperations
1x (100 req/s)2 replicas (N+1), statelessOne primary + standby, RedisHealth checks, graceful shutdown
10x (1,000 req/s)HPA 3..20, diagonal sizing, OctaneBigger primary, PgBouncer, 2 replicas, CDNLoad tests per release, USL fit, N+2
100x (10,000 req/s)Multiple node pools, predictive + reactive, warm capacityPartitioned tables, sharded writes, Redis Cluster, queues everywhereCost 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.

  1. Run the tests (stateless replicas sharing a store, readiness, drain, USL, HPA):
bash
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
  1. Print the page's numbers:
bash
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.

  1. Find the knee with an open-model test (k6 ramping-arrival-rate; expected, not run):
javascript
// 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
  1. Cross-check with vegeta (constant rate) and wrk (closed model) (expected, not run):
bash
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
  1. Watch the HPA and the drain on a cluster (expected, not run):
bash
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
  1. Measure the cold start (expected, not run): scale a deployment from 3 to 13 with kubectl scale, and record the time until kubectl get deploy shows 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 ​

BeliefReality
Horizontal scaling is always better than verticalFor stateful tiers, scale up first; scale out what is stateless
N nodes give N times the throughputContention bends the curve, coherence turns it down (USL)
Stateless means no stateState moves to Redis, the database and S3, which you must now scale
Sticky sessions are a fine fix for sessionsThey break on scale-in and deploys and skew load; 12-factor forbids relying on them
A read replica doubles database capacityOnly reads, with lag; every replica still replays every write
A queue increases write capacityIt absorbs bursts; average rate must still fit the consumers
Autoscaling replaces capacity planningIt reacts late; you still need headroom, bounds and load tests
HPA scaled up, so users are fineNew pods may be Pending until nodes arrive
Faster cooldowns are always betterFast scale-down causes flapping and repeated cold starts
Liveness probes should check the databaseThat restarts the whole fleet on a database blip
Kubernetes stops routing before SIGTERMEndpoint removal and SIGTERM race; add a drain delay
Scale to zero is freeThe first request pays the full cold start
Octane is just faster PHPIt keeps the app in memory; static and captured state leak across requests
Sharding early saves work laterIt freezes a shard key before you know the access patterns

Cheat sheet ​

TopicRemember
VerticalFirst for stateful tiers; ceiling, cost curve, NUMA, one failure domain
HorizontalNeeds statelessness or partitioning; pay the coordination tax
DiagonalRight-size the node, then multiply it
AmdahlN/(1+σ(N−1)), ceiling 1/σ
USLN/(1+σ(N−1)+κN(N−1)), peak √((1−σ)/κ), retrograde after
StatelessSessions → Redis/DB, files → S3, cache → shared, config → env
Sticky sessionsA smell for app state; OK only as a cache-locality hint
ReadsCDN → cache → replicas; design for staleness
WritesBatch → queue → shard
HPAceil(cur × metric/target), 15 s loop, 10% tolerance, 5 min down window
KEDAEvent metrics, 0↔1, poll 30 s, cooldown 300 s
NodesCluster Autoscaler / Karpenter react to Pending pods; minutes
Graceful shutdownReadiness 503 → delay → Shutdown(ctx) → exit before 30 s
HeadroomN+2 from the breaking point; ~60% CPU target across 3 zones
CostReserved for baseline, on-demand for peaks, spot for retryable, zero for idle
Load testOpen model (k6 arrival rate, vegeta); find the knee and the breaking point
LaravelOctane workers = cores, --max-requests, scoped(); Horizon auto + time

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Vertical scaling (scale up)Adding resources to one node
Horizontal scaling (scale out)Adding nodes that share the work
Diagonal scalingRight-sizing nodes, then adding more of them
Shared-nothingNodes share no memory or disk; they coordinate over the network
StatelessA process that keeps no data between requests
StatefulA process or tier that owns data across requests
Externalised stateSession, cache, files and locks kept in shared backing services
12-factorThe Twelve-Factor App methodology (processes, concurrency, disposability)
Sticky sessionLoad-balancer affinity binding a client to one backend
Amdahl's lawSpeedup limited by the serial fraction σ, ceiling 1/σ
Universal Scalability LawGunther's model adding coherence κ to Amdahl; has a peak
ContentionQueueing for a shared resource (σ)
Coherence / coordination costPairwise work to keep shared data consistent (κ)
Retrograde scalingThroughput falling as nodes are added past the peak
NUMANon-uniform memory access: local memory is faster than remote memory
Read replicaA copy of the database that serves reads, with lag
CacheA fast copy of data to serve repeated reads
CDNEdge caches that serve content close to users
ShardingSplitting data by key so each shard owns a slice of writes
QueueA buffer that decouples producers from consumers
BatchingCombining many small operations into one
AutoscalingA controller changing capacity from a metric
Target trackingKeep a metric at a target value (thermostat)
Step scalingAlarm bands mapped to fixed adjustments
Predictive scalingCapacity launched ahead of a forecast
Scheduled scalingCapacity changed at fixed times
CooldownA wait after a scaling action before the next
Stabilization windowHPA's look-back that picks the highest recommendation before scaling down
Flapping (thrashing)Capacity oscillating up and down
HPAKubernetes HorizontalPodAutoscaler (pod count)
VPAKubernetes VerticalPodAutoscaler (pod requests)
KEDAKubernetes Event-driven Autoscaling, including scale to zero
Cluster AutoscalerAdds or removes nodes for pending or unneeded pods
KarpenterNode provisioner that creates right-sized nodes for pending pods
Warm poolPre-initialised instances ready to join an Auto Scaling group
Scale to zeroRunning no replicas when idle
Cold startTime from requesting capacity to serving at full speed
Readiness probeCheck that decides whether a pod receives traffic
Liveness probeCheck that decides whether a container is restarted
Graceful shutdownStop accepting, finish in-flight work, then exit
HeadroomCapacity above expected peak
N+1 redundancyPeak served with one unit lost
N+2Peak served with two units lost (planned + unplanned)
Right-sizingMatching instance types and requests to real usage
Spot instanceDiscounted spare capacity that can be interrupted with notice
Reserved instanceDiscount for a one- or three-year commitment
Load testingGenerating traffic to measure limits
k6Load-testing tool with open-model executors
wrkClosed-model HTTP benchmarking tool
vegetaConstant-rate HTTP load tool
KneeThe load where latency starts rising much faster than throughput
ThroughputRequests completed per unit of time
SaturationHow full a resource is (CPU, connections, queue)
OctaneLaravel's long-running application server integration
Horizon balanceHorizon's worker balancing strategy (auto, simple, false)
Conway's lawSystems mirror the communication structure of their organisation

References ​

Built by Morteza Negahi