Approach: compute required instances based on throughput and per-request CPU; factor in CPU capacity per instance, add headroom percentage, round up to whole instances, and also compute instances required by memory and take the max. Support using average or p95 CPU per request.python
import math
def required_instances(target_rps,
cpu_per_request,
cpu_per_instance,
headroom_pct=20,
mem_per_request=None,
mem_per_instance=None,
percentile_label="avg"):
"""
Calculate required identical instances.
- target_rps: target requests/sec (int/float)
- cpu_per_request: CPU cores used per request (avg or p95)
- cpu_per_instance: CPU cores available per instance
- headroom_pct: percent extra capacity to reserve (e.g., 20)
- mem_per_request: memory bytes used per request (optional)
- mem_per_instance: memory bytes available per instance (optional)
- percentile_label: descriptive string for logs ("avg" or "p95")
Returns: dict with cpu_based, mem_based (if applicable), final_instances, notes
"""
if target_rps <= 0:
return {"final_instances": 0, "notes": "No traffic"}
# total CPU cores needed to handle requests concurrently per second:
total_cpu_needed = target_rps * cpu_per_request
# apply headroom
safety_multiplier = 1 + headroom_pct / 100.0
total_cpu_with_headroom = total_cpu_needed * safety_multiplier
# instances from CPU (round up)
instances_cpu = math.ceil(total_cpu_with_headroom / cpu_per_instance)
note = f"Calculated from {percentile_label} CPU per request."
result = {"cpu_based": instances_cpu, "notes": note}
# memory-based calculation (if data provided)
if mem_per_request is not None and mem_per_instance is not None:
total_mem_needed = target_rps * mem_per_request
total_mem_with_headroom = total_mem_needed * safety_multiplier
instances_mem = math.ceil(total_mem_with_headroom / mem_per_instance)
result["mem_based"] = instances_mem
final = max(instances_cpu, instances_mem)
result["final_instances"] = final
result["notes"] += " Memory considered; taking max of CPU and memory requirements."
else:
result["final_instances"] = instances_cpu
return result
Key points:- Use percentile (p95) when traffic spike safety is needed.- Headroom protects against bursts, background processes, scheduler overhead.- Rounds up with ceil to avoid under-provisioning.Complexity: O(1) time and space.Edge cases: zero/negative inputs, extremely small per-request CPU (ensure not zero), missing memory info, integer overflow for large numbers. Alternative: model concurrency per request duration (if requests overlap) by using per-request CPU*time instead of simple per-second multiplicative model.