037 Project 37: Kubernetes HPA Simulator
037 Build a Kubernetes HPA Simulator
Simulate replica scaling from CPU load over time.
Full main.go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
replicas := 2
targetCPU := 60.0
for t := 1; t <= 30; t++ {
cpu := 30 + rand.Float64()*70
if cpu > targetCPU+10 && replicas < 20 {
replicas++
} else if cpu < targetCPU-20 && replicas > 1 {
replicas--
}
fmt.Printf("tick=%02d cpu=%5.1f%% replicas=%d\n", t, cpu, replicas)
time.Sleep(150 * time.Millisecond)
}
}Step-by-Step Explanation
- Model desired and actual state explicitly.
- Compute a minimal diff.
- Apply one idempotent reconciliation step.
- Observe updated state and repeat.
- Keep loops convergent and failure-aware.
Code Anatomy
- State model captures control-plane truth.
- Reconcile function decides next action.
- Loop executes continuously with visibility into actions.
Learning Goals
- Learn the controller pattern used in modern platforms.
- Build robust automation through repeated reconciliation.
- Understand convergence over one-shot scripting.