Mock Kubernetes HPA CPU Scaling in Python

Python function that simulates CPU utilization and calculates desired replicas using the Kubernetes HPA formula.

Medium Python 3.9+ Aug 9, 2026 Production deployment patterns 14 views 0 copies

Python code

34 lines
Python 3.9+
import 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

stdout
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

  1. Use a for loop with explicit time.sleep() to simulate real-time monitoring intervals
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.