Mock Kubernetes HPA CPU Scaling in Python
Python function that simulates CPU utilization and calculates desired replicas using the Kubernetes HPA formula.
Python code
34 linesimport random
import time
def simulate_cpu_utilization(target_utilization=50, samples=10):
"""Simulate CPU utilization readings for HPA mock."""
utilizations = []
for _ in range(samples):
# Simulate fluctuating CPU with random noise around target
current = target_utilization + random.uniform(-20, 20)
# Clamp between 0 and 100
current = max(0.0, min(100.0, current))
utilizations.append(round(current, 2))
return utilizations
def calculate_hpa_replicas(current_replicas, current_utilization, target_utilization):
"""Calculate desired replicas similar to Kubernetes HPA formula."""
if current_utilization == 0:
return max(1, current_replicas)
ratio = current_utilization / target_utilization
desired_replicas = current_replicas * ratio
return max(1, int(desired_replicas + 0.5)) # round up
if __name__ == "__main__":
replicas = 3
target = 50
cpu_samples = simulate_cpu_utilization(target, samples=5)
print(f"CPU samples: {cpu_samples}")
for cpu in cpu_samples:
desired = calculate_hpa_replicas(replicas, cpu, target)
print(f"CPU={cpu}% -> replicas: {desired}")
replicas = desired
Output
CPU samples: [63.42, 45.18, 52.87, 38.24, 61.09]
CPU=63.42% -> replicas: 4
CPU=45.18% -> replicas: 4
CPU=52.87% -> replicas: 4
CPU=38.24% -> replicas: 3
CPU=61.09% -> replicas: 4
How it works
The simulate_cpu_utilization function generates realistic CPU readings by adding random noise around a target value and clamping results to 0-100%. The calculate_hpa_replicas function mirrors Kubernetes HPA behavior by computing the utilization ratio and multiplying by current replicas, rounding up to ensure capacity. This mock helps developers test autoscaling logic without a live cluster. The iterative loop updates replicas based on each sample, demonstrating how HPA reacts to changing load over time.
Common mistakes
- Forgetting to clamp CPU utilization to 0-100% range
- Using integer division instead of float division for accurate ratio calculation
- Not rounding up desired replicas, causing under-provisioning
Variations
- Use a for loop with explicit time.sleep() to simulate real-time monitoring intervals
- Add a smoothing factor to prevent replica flapping between samples
Real-world use cases
- Unit testing HPA configs and scaling policies before deploying to a Kubernetes cluster.
- Developing capacity planning dashboards that need realistic autoscaling simulation.
- Teaching Kubernetes autoscaling concepts in training environments without cluster access.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.