If both conditions are met, the test passes, else fails.
However, note that sometimes we might have multiple SLOs and we might want to check all.
Let's design:
class SLO:
def init(self, availability=None, latency_p99=None, ...):
self.availability = availability # float between 0 and 1
self.latency_p99 = latency_p99 # in milliseconds
class ScenarioTemplate:
This can be an abstract base class. We'll have subclasses for each pattern.
code
We need a method that, given the current time (or iteration), returns the desired rate (requests per second) at that time.
Alternatively, we can have a generator that yields the next time to send a request, but that might be complex for variable rates.
Another approach: we can have a function that, for a given time t (in seconds from start), returns the rate at that time.
Then, in the load generator, we can adjust the sleep time between requests based on the current rate.
However, note that we want to be precise and also account for the time taken by the request itself.
A simpler method: we can pre-calculate the number of requests to send at each second (or smaller interval) and then schedule them.
But for flexibility, we can have:
rate_function(t) -> rate (requests per second) at time t.
Then, we can run a loop that:
- at each step, we check the current time and the desired rate at that time.
- we adjust the interval between requests accordingly.
However, if the rate is high, we might need to send multiple requests in parallel? Or we can use async.
Let's assume we are going to use asynchronous requests (aiohttp) or threads to achieve high rates.
We'll design the traffic shaper to be able to produce a stream of requests at the desired rate.
We can break the scenario into small time steps (e.g., 0.1 seconds) and for each step, we know how many requests to send.
Then we can schedule them within that step.
But note: we want to be able to change the rate smoothly, so we might not want to fix the step.
Alternatively, we can use a token bucket or leaky bucket algorithm to control the rate.
Given the complexity, let's assume we are going to run the test for a short duration (a few minutes) and we can pre-calculate the exact schedule.
However, for long duration tests, we might want to generate the schedule on the fly.
Let's keep it simple for now:
code
We'll have a function that, given the scenario parameters, returns a list of (time_offset, rate) for each second?
But then within a second, we need to spread the requests.
Alternatively, we can have:
code
total_duration: in seconds.
rate_function: a function that takes time (in seconds) and returns the rate at that time.
We'll generate requests in a loop that runs for total_duration.
We'll keep track of the current time and the next time we should send a request.
Steps for the load generator:
code
start_time = time.time()
next_request_time = start_time
while current_time < start_time + total_duration:
now = time.time()
if now >= next_request_time:
# We are due to send a request
# But note: the rate might have changed since we scheduled this request?
# We are using the rate at the time we schedule? Or at the time we send?
Actually, we want to follow the rate_function as closely as possible.
We can do:
Let current_rate = rate_function(now - start_time)
Then, the interval until next request should be 1/current_rate.
But if we are falling behind (because requests take time), we might need to adjust.
Alternatively, we can schedule the next request based on the current rate and the time we sent the last request.
Let last_request_time be the time we sent the last request.
Then, the ideal next request time = last_request_time + 1/current_rate.
But if we are behind, we might have to send multiple requests in quick succession to catch up?
That might not be desired because we want to simulate a steady rate.
Alternatively, we can use a fixed step and adjust the rate by sending multiple requests in a step?
Given the complexity, let's assume we are going to send one request at a time and adjust the sleep time.
However, if the rate is high (e.g., 1000 rps) then 1/1000 = 0.001 seconds, which is 1ms. We might not be able to sleep that accurately.
So for high rates, we might need to use a different approach (like asyncio and multiple concurrent requests).
Given the time, let's design for moderate rates (say up to 100 rps) and use a simple sleep.
But note: the request itself takes time. So if we want 100 rps, we need to send 100 requests per second, and each request must complete within 10ms on average?
Actually, if we send 100 requests in parallel, then each request can take up to 10ms and we still achieve 100 rps.
So for high rates, we need concurrency.
Considering the above, let's design two modes:
code
Mode 1: Sequential (for low rates) - we send one request at a time and sleep for the interval.
Mode 2: Concurrent (for high rates) - we use a thread pool or asyncio to send multiple requests in parallel.
But to keep the example simple, we'll stick to sequential for now and note that for high rates we need a different approach.
Alternatively, we can use a token bucket that is refilled at the desired rate, and we have multiple workers that take tokens and send requests.
Given the scope, let's do:
code
We'll have a TrafficShaper that, given a rate function and a total duration, will produce a stream of requests (or rather, will control when to send the next request).
We'll implement a simple version that uses a loop and adjusts the sleep time.
Steps for the sequential load generator:
code
start = time.time()
last_request_time = start
request_count = 0
while time.time() < start + total_duration:
now = time.time()
elapsed = now - start
# Get the current rate (requests per second) at this elapsed time.
current_rate = self.rate_function(elapsed)
# If current_rate is 0, then we don't want to send any request now, so sleep until the rate changes or until the end.
if current_rate == 0:
# How long to sleep? We can compute the next time when rate becomes non-zero?
# Alternatively, we can sleep for a short interval and recheck.
time.sleep(0.1)
continue
# The ideal time between requests at the current rate.
interval = 1.0 / current_rate
# If we are behind schedule (i.e., the time since last request is less than interval), then we wait until the interval has passed.
time_since_last = now - last_request_time
if time_since_last < interval:
time.sleep(interval - time_since_last)
# Now we send a request.
self.send_request()
last_request_time = time.time()
request_count += 1
However, note that if the rate changes very quickly, we might be using an outdated rate.
But we are recalculating the rate at the time we are about to send, so it's the current rate.
But note: we are using the rate at the time we decide to send, but then we sleep for the interval based on that rate.
If the rate changes during the sleep, then we are not following the new rate until the next iteration.
This might be acceptable for slowly changing rates.
For rapidly changing rates, we might want to adjust more frequently.
Given the complexity, we'll assume the rate function is piecewise constant (i.e., constant within each second) or changes slowly.
Now, let's define the scenario templates as rate functions.
Example:
code
ConstantScenario(rate) -> rate_function(t) = rate for all t.
RampUpScenario(start_rate, end_rate, duration) -> rate_function(t) = start_rate + (end_rate - start_rate) * (t / duration) for t <= duration, else end_rate.
SpikeScenario(base_rate, spike_rate, spike_start, spike_duration) ->
if t < spike_start: base_rate
elif t < spike_start + spike_duration: spike_rate
else: base_rate
We can have a class for each.
Now, the SLO evaluation:
code
We'll collect for each request:
- success (boolean)
- latency (in seconds)
After the test, we compute:
total_requests = len(successes)
successful_requests = sum(successes)
availability = successful_requests / total_requests if total_requests > 0 else 1
For latency, we sort the latencies and compute the percentiles.
Then, we check:
if self.slo.availability is not None:
if availability < self.slo.availability:
return False
if self.slo.latency_p99 is not None:
p99 = np.percentile(latencies, 99) # in seconds, but SLO is in milliseconds?
if p99 * 1000 > self.slo.latency_p99:
return False
Similarly for other percentiles.
Let's code:
code
We'll create:
class LoadGenerator:
def __init__(self, target, scenario, slo):
self.target = target # could be a URL or a function that sends a request and returns (success, latency)
self.scenario = scenario # an instance of a ScenarioTemplate (with a rate_function)
self.slo = slo # an instance of SLO
self.results = [] # list of (success, latency) tuples
def run(self):
# implement the traffic shaper as above, but instead of self.send_request(), we call a method that sends a request to the target and records the result.
pass
def evaluate(self):
# compute metrics and compare to SLO
pass
class ScenarioTemplate(ABC):
@abstractmethod
def rate_function(self, t):
pass
class ConstantScenario(ScenarioTemplate):
def __init__(self, rate):
self.rate = rate
def rate_function(self, t):
return self.rate
class RampUpScenario(ScenarioTemplate):
def __init__(self, start_rate, end_rate, duration):
self.start_rate = start_rate
self.end_rate = end_rate
self.duration = duration
def rate_function(self, t):
if t > self.duration:
return self.end_rate
return self.start_rate + (self.end_rate - self.start_rate) * (t / self.duration)
class SpikeScenario(ScenarioTemplate):
def __init__(self, base_rate, spike_rate, spike_start, spike_duration):
self.base_rate = base_rate
self.spike_rate = spike_rate
self.spike_start = spike_start
self.spike_duration = spike_duration
def rate_function(self, t):
if t < self.spike_start:
return self.base_rate
elif t < self.spike_start + self.spike_duration:
return self.spike_rate
else:
return self.base_rate
class SLO:
def __init__(self, availability=None, latency_p99=None, latency_p95=None, ...):
self.availability = availability
self.latency_p99 = latency_p99
self.latency_p95 = latency_p95
Then, in LoadGenerator.evaluate:
total = len(self.results)
successes = sum(1 for success, _ in self.results if success)
availability = successes / total if total > 0 else 1.0
latencies = [lat for _, lat in self.results]
# Calculate percentiles
p99 = np.percentile(latencies, 99) * 1000 # convert to ms
p95 = np.percentile(latencies, 95) * 1000
# Check each SLO condition that is set.
if self.slo.availability is not None and availability < self.slo.availability:
return False
if self.slo.latency_p99 is not None and p99 > self.slo.latency_p99:
return False
if self.slo.latency_p95 is not None and p95 > self.slo.latency_p95:
return False
return True
However, note that the SLO might have multiple conditions and we want to check all that are set.
Also, note that we might have a condition that the error rate must be below a threshold, which is 1 - availability.
We are using availability, but sometimes SLOs are defined in terms of error rate.
We can let the SLO have an error_rate threshold instead, but we can compute error_rate = 1 - availability.
Let's change the SLO to:
code
class SLO:
def __init__(self, error_rate=None, latency_p99=None, latency_p95=None, ...):
self.error_rate = error_rate # maximum allowed error rate (as a float, e.g., 0.001 for 0.1%)
self.latency_p99 = latency_p99
...
Then in evaluate:
code
error_rate = 1 - availability
if self.slo.error_rate is not None and error_rate > self.slo.error_rate:
return False
This is more flexible.
Now, about the target:
code
We can have the target as a function that we call to send a request.
Example:
def send_http_request(url, method='GET', body=None, headers=None):
start = time.time()
try:
response = requests.request(method, url, json=body, headers=headers)
success = response.status_code < 400
latency = time.time() - start
return success, latency
except Exception as e:
return False, time.time() - start
Then we can set:
generator = LoadGenerator(target=lambda: send_http_request('http://example.com'), scenario=..., slo=...)
But note: the target might have state (e.g., we want to vary the request body, or use different endpoints).
We can make the target function more complex, or we can have a generator that yields a function for each request.
However, for simplicity, we assume the target is fixed.
For more complex scenarios, we can have:
code
target: a function that takes the current time (or request index) and returns a tuple (method, url, body, headers) or a callable that sends the request.
But let's keep it simple: the target is a callable that sends a request and returns (success, latency).
We'll also need to handle timeouts, etc. in the target function.
Now, let's code the LoadGenerator.run method:
code
def run(self):
start_time = time.time()
last_request_time = start_time
self.results = []
while time.time() < start_time + self.scenario.total_duration:
now = time.time()
elapsed = now - start_time
current_rate = self.scenario.rate_function(elapsed)
if current_rate <= 0:
time.sleep(0.1)
continue
interval = 1.0 / current_rate
time_since_last = now - last_request_time
if time_since_last < interval:
time.sleep(interval - time_since_last)
# Send the request
try:
success, latency = self.target()
except Exception as e:
success = False
latency = time.time() - (last_request_time + interval) # approximate? We can record the start time inside the target.
self.results.append((success, latency))
last_request_time = time.time()
return self.results
However, note that the target function might take a variable amount of time.
In the above, we are sleeping until the next scheduled time, but then the request takes time, so the actual interval between the start of requests is interval + request_time.
This means that if the request time is significant, we are effectively reducing the rate.
We have two options:
code
1. We adjust the interval by the average request time? But the request time might vary.
2. We don't account for the request time and just use the interval as the time between the start of requests?
But then the actual rate will be lower because we are spending time in the request.
Actually, we want to achieve a certain request rate (requests per second).
The interval should be the time between the start of consecutive requests.
So we should schedule the next request based on the start time of the last request.
Let me adjust:
code
We want to send at time: last_request_start_time + interval.
But if the request takes time, then the next request will be delayed.
So we should set:
next_request_start_time = last_request_start_time + interval
Then, we wait until next_request_start_time.
But note: if the request takes longer than interval, then we are already behind and we should send the next request immediately?
That would mean we are trying to catch up, which might not be desired because we want to simulate a fixed rate.
Actually, if we want to simulate a fixed rate of 100 rps, we want to start 100 requests every second, regardless of how long they take.
So we should not wait for the request to finish to schedule the next one?
But then we might have too many concurrent requests.
Alternatively, we can have a fixed number of concurrent requests?
Given the complexity, let's assume we are sending one request at a time and we want the rate to be the rate at which we start requests.
So we do:
next_request_start_time = last_request_start_time + interval
Then, we wait until next_request_start_time, and then we start the request.
The request runs and we record the start time and the latency.
Then we set last_request_start_time to the time we started the request (which is next_request_start_time, or a bit later if we overslept).
But note: if the request takes longer than interval, then next_request_start_time will be in the past, so we won't sleep and we start the next request immediately.
That means we are trying to catch up, and the actual rate will be higher than desired?
Actually, if we are behind, we will start the next request as soon as the previous one finishes, which means the rate will be determined by the request time.
To maintain the desired rate, we should not let the request time affect the schedule. We should start requests at fixed intervals regardless of the request time.
But then we might have multiple requests in flight if the request time is longer than the interval.
So we need to handle concurrency.
Given the time, let's change the design:
code
We'll use a thread pool to send multiple requests in parallel, and we'll schedule the start times.
Alternatively, we can use asyncio.
Since this is a synthetic load generator, we want to generate a lot of load, so we need concurrency.
Let's redesign for concurrency:
code
We have a desired rate (requests per second). We want to start a certain number of requests per second.
We can break the total duration into small intervals (e.g., 0.1 seconds) and for each interval, we calculate how many requests to start.
Then we can schedule these requests to start at evenly spaced times within the interval.
But note: the scenario might change the rate every second, but we can break into smaller intervals.
Alternatively, we can use a token bucket:
We have a bucket that fills at the desired rate (tokens per second).
We have a pool of workers that, when they want to send a request, take a token.
If no token, they wait.
But then the rate is limited by the token generation.
However, we want to follow the scenario, which might change the rate every second.
We can have:
- A shared variable for the current rate (set by the scenario function at the current time).
- A token bucket that refills at the current rate? But the rate changes, so we need to adjust the refill rate.
Given the complexity, let's stick to the sequential version for now and note that for high rates we need a concurrent version.
Given the time constraints, we'll implement the sequential version and then discuss how to extend.
But note: the sequential version will be limited by the request time. For example, if the request takes 100ms, then the maximum rate we can achieve is 10 rps.
So for high rates, we must use concurrency.
Let's do:
code
We'll have a configurable concurrency level.
We'll have a queue of requests to send (with their scheduled start time).
We'll have a set of worker threads that:
- take a request from the queue (with the scheduled start time)
- wait until the scheduled start time
- send the request
- record the result
The main thread will generate the schedule and put the requests in the queue.
How to generate the schedule:
We break the total duration into small intervals (e.g., 0.01 seconds) and for each interval, we compute the number of requests to start in that interval.
Then, for each request in that interval, we schedule it at:
start_time = interval_start + (i + 0.5) * (interval_length / num_requests_in_interval)
But note: if the number of requests in an interval is high, we might not be able to schedule them all at exactly the same time?
We can spread them evenly.
Alternatively, we can generate the schedule by:
t = 0
while t < total_duration:
rate = scenario.rate_function(t)
if rate > 0:
interval = 1.0 / rate
# We schedule a request at time t, then t += interval
schedule.append(t)
t += interval
else:
# We skip until the rate becomes non-zero? But we need to check the rate function at every step.
# We can step in small steps.
t += 0.1
But then we have a list of scheduled start times.
Then we can assign these scheduled times to workers.
However, if the rate is high, the number of scheduled requests might be huge.
We can generate the schedule on the fly by the workers?
Given the complexity, let's stick to the sequential version for now and assume we are testing at low rates.
We'll change the LoadGenerator to have a concurrency parameter, and if concurrency > 1, we use a thread pool.
But to keep the example simple, we'll leave concurrency for future work.
So we'll implement the sequential version and note that it's for low rates.
Now, let's code:
We'll assume the scenario has a total_duration.
Steps:
code
class ScenarioTemplate(ABC):
def __init__(self, total_duration):
self.total_duration = total_duration
@abstractmethod
def rate_function(self, t):
pass
Then, in LoadGenerator.run, we use self.scenario.total_duration.
Let's code accordingly.
We'll also need to handle the case where the rate function returns a non-integer number of requests per second?
We are using it as a float, and then we compute the interval as 1/rate.
Example: if rate=0.5, then interval=2 seconds. We'll send a request every 2 seconds.
This is acceptable.
Now, what if the rate changes very quickly? Our method of using the current rate at the time of sending might not be accurate.
We are using the rate at the time we are about to send, but we scheduled the next send based on that rate and the last send time.
This should be okay for slowly changing rates.
For rapidly changing rates, we might need to adjust the schedule more frequently.
Given the time, we'll leave it as is.
Let's code the classes.
Note: We are using time.time() which returns seconds as a float.
We'll also record the start time of each request and the end time to compute latency.
We'll change the target function to return (success, latency) where latency is the time taken by the request.
But in the LoadGenerator, we are already measuring the time between requests?
Actually, we want the latency of the request, which is the time from when we send the request until we get the response.
So we should measure that inside the target function.
We'll change the target function to:
code
def target():
start = time.time()
# send the request
# get response
latency = time.time() - start
return success, latency
Then in LoadGenerator, we call target() and record the latency.
But note: the target function might block for the entire request time. So during that time, we are not scheduling the next request.
That's why for high rates we need concurrency.
We'll proceed with the sequential version.
Now, code:
Let's put it all together.
We'll also add some logging to see progress.
We'll also allow the scenario to have a warm-up period? Or we can have a separate warm-up scenario.
But let's keep it simple.
We'll also handle keyboard interrupt to stop the test.
Now, let's code.
I'll design a comprehensive synthetic load generator system tied to SLOs. This will be a modular, configurable framework that can simulate various traffic patterns while measuring against defined SLO thresholds.
The system ties synthetic load directly to business SLOs, enabling "SLO-driven load testing" where the test passes/fails based on actual service objectives rather than arbitrary request counts.
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Callable, Optional, Tuple
from datetime import datetime, timedelta
from enum import Enum
import asyncio
import time
import statistics
from dataclasses import dataclass, field
from collections import defaultdict, deque
# ================ SLO Definitions ================
class SLOType(Enum):
AVAILABILITY = "availability" # Success rate
LATENCY = "latency" # Response time percentiles
THROUGHPUT = "throughput" # Requests per second
ERROR_RATE = "error_rate" # Error percentage
CUSTOM = "custom" # Custom metric
@dataclass
class SLO:
"""Service Level Objective definition"""
name: str
slo_type: SLOType
target_value: float # e.g., 0.999 for 99.9% availability
measurement_window: timedelta # Window for measurement (e.g., 5 minutes)
threshold: float # Burn rate threshold for alerting
direction: str = "upper" # "upper" (latency) or "lower" (availability)
@dataclass
class SLOEvaluation:
"""Result of SLO evaluation"""
slo_name: str
current_value: float
target_value: float
passed: bool
burn_rate: float # Error budget consumption rate
error_budget_remaining: float
timestamp: datetime
# ================ Scenario Templates ================
class TrafficPattern(Enum):
CONSTANT = "constant"
RAMP_UP = "ramp_up"
RAMP_DOWN = "ramp_down"
SPIKE = "spike"
STAIRCASE = "staircase"
RANDOM = "random"
BURST = "burst"
SEASONAL = "seasonal"
DAY_IN_LIFE = "day_in_life" # Complex real-world pattern
@dataclass
class ScenarioConfig:
"""Configuration for a load scenario"""
name: str
pattern: TrafficPattern
duration: timedelta
base_rate: float # Base requests per second
peak_rate: Optional[float] = None # For spike/ramp patterns
ramp_duration: Optional[timedelta] = None
burst_size: Optional[int] = None
burst_interval: Optional[timedelta] = None
variance: float = 0.0 # Random variance (0-1)
seasonal_pattern: Optional[Callable[[float], float]] = None
warmup_period: timedelta = timedelta(seconds=30)
coolin_period: timedelta = timedelta(seconds=30)
# ================ Traffic Shaper ================
class TrafficShaper:
"""Generates traffic according to scenario patterns"""
def __init__(self, config: ScenarioConfig):
self.config = config
self.start_time = None
self.request_counter = 0
def get_target_rate(self, elapsed: float) -> float:
"""Calculate target RPS at given elapsed time"""
pattern = self.config.pattern
total_sec = self.config.duration.total_seconds()
normalized = elapsed / total_sec if total_sec > 0 else 0
if pattern == TrafficPattern.CONSTANT:
return self.config.base_rate
elif pattern == TrafficPattern.RAMP_UP:
if self.config.peak_rate is None:
return self.config.base_rate
ramp_sec = self.config.ramp_duration.total_seconds() if self.config.ramp_duration else total_sec
if elapsed <= ramp_sec:
progress = elapsed / ramp_sec
return self.config.base_rate + (self.config.peak_rate - self.config.base_rate) * progress
return self.config.peak_rate
elif pattern == TrafficPattern.SPIKE:
if self.config.peak_rate is None or self.config.ramp_duration is None:
return self.config.base_rate
spike_sec = self.config.ramp_duration.total_seconds()
# Single spike in middle
mid_point = total_sec / 2
if abs(elapsed - mid_point) < spike_sec / 2:
progress = 1 - abs(elapsed - mid_point) / (spike_sec / 2)
return self.config.base_rate + (self.config.peak_rate - self.config.base_rate) * progress
return self.config.base_rate
elif pattern == TrafficPattern.BURST:
if self.config.burst_size is None or self.config.burst_interval is None:
return self.config.base_rate
burst_interval_sec = self.config.burst_interval.total_seconds()
cycle_pos = elapsed % burst_interval_sec
burst_sec = min(5, burst_interval_sec * 0.1) # Burst lasts 10% of interval
if cycle_pos < burst_sec:
return self.config.base_rate * 10 # 10x burst
return self.config.base_rate
elif pattern == TrafficPattern.RANDOM:
import random
variance_factor = 1 + (random.random() * 2 - 1) * self.config.variance
return self.config.base_rate * variance_factor
return self.config.base_rate
def should_send_request(self) -> bool:
"""Determine if a request should be sent now"""
if self.start_time is None:
self.start_time = time.time()
elapsed = time.time() - self.start_time
# Check duration
if elapsed > self.config.duration.total_seconds():
return False
# Check warmup/cooling
if elapsed < self.config.warmup_period.total_seconds():
return True # During warmup, send at base rate
# Get target rate and calculate timing
target_rate = self.get_target_rate(elapsed)
ideal_interval = 1.0 / target_rate if target_rate > 0 else float('inf')
# Jitter for realism
jitter = ideal_interval * 0.1 * (hash(str(self.request_counter)) % 100 / 100)
adjusted_interval = ideal_interval + jitter
now = time.time()
time_since_last = now - getattr(self, '_last_request_time', now - adjusted_interval)
if time_since_last >= adjusted_interval:
self._last_request_time = now
self.request_counter += 1
return True
return False
# ================ Load Generator ================
@dataclass
class RequestMetrics:
"""Metrics for a single request"""
timestamp: float
latency_ms: float
success: bool
status_code: Optional[int] = None
error_message: Optional[str] = None
scenario_name: str = ""
class SyntheticLoadGenerator:
"""Main load generator class"""
def __init__(
self,
target_url: str,
request_generator: Callable[[], RequestMetrics],
slos: List[SLO],
scenario: ScenarioConfig
):
self.target_url = target_url
self.request_generator = request_generator
self.slos = slos
self.scenario = scenario
self.traffic_shaper = TrafficShaper(scenario)
# Metrics storage (with time windowing)
self.metrics: List[RequestMetrics] = []
self.slo_evaluations: List[SLOEvaluation] = []
self.error_budget_consumption: Dict[str, float] = defaultdict(float)
# Sliding window for SLO measurement
self.window_size = max(slo.measurement_window for slo in slos)
self.metrics_window: deque = deque(maxlen=int(self.window_size.total_seconds() * 1000))
async def run_async(self):
"""Run load test asynchronously"""
self.traffic_shaper.start_time = time.time()
end_time = self.traffic_shaper.start_time + self.scenario.duration.total_seconds()
print(f"Starting load test: {self.scenario.name}")
print(f"Pattern: {self.scenario.pattern.value}, Duration: {self.scenario.duration}")
print(f"Target: {self.target_url}")
try:
while time.time() < end_time:
if self.traffic_shaper.should_send_request():
await self._send_request_async()
else:
await asyncio.sleep(0.001) # Small sleep to prevent CPU spinning
except KeyboardInterrupt:
print("\nLoad test interrupted")
finally:
await self._finalize()
async def _send_request_async(self):
"""Send a single request (async version)"""
try:
start_time = time.time()
metric = await self.request_generator()
metric.timestamp = start_time
metric.latency_ms = (time.time() - start_time) * 1000
metric.scenario_name = self.scenario.name
self.metrics.append(metric)
self.metrics_window.append(metric)
except Exception as e:
metric = RequestMetrics(
timestamp=time.time(),
latency_ms=0,
success=False,
error_message=str(e)
)
self.metrics.append(metric)
self.metrics_window.append(metric)
def evaluate_slos(self) -> List[SLOEvaluation]:
"""Evaluate all SLOs against current metrics"""
evaluations = []
current_time = datetime.now()
for slo in self.slos:
window_metrics = self._get_window_metrics(slo.measurement_window)
if slo.slo_type == SLOType.AVAILABILITY:
value = self._calculate_availability(window_metrics)
passed = (value >= slo.target_value) if slo.direction == "lower" else (value <= slo.target_value)
elif slo.slo_type == SLOType.LATENCY:
value = self._calculate_latency_percentile(window_metrics, 99) # Default to p99
passed = (value <= slo.target_value) if slo.direction == "upper" else (value >= slo.target_value)
elif slo.slo_type == SLOType.ERROR_RATE:
value = 1 - self._calculate_availability(window_metrics)
passed = (value <= slo.target_value)
else:
continue
# Calculate burn rate (error budget consumption per second)
error_budget = 1 - slo.target_value if slo.slo_type != SLOType.LATENCY else slo.target_value
if len(window_metrics) > 0:
window_seconds = slo.measurement_window.total_seconds()
burn_rate = (1 - passed) / window_seconds if window_seconds > 0 else 0
self.error_budget_consumption[slo.name] += burn_rate * 60 # Per minute
evaluation = SLOEvaluation(
slo_name=slo.name,
current_value=value,
target_value=slo.target_value,
passed=passed,
burn_rate=burn_rate,
error_budget_remaining=max(0, 1 - self.error_budget_consumption[slo.name]),
timestamp=current_time
)
evaluations.append(evaluation)
self.slo_evaluations.append(evaluation)
return evaluations
def _get_window_metrics(self, window: timedelta) -> List[RequestMetrics]:
"""Get metrics within time window"""
cutoff_time = time.time() - window.total_seconds()
return [m for m in self.metrics_window if m.timestamp >= cutoff_time]
def _calculate_availability(self, metrics: List[RequestMetrics]) -> float:
"""Calculate availability = successful requests / total requests"""
if not metrics:
return 1.0
successful = sum(1 for m in metrics if m.success)
return successful / len(metrics)
def _calculate_latency_percentile(self, metrics: List[RequestMetrics], percentile: float) -> float:
"""Calculate latency percentile in milliseconds"""
latencies = [m.latency_ms for m in metrics if m.success]
if not latencies:
return 0.0
return statistics.quantiles(latencies, n=100)[int(percentile)-1]
async def _finalize(self):
"""Finalize test and generate report"""
evaluations = self.evaluate_slos()
self._generate_report(evaluations)
def _generate_report(self, evaluations: List[SLOEvaluation]):
"""Generate test report"""
print("\n" + "="*60)
print("LOAD TEST REPORT")
print("="*60)
print(f"Scenario: {self.scenario.name}")
print(f"Total Requests: {len(self.metrics)}")
print(f"Duration: {self.scenario.duration}")
print(f"Successful: {sum(1 for m in self.metrics if m.success)}")
print(f"Failed: {sum(1 for m in self.metrics if not m.success)}")
print("\nSLO Evaluations:")
print("-"*40)
all_passed = True
for eval in evaluations:
status = "✓ PASS" if eval.passed else "✗ FAIL"
print(f"{eval.slo_name}: {status}")
print(f" Target: {eval.target_value}, Current: {eval.current_value:.4f}")
print(f" Burn Rate: {eval.burn_rate:.6f}/sec")
print(f" Error Budget Remaining: {eval.error_budget_remaining:.2%}")
if not eval.passed:
all_passed = False
print("\n" + "="*60)
if all_passed:
print("OVERALL RESULT: ✓ PASSED")
else:
print("OVERALL RESULT: ✗ FAILED")
print("="*60)
return all_passed
# ================ Usage Example ================
async def example_request_generator():
"""Example request generator - replace with actual HTTP calls"""
await asyncio.sleep(0.01) # Simulate network latency
# Simulate 95% success rate
import random
success = random.random() > 0.05
status = 200 if success else random.choice([429, 500, 503])
return RequestMetrics(
timestamp=time.time(),
latency_ms=random.uniform(50, 500),
success=success,
status_code=status if success else status
)
async def main():
# Define SLOs
slos = [
SLO(
name="availability",
slo_type=SLOType.AVAILABILITY,
target_value=0.999, # 99.9%
measurement_window=timedelta(minutes=5),
threshold=0.001, # 0.1% error rate threshold
direction="lower"
),
SLO(
name="latency_p99",
slo_type=SLOType.LATENCY,
target_value=200.0, # 200ms p99
measurement_window=timedelta(minutes=5),
threshold=0.05, # 5% of requests exceeding
direction="upper"
)
]
# Define scenario
scenario = ScenarioConfig(
name="peak_traffic_test",
pattern=TrafficPattern.SPIKE,
duration=timedelta(minutes=10),
base_rate=100.0, # 100 RPS base
peak_rate=1000.0, # 1000 RPS spike
ramp_duration=timedelta(seconds=30),
variance=0.1
)
# Create and run generator
generator = SyntheticLoadGenerator(
target_url="https://api.example.com/endpoint",
request_generator=example_request_generator,
slos=slos,
scenario=scenario
)
await generator.run_async()
# You can also evaluate at any point
current_evaluations = generator.evaluate_slos()
for eval in current_evaluations:
print(f"{eval.slo_name}: {'PASS' if eval.passed else 'FAIL'}")
if __name__ == "__main__":
asyncio.run(main())