How to plan reserved capacity from a CSV in Python
Read a CSV of workloads with csv.DictReader and compute a mock reserved capacity plan with headroom per service.
Python code
32 linesimport csv
import io
def plan_reserved_capacity(workloads_csv: str) -> list[dict]:
"""Read a CSV of workloads and return a plan for reserved capacity per service."""
reader = csv.DictReader(io.StringIO(workloads_csv))
plan = []
for row in reader:
service = row["service"]
avg_load = float(row["avg_load"])
peak_load = float(row["peak_load"])
# Mock rule: reserve 80% of peak load, never below average load
reserved = max(avg_load, peak_load * 0.8)
plan.append({
"service": service,
"reserved_capacity": round(reserved, 1),
"headroom": round(peak_load - reserved, 1),
})
return plan
if __name__ == "__main__":
sample_csv = (
"service,avg_load,peak_load\n"
"api-gateway,42,58\n"
"auth,15,25\n"
"reporting,80,120\n"
)
result = plan_reserved_capacity(sample_csv)
for item in result:
print(f"{item['service']}: reserved={item['reserved_capacity']}, headroom={item['headroom']}")
Output
api-gateway: reserved=46.4, headroom=11.6
auth: reserved=20.0, headroom=5.0
reporting: reserved=96.0, headroom=24.0
How it works
csv.DictReader turns each CSV row into a dictionary keyed by the header row, so you can access columns by name instead of index. The mock rule reserves 80% of the peak load but never less than the average load using max(). Converting the string values with float() lets you do arithmetic safely. io.StringIO wraps the CSV text so DictReader can consume it as a file-like object without writing to disk. The output shows per-service reserved capacity plus the remaining headroom, which is the difference between peak and reserved.
Common mistakes
- Forgetting to convert string numbers with float() before doing arithmetic
- Assuming the CSV always has the expected column headers, causing KeyError
- Using a file path directly instead of wrapping the CSV string with io.StringIO
Variations
- Read from an actual file with `open('workloads.csv')` instead of a string
- Use `pandas.read_csv` for more complex data processing and analytics
Real-world use cases
- Determining how much Amazon EC2 Reserved Capacity to purchase for a service based on historical peak usage.
- Planning Kubernetes cluster node reservations by feeding a CSV of pod load metrics into a capacity planner script.
- Generating infrastructure budget reports that show reserved vs. on-demand compute headroom for finance review.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.