Scaling and Load Balancing
If we want to host our own application—e.g., an open-source Llama model or (as we’ll see below) an API wrapper around a GPT model—then we need to consider our system’s ability to scale and handle unpredictable loads.
In this lesson, we’ll discuss the basics of scaling and load balancing, and how these work with cloud platforms.
This Lesson Will Cover
- 📏 Horizontal vs Vertical Scaling
- ⚙️ Auto-Scaling Configurations
- 🔀 Load Balancers
- ☁️ Practical Example: Setting up a Load Balancer on Google Cloud
Horizontal VS Vertical Scalability
Horizontal and vertical scaling are the two fundamental approaches to handling an increased workload:
Vertical Scaling (Scale Up): Adds more power to existing resources (CPU, RAM, Storage)
- Limited by hardware capacity
- Usually requires downtime during upgrades
- Better for applications with state management requirements
Horizontal Scaling (Scale Out): Adds more instances of resources
- Virtually unlimited scaling potential
- No downtime during scaling
- Is simpler for stateless applications; stateful systems can also scale horizontally with shared state, partitioning or replication
- More complex to manage data consistency
Cloud Platform Scaling Support
Modern cloud-native applications prefer horizontal scaling for its reliability and cost-effectiveness, especially when building AI-powered services that need to handle variable workloads.
A simple example is AWS Lambda, which automatically scales by creating new function instances as requests come in. When your AI service receives more requests, Lambda instantaneously creates more execution environments to handle the load and scales back down when traffic decreases. This serverless approach means you only pay for actual compute time used, making it highly cost-effective for variable workloads.
On the other hand, vertical resizing can be a much simpler solution since it just involves changing the specifications of an existing instance—like upgrading from a small to a medium-sized VM. However, this approach has theoretically fixed upper limits based on available hardware configurations and can become quite expensive when dealing with high-end compute resources.
Here’s a table with some cloud platform services and the types of scaling they support:
| Service | Platform | Scaling Type | Notes |
|---|---|---|---|
| EC2 | AWS | Both | Vertical through instance resize, horizontal via Auto Scaling Groups |
| Lambda | AWS | Horizontal | Automatic scaling of function instances |
| ECS/EKS | AWS | Horizontal | Container orchestration with automatic scaling |
| App Engine | Google Cloud | Horizontal | Automatic scaling based on load |
| Compute Engine | Google Cloud | Both | Similar to EC2, supports both types |
| Cloud Functions | Google Cloud | Horizontal | Automatic scaling for serverless functions |
| Azure VMs | Azure | Both | Vertical through VM resize, horizontal with Scale Sets |
| Azure Functions | Azure | Horizontal | Automatic scaling for serverless workloads |
| Azure Container Apps | Azure | Horizontal | Kubernetes-based container scaling |
Auto-Scaling Configurations
Auto-scaling dynamically adjusts the number of resources (e.g., servers, containers) to match the current workload. This is especially beneficial for applications where resource demands can spike unpredictably.
Before we look at some examples, consider this list of services and deployment solutions that lack auto-scaling:
- Single VMs/Instances (traditional VM instances require manual scaling)
- Managed Databases (many require manual vertical scaling)
- Legacy On-Premises Applications (require manual intervention)
- Bare Metal Servers (physical hardware requires manual capacity planning)
* Note that cloud services offer solutions for auto-scaling these services, as discussed below.
Cloud Services with Auto-Scaling
AWS:
- EC2 Auto Scaling Groups: Scale EC2 instances based on CPU, memory, or custom metrics
- ECS: Auto-scales container tasks based on CPU/memory utilization
- EKS: Kubernetes-based pod auto-scaling using HPA (Horizontal Pod Autoscaler)
- Lambda: Automatic scaling of concurrent function executions
- Aurora: Auto-scales read replicas based on database load
Google Cloud:
- Compute Engine Instance Groups: Automatic VM scaling based on load metrics
- Google Kubernetes Engine (GKE): Native Kubernetes auto-scaling
- Cloud Run: Automatic container scaling based on request volume
- App Engine: Built-in auto-scaling for applications
- Cloud Functions: Automatic scaling of function instances
Azure:
- Virtual Machine Scale Sets: Auto-scales VM instances
- Azure Kubernetes Service (AKS): Kubernetes-based container scaling
- App Service: Built-in auto-scaling for web applications
- Azure Functions: Automatic scaling based on event triggers
- Azure Container Apps: Event-driven container scaling
Load Balancers
Load balancers distribute incoming requests across multiple servers to ensure high availability and reliability. They can also provide additional features like:
- SSL termination: (handling HTTPS encryption/decryption at the load balancer level)
- Health checks (monitoring backend server status and removing unhealthy instances)
Example: Setting Up a Load Balancer on Google Cloud
Let’s use the remainder of this lesson to walk through a practical example of configuring a load balancer for a Flask application on Google Cloud Platform.
This setup will create a highly available service that automatically distributes incoming traffic across multiple backend instances.
1. Flask Application (app.py)
from flask import Flask, jsonify
from openai import OpenAI
app = Flask(__name__)
client = OpenAI()
@app.route('/health')
def health():
return jsonify({"status": "healthy"})
@app.route('/generate/<text>')
def generate(text):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": text}]
)
return jsonify({"response": response.choices[0].message.content})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
2. Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY app.py .
CMD ["python", "app.py"]
3. Requirements (requirements.txt)
flask==3.1.0
openai==1.64.0
gunicorn==23.0.0
4. Startup Script (startup.sh)
#!/bin/bash
# Install Docker
apt-get update
apt-get install -y docker.io
# Pull and run the container
docker pull gcr.io/${PROJECT_ID}/ai-flask-app:latest
docker run -d -p 8080:8080 gcr.io/${PROJECT_ID}/ai-flask-app:latest
5. Build and Push Docker Image to Google Container Registry
# Build the image
docker build -t ai-flask-app .
# Tag the image
docker tag ai-flask-app gcr.io/${PROJECT_ID}/ai-flask-app:latest
# Push to Google Container Registry
docker push gcr.io/${PROJECT_ID}/ai-flask-app:latest
6. Setting Up Load Balancer with Python
from google.cloud import compute_v1
def create_load_balancer(project_id, region, instance_template_name):
# Create instance template
template_client = compute_v1.InstanceTemplatesClient()
template = compute_v1.InstanceTemplate(
name=instance_template_name,
properties=compute_v1.InstanceProperties(
machine_type="e2-medium",
metadata={
"items": [{
"key": "startup-script",
"value": open("startup.sh").read()
}]
},
disks=[{
"boot": True,
"auto_delete": True,
"initialize_params": {
"source_image": "projects/debian-cloud/global/images/debian-10"
}
}]
)
)
template_client.insert(project=project_id, instance_template_resource=template)
# Create managed instance group
instance_groups_client = compute_v1.InstanceGroupsClient()
group = compute_v1.InstanceGroup(
name="ai-service-group",
instance_template=f"projects/{project_id}/global/instanceTemplates/{instance_template_name}",
target_size=2 # Start with 2 instances
)
instance_groups_client.insert(
project=project_id,
zone=f"{region}-a",
instance_group_resource=group
)
# Create health check
health_client = compute_v1.HealthChecksClient()
health_check = compute_v1.HealthCheck(
name="http-health-check",
http_health_check=compute_v1.HTTPHealthCheck(
port=8080,
request_path="/health"
)
)
health_client.insert(project=project_id, health_check_resource=health_check)
# Create backend service
backend_client = compute_v1.BackendServicesClient()
backend_service = compute_v1.BackendService(
name="ai-backend-service",
health_checks=[f"projects/{project_id}/global/healthChecks/http-health-check"],
backends=[{
"group": f"projects/{project_id}/zones/{region}-a/instanceGroups/ai-service-group"
}]
)
backend_client.insert(project=project_id, backend_service_resource=backend_service)
How the Setup Works
-
Container Image:
- The Flask application is containerized and pushed to Google Container Registry.
- Each instance pulls and runs this container on startup.
-
Instance Template:
- Defines the VM configuration and startup script.
- Startup script automatically pulls and runs the container.
-
Instance Group:
- Creates multiple VM instances from the template.
- Handles auto-scaling based on load.
-
Health Checks:
- Regularly pings the
/healthendpoint. - Removes unhealthy instances from the load balancer.
- Regularly pings the
-
Load Balancer:
- Distributes traffic evenly across instances.
- Routes requests to healthy backend instances.
- Works with the managed instance group and autoscaler, which replace instances and adjust capacity.
- Provides SSL termination and security features.
[Google Cloud Load Balancer]
|
|
+------------------------+-----------------------+
| | |
[Instance 1] [Instance 2] [Instance 3]
Flask Container Flask Container Flask Container
(8080) (8080) (8080)
Conclusion
That was fun, eh?
Please excuse my Canadian-ness. Yes, we do actually say “eh”. The Japanese do something similar: “え”? (pronounced the same way!).
That was pretty interesting, eh?
I’ll see myself out.
Key Takeaways
⚖️ Horizontal scaling (adding instances) and vertical scaling (adding power) serve different use cases.
🔄 Auto-scaling is essential for AI services with variable workloads.
🌐 Load balancers ensure high availability and traffic distribution.
📦 Container-based deployments simplify scaling and load balancing.
✅ Health checks help maintain system reliability.
☁️ Cloud platforms enable cost-effective scaling by charging only for resources used.
Next: Infrastructure as Code
The next lesson is on infrastructure as code.
Comments (0)
No comments yet.