Infrastructure Scaling
Capacity Planning
ML-powered demand forecasting with predictive auto-scaling, achieving 99.9% capacity SLA while reducing infrastructure costs by 28%.
35%
Capacity Headroom
94%
Forecast Accuracy
47
Scale Events/Day
28%
Cost Savings
ML Demand Forecasting
Prophet-based time series forecasting with seasonality detection and trend analysis for accurate capacity planning.
# capacity_planning/forecasting.py
import pandas as pd
from prophet import Prophet
from dataclasses import dataclass
from typing import List, Dict, Tuple
import numpy as np
@dataclass
class ForecastResult:
timestamp: pd.Timestamp
predicted_load: float
lower_bound: float
upper_bound: float
confidence: float
class DemandForecaster:
"""
ML-powered demand forecasting using
Prophet with custom seasonality.
"""
def __init__(self):
self.model = None
self.seasonality_config = {
"weekly": True,
"daily": True,
"yearly": True,
"custom": [
{"name": "monthly_sales", "period": 30.5, "fourier_order": 5},
{"name": "end_of_quarter", "period": 91.25, "fourier_order": 3}
]
}
def train(
self,
historical_data: pd.DataFrame,
metric: str = "request_rate"
) -> None:
"""
Train forecasting model on
historical load data.
"""
# Prepare data for Prophet
df = historical_data[["timestamp", metric]].copy()
df.columns = ["ds", "y"]
# Initialize Prophet with tuned hyperparameters
self.model = Prophet(
changepoint_prior_scale=0.05,
seasonality_prior_scale=10,
holidays_prior_scale=10,
seasonality_mode="multiplicative",
interval_width=0.95
)
# Add custom seasonality
for custom in self.seasonality_config["custom"]:
self.model.add_seasonality(
name=custom["name"],
period=custom["period"],
fourier_order=custom["fourier_order"]
)
# Add special events (sales, launches)
self.model.add_country_holidays(country_name="US")
# Fit model
self.model.fit(df)
def forecast(
self,
horizon_hours: int = 168, # 1 week
granularity_minutes: int = 15
) -> List[ForecastResult]:
"""
Generate demand forecast for
specified time horizon.
"""
if not self.model:
raise ValueError("Model not trained. Call train() first.")
# Create future dataframe
periods = (horizon_hours * 60) // granularity_minutes
future = self.model.make_future_dataframe(
periods=periods,
freq=f"{granularity_minutes}min"
)
# Generate predictions
forecast = self.model.predict(future)
# Extract results for future dates
results = []
for _, row in forecast.tail(periods).iterrows():
results.append(ForecastResult(
timestamp=row["ds"],
predicted_load=max(0, row["yhat"]),
lower_bound=max(0, row["yhat_lower"]),
upper_bound=row["yhat_upper"],
confidence=0.95
))
return results
def detect_anomalies(
self,
actual_data: pd.DataFrame,
threshold_std: float = 3.0
) -> List[Dict]:
"""
Detect load anomalies by comparing
actual vs predicted values.
"""
predictions = self.model.predict(actual_data[["ds"]])
residuals = actual_data["y"] - predictions["yhat"]
std = residuals.std()
anomalies = []
for i, (_, row) in enumerate(actual_data.iterrows()):
if abs(residuals.iloc[i]) > threshold_std * std:
anomalies.append({
"timestamp": row["ds"],
"actual": row["y"],
"predicted": predictions["yhat"].iloc[i],
"deviation_std": residuals.iloc[i] / std
})
return anomalies7-Day Forecast
Monday
Avg: 4.2M reqPeak: 6.1M2-4 PM
Tuesday
Avg: 4.5M reqPeak: 6.8M1-3 PM
Wednesday
Avg: 4.8M reqPeak: 7.2M12-2 PM
Thursday
Avg: 4.6M reqPeak: 6.9M2-4 PM
Friday
Avg: 5.2M reqPeak: 8.1M11AM-1PM
Saturday
Avg: 3.8M reqPeak: 5.4M10AM-12PM
Sunday
Avg: 3.2M reqPeak: 4.6M6-8 PM
Detected Seasonality
Daily
Peak:1-3 PM
Trough:3-5 AM
Variance:+180%
Weekly
Peak:Friday
Trough:Sunday
Variance:+45%
Monthly
Peak:End of month
Trough:Mid-month
Variance:+25%
Quarterly
Peak:Q4 (Holiday)
Trough:Q1
Variance:+120%
Scale with Confidence
Predictive capacity planning that grows with your business.
94% Forecast Accuracy28% Cost Reduction99.9% Capacity SLA