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.

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

Python code

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

stdout
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

  1. Read from an actual file with `open('workloads.csv')` instead of a string
  2. 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

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.