How to Mock Auto Scaling Policy Scale Out in Python

Define a mock auto-scaling function that scales out capacity by a factor up to a max, simulating AWS-like events.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

24 lines
Python 3.9+
def mock_scale_out(current_capacity: int, max_capacity: int, scale_factor: int = 1) -> tuple:
    """
    Mock auto-scaling policy: scales out by the specified factor
    if capacity allows, capped at max_capacity.
    """
    if current_capacity >= max_capacity:
        return current_capacity, False
    
    new_capacity = min(current_capacity + scale_factor, max_capacity)
    scaled_out = new_capacity > current_capacity
    return new_capacity, scaled_out

if __name__ == "__main__":
    # Simulate scale-out events
    initial_capacity = 3
    max_capacity = 5
    scale_factor = 2
    
    capacity = initial_capacity
    print(f"Initial capacity: {capacity}, Max: {max_capacity}")
    
    for event in range(3):
        capacity, scaled = mock_scale_out(capacity, max_capacity, scale_factor)
        print(f"Event {event + 1}: capacity={capacity}, scaled_out={scaled}")

Output

stdout
Initial capacity: 3, Max: 5
Event 1: capacity=5, scaled_out=True
Event 2: capacity=5, scaled_out=False
Event 3: capacity=5, scaled_out=False

How it works

The function checks if current capacity already meets or exceeds max capacity to avoid unnecessary scaling. It then computes the new capacity as the minimum of current plus scale factor and max capacity. The return tuple includes the updated capacity and a boolean indicating whether scaling actually occurred. This deterministic logic makes it easy to test and simulate scaling events without external dependencies.

Common mistakes

  • Forgetting to cap at max_capacity, causing overshoot
  • Not returning whether scaling occurred, making it hard to log events
  • Using a negative scale factor for scale-out by accident

Variations

  1. Use a dict to record event history, e.g., {event: capacity}
  2. Add a cooldown parameter to throttle consecutive scale-outs

Real-world use cases

  • Simulating EC2 Auto Scaling group scale-out behavior in a local dev test harness.
  • Validating capacity limit logic in a game server auto-scaler before deploying to production.
  • Unit-testing a custom scheduler that triggers scale-out events based on load metrics.

Sponsored

Run this sample

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

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.