Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Capacity Planning

Module 7 Lesson 7.d 50 min Difficulty 3/5

Prerequisites 7.a, 3.a

The idea in one minute#

Capacity planning answers: how much do we need, and by when? It combines four things: a forecast of demand (organic growth plus known events — launches, sales, seasons), a measured cost of serving one unit of demand (from load tests and production data), headroom for failures and surprises (N+2, zone loss, a target utilisation), and the lead time to get more (seconds for autoscaling, weeks for quota increases, months for hardware).

Autoscaling handles the minute-to-minute shape. It does not handle quotas, databases, licences, budgets, or the day the autoscaler itself is the bottleneck. Someone still has to plan.

An analogy#

A city’s water supply. Daily usage goes up and down (autoscaling: valves), but someone has to forecast population growth, plan for droughts and fires (headroom), and start building the new reservoir years before it is needed (lead time).

A picture#

flowchart LR
  H[":i-activity: <b>History</b><br/><small>weekly peaks</small>"] --> F["Forecast<br/><small>trend + seasonality + events</small>"]
  E[":i-file-text: <b>Known events</b><br/><small>launches, sales, migrations</small>"] --> F
  F --> D["Peak demand<br/><small>req/s in 6–12 months</small>"]
  LT[":i-gauge: <b>Load test</b><br/><small>req/s per instance at SLO</small>"] --> N["Instances needed"]
  D --> N
  N --> HR["+ headroom<br/><small>zone loss, N+2, target util</small>"]
  HR --> P[":i-coins: <b>Plan</b><br/><small>quota, budget, order by lead time</small>"]
  class H,E neutral
  class F,D queue
  class LT compute
  class N,HR memory
  class P io

How it really works#

Step 1 — forecast demand#

  • Use peaks, not averages: plan for the busiest minute of the busiest day of the week (often the busiest week of the year).
  • Separate organic growth (a trend: +4% a month) from inorganic events (a marketing campaign, a new country, a big customer, Black Friday). Get the event calendar from the product and business side.
  • Model seasonality: weekday/weekend, time of day, holidays, month-end.
  • A simple linear or log-linear fit on weekly peaks is often enough for 6–12 months; tools like Prophet help with seasonality. Always show a range, not a single line.

Step 2 — measure the cost of demand#

Turn demand into resources with a unit cost from load tests (7.f) and production:

one instance (4 vCPU) serves 450 req/s at p99 < 300 ms (the SLO), at 70% CPU

Measure each constrained resource: CPU, memory, database connections, IOPS, network, licence counts, third-party rate limits. The one that runs out first is the one you plan.

Watch efficiency drift: every release changes the cost per request. Track req/s per core over time; a 20% regression is a 20% capacity loss nobody planned for.

Step 3 — add headroom#

Headroom forTypical allowance
Losing a zone (3 zones)+50% (7.a)
N+2: one failure during maintenance+2 instances per pool
Target utilisation below saturation (7.e)Plan to run at 60–70% of measured max at peak
Forecast error+10–25%, depending on how good the forecast has been
Sudden spikes (viral, bots)Load shedding (6.d) rather than capacity

Step 4 — respect lead times#

ResourceLead time
Pod autoscaling (HPA)Seconds–minutes (plus image pull and warm-up)
Node autoscaling (Cluster Autoscaler, Karpenter)1–5 minutes, if capacity is available in the zone
Cloud quota increaseHours to weeks
Reserved capacity / committed use discountsWeeks of finance approval
Bigger database instance, reshardingDays to months of engineering
Own hardwareMonths

Plan so that demand × headroom stays below what can be obtained within the lead time.

Autoscaling is part of the plan, not the plan#

  • Scale on a signal that predicts load: requests per second or concurrency per pod, rather than CPU alone. KEDA scales on queue length and other external metrics.
  • Set minimum replicas high enough to absorb a spike while the autoscaler reacts, and enough to survive a zone loss.
  • Set maximum replicas to protect downstream dependencies (the database cannot scale like the stateless tier).
  • Schedule pre-scaling before known events.

A worked example#

Checkout traffic: weekly peaks over the last 26 weeks grew from ~2,100 to ~3,000 req/s. Black Friday, in 20 weeks, historically peaks at 3.2× a normal week’s peak.

  1. Forecast: a linear fit gives +36 req/s per week; in 20 weeks a normal-week peak of about 3,700 req/s. Black Friday: 3.2 × 3,700 ≈ 11,900 req/s.
  2. Unit cost: 450 req/s per instance at SLO.
  3. Headroom: 3 zones (×1.5), target 70% of max (÷0.7), forecast error 15% (×1.15).
  4. Instances: 11,900 / 450 × 1.5 / 0.7 × 1.15 ≈ 65 instances, versus 24 today — fine, that is minutes of autoscaling (with the maximum replica count raised in advance).
  5. Other resources: checkout makes 1.4 database queries per request, so Black Friday needs about 16,700 QPS against today’s 9,000 — and with the same headroom, about 4.6× today’s database capacity. The payment provider’s transaction quota is short too. The database and the quota are the bottlenecks, with lead times of weeks. Start now: read replicas, caching for catalogue lookups, and a quota request to the provider.

Code#

Go
// capacity.go — forecast weekly peaks with a linear fit, then size instances with headroom.
package main

import (
	"fmt"
	"math"
)

func linearFit(ys []float64) (slope, intercept, rmse float64) {
	n := float64(len(ys))
	var sx, sy, sxx, sxy float64
	for i, y := range ys {
		x := float64(i)
		sx, sy, sxx, sxy = sx+x, sy+y, sxx+x*x, sxy+x*y
	}
	slope = (n*sxy - sx*sy) / (n*sxx - sx*sx)
	intercept = (sy - slope*sx) / n
	for i, y := range ys {
		e := y - (intercept + slope*float64(i))
		rmse += e * e
	}
	return slope, intercept, math.Sqrt(rmse / n)
}

func main() {
	// 26 weeks of peak req/s (with noise).
	peaks := []float64{2100, 2150, 2080, 2230, 2260, 2240, 2330, 2380, 2350, 2420, 2490, 2460, 2530,
		2580, 2560, 2650, 2690, 2700, 2740, 2790, 2820, 2860, 2850, 2930, 2960, 3010}
	slope, icpt, rmse := linearFit(peaks)
	fmt.Printf("trend: +%.0f req/s per week (%.1f%%/week), fit error ±%.0f\n", slope, 100*slope/peaks[len(peaks)-1], rmse)

	const weeksAhead = 20
	x := float64(len(peaks) - 1 + weeksAhead)
	normal := icpt + slope*x
	const eventMultiplier = 3.2 // Black Friday vs a normal week's peak
	event := normal * eventMultiplier
	fmt.Printf("in %d weeks: normal peak %.0f req/s, Black Friday %.0f req/s\n\n", weeksAhead, normal, event)

	type resource struct {
		name     string
		perUnit  float64 // demand units one unit of resource serves at SLO
		demandX  float64 // resource demand per request
		current  float64
		leadTime string
	}
	const zoneFactor, targetUtil, forecastErr = 1.5, 0.7, 1.15
	res := []resource{
		{"app instances", 450, 1, 24, "minutes (autoscaling)"},
		{"DB QPS (primary + replicas)", 9000, 1.4, 1, "weeks"},
		{"payment provider TPS quota", 1500, 0.12, 1, "2–4 weeks (contract)"},
	}
	fmt.Printf("%-30s %10s %10s %8s  %s\n", "resource", "needed", "have", "ok?", "lead time")
	for _, r := range res {
		need := event * r.demandX / r.perUnit * zoneFactor / targetUtil * forecastErr
		have := r.current
		ok := "yes"
		if need > have {
			ok = "NO"
		}
		unit := "units"
		if r.name == "app instances" {
			unit = "inst"
		}
		fmt.Printf("%-30s %7.1f %-3s %7.0f %-3s %5s  %s\n", r.name, need, unit, have, unit, ok, r.leadTime)
	}
	fmt.Println("\n(DB and quota rows are in multiples of today's capacity.)")
}

Remember this#

  • Forecast peaks: organic trend plus known events plus seasonality, with a range.
  • Measure the unit cost of each constrained resource at SLO; watch for efficiency regressions.
  • Add headroom for zone loss, N+2, target utilisation and forecast error; shed spikes rather than buy for them.
  • Plan by lead time: the resource with the longest lead time is the one to start on.
  • Autoscaling handles the shape, not the plan; set minimums for zone loss and maximums for dependencies.

Try it#

  1. Run capacity.go. Set eventMultiplier to 2. Which resource is still short?
  2. Collect 12 weeks of peak traffic for a service you know and fit a trend. How wide is the error?
  3. List every non-autoscaling limit in your request path (quotas, connection limits, licences).

Check yourself#

  1. Why plan on peaks rather than averages?
  2. What is “efficiency drift”, and why does it matter for capacity?
  3. Why is the database usually the planning bottleneck rather than the stateless tier?
  4. What should the minimum replica count of an autoscaled service be based on?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in