The user wants to build a continuous verification pipeline for Service Level Objectives (SLOs).
Key requirements:
- Continuous Verification: It's an ongoing process, not a one-off.
- Service Level Objectives (SLOs): The verification criteria are based on SLOs (e.g., latency, error rate, availability).
- Replay Production Traces: The input data comes from actual production traffic (captured traces/logs/requests).
- Shadow Environments: The destination is a "shadow" or "staging" environment that mirrors production but doesn't affect real users.
High-Level Architecture:
- Source (Production): Where the traffic happens.
- Collection: Capturing the traffic (traces).
- Storage: Storing the traces.
- Transformation/Sanitization: Cleaning PII, adjusting timestamps.
- Replay Engine: The tool that sends the traffic to the shadow environment.
- Shadow Environment: The target system under test.
- Observability/Metrics: Collecting data from the shadow environment.
- Evaluation/Analysis: Comparing the shadow results against SLOs and potentially against production baseline.
Tools & Technologies (Open Source is usually preferred for "building" unless specified otherwise):
- Collection: OpenTelemetry (OTel), DaemonSets (if K8s).
- Storage: Object Storage (S3/GCS), Kafka (for streaming), or a specialized DB (ClickHouse).
- Replay Engine:
- For HTTP: Vegeta, JMeter, Gatling, or specialized tools like Gremlin (chaos) or Speedscale (commercial but concept fits).
- Let's stick to open-source friendly logic: Custom Go/Python script or something like Grafana Faro (frontend) or backend logic using a tool like Vegeta or ghz (for gRPC).
- Actually, a dedicated traffic replayer is better. Shadow Traffic (concept) or Meroja.
- Let's define a generic "Replayer" component.
- Shadow Environment: Kubernetes cluster, a separate namespace, or a Serverless preview environment.
- SLO Evaluation: OpenSLO (spec), Pyrra, Nobl9, or standard Prometheus/Thanos + custom logic.
- Routing: Service Mesh (Istio/Linkerd) for mirroring traffic (if doing live shadowing) OR offline replay. The prompt says "Replays production traces," implying an offline or buffered approach, not necessarily live mirroring (though mirroring is a form of this). I will focus on Capture-Store-Replay as it allows for regression testing over time.
Step-by-Step Implementation Plan:
- Step 1: Define SLOs. What are we measuring? (Latency p99 < 200ms, Error Rate < 0.1%).
- Step 2: Capture Mechanism. How to record ingress/egress.
- Step 3: The Shadow Infra. Setting up the environment.
- Step 4: The Replayer. The script/tool.
- Step 5: The Verifier. The logic that compares metrics vs. SLO.
Refining the "Replay" aspect:
Live traffic mirroring (e.g., Istio Mirroring) is great, but "replaying traces" suggests we might want to test a specific window of time or a new build against yesterday's traffic. I will design an Offline/Async Replay Pipeline because it's more robust for verifying new code changes against historical patterns.
Code/Structure:
I will provide a high-level architectural overview, a tool stack recommendation, and code snippets for the "Replayer" and "Evaluator" logic (Python or Go).
Key Challenges to Address:
- Non-determinism: Timestamps, UUIDs, random seeds.
- Statefulness: Database interactions (POST requests might fail if the DB state doesn't match prod).
- Solution: Use a sanitized copy of the DB or mock external dependencies (Service Virtualization). Or, focus only on Read-only traffic for strict SLO verification, or generate synthetic IDs.
- Side Effects: Don't send emails/charge credit cards in shadow. (Toggle flags).
Drafting the Content:
-
Architecture Diagram (Textual):
Prod -> [Collector] -> [Queue/Blob] -> [Replayer] -> Shadow Env -> [Metrics] -> [SLO Evaluator] -> Alert/Greenlight.
-
Component 1: Trace Collection (OpenTelemetry).
Use OTel collectors. Store in S3/Minio as JSON/Protobuf.
-
Component 2: The Shadow Environment.
K8s Namespace. Needs a "Shadow" feature flag configuration (to disable 3rd party APIs).
-
Component 3: The Replay Pipeline (The Core).
I'll write a Python script that reads the traces, sanitizes them, and uses aiohttp to replay them at a specific rate.
-
Component 4: SLO Evaluation.
Pull metrics from Prometheus in the shadow env. Compare against threshold.
Refining the "Replayer" Code:
I need a script that can:
- Read a trace file.
- Convert trace spans back into HTTP requests (this is tricky, usually we capture raw HTTP payloads, not just spans).
- Correction: "Replaying traces" usually means capturing the Request/Response pair (PCAP or HTTP payload), not just the telemetry span data (which might lack the body). I will assume we are capturing HTTP payloads (like a "golden master" or traffic recording).
Let's structure the answer:
- Architecture Overview: The "Clockwork" mechanism.
- Infrastructure Setup: K8s, S3, Prometheus.
- Data Collection: Recording traffic.
- The Pipeline (Code): A Python-based replayer and evaluator.
- Handling Edge Cases: State and Side Effects.
Self-Correction during drafting:
Simply replaying traces blindly doesn't work if the system relies on time (e.g., "give me data from last 5 mins").
Fix: The replayer must rewrite time-sensitive parameters on the fly or ensure the shadow environment has the necessary historical data seeded. I'll mention "Time Travel" or "Time Shifting" as a requirement.
Final Polish:
Make sure to emphasize Continuous Verification. This should run on every PR or nightly build.
Let's write the code.
Language: Python is easiest for pipeline logic glue. Go is better for high performance, but Python is more readable for the logic. I'll use Python for the example.
Specific SLO check:
if latency_p99 > threshold: fail_pipeline
Let's assemble.
- Phase 1: Ingest (Capture raw JSON requests).
- Phase 2: Transform (Sanitize PII, Shift timestamps).
- Phase 3: Replay (Send to Shadow URL).
- Phase 4: Analyze (Query Prometheus, compute SLO).
This looks solid. I will structure the response with a diagram, the architecture components, and the implementation code.
This design outlines a "Chronometer" pipeline. It captures live production traffic, sanitizes it, and replays it against a shadow environment (a candidate version of your software) to verify if it meets Service Level Objectives (SLOs) before deployment or continuously alongside production.
1. Architecture Overview
The pipeline consists of four distinct stages:
- Capture & Sanitize (The Sniffer): Intercepts raw requests in production, scrubs PII (Personally Identifiable Information), and serializes them to a durable buffer.
- Shadow Infrastructure (The Sandbox): A dedicated environment running the candidate version of the service. It must be isolated (no external side effects) but realistic (dependencies mocked or mirrored).
- Replay Engine (The Driver): Pulls traces and replays them against the Shadow environment at a controlled rate (e.g., 1x or 10x speed) while capturing resulting latencies and error codes.
- Verdict Engine (The Judge): Aggregates the results and compares them strictly against defined SLOs (e.g., P99 latency < 200ms, Error Rate < 0.1%).
2. Infrastructure Setup
We will define the SLOs using Python data classes and the Shadow Environment using Terraform (conceptual).
A. Defining the SLOs (config/slo.yaml)
service: payment-gateway
slos:
- name: availability
target: 99.9
type: availability
- name: latency-p99
target: 200 # milliseconds
type: latency
percentile: 0.99
- name: error-rate-5xx
target: 0.05 # 0.05%
type: error_rate
filter: "status >= 500"
B. Shadow Environment Logic
The shadow environment must handle side effects gracefully. If the trace includes a request to POST /charge_credit_card, the shadow service should execute the logic but use a mocked payment gateway so real money isn't transacted.
3. The Pipeline Implementation
Here is a complete, runnable Python implementation of the Continuous Verification Pipeline.
Prerequisites:
pip install prometheus-client pyyaml numpy requests
The Code (verification_pipeline.py)
import time
import yaml
import json
import numpy as np
import requests
import logging
from dataclasses import dataclass
from typing import List, Dict, Optional
from concurrent.futures import ThreadPoolExecutor, as_completed
# Configure Logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("CV-Pipeline")
# --- 1. Data Models ---
@dataclass
class Trace:
trace_id: str
method: str
path: str
headers: Dict
body: str
# The original production timestamp
timestamp: float
@dataclass
class ReplayResult:
trace_id: str
status_code: int
latency_ms: float
success: bool
error_message: Optional[str] = None
@dataclass
class SLO:
name: str
target: float
slo_type: str
percentile: Optional[float] = None
# --- 2. The Verifier Class ---
class ContinuousVerifier:
def __init__(self, config_path, shadow_url):
self.shadow_url = shadow_url
self.slos = self._load_slos(config_path)
self.results_buffer = []
def _load_slos(self, path):
with open(path, 'r') as f:
config = yaml.safe_load(f)
return [SLO(**slo) for slo in config['slos']]
# --- Simulation of Trace Capture ---
# In production, this would read from Kafka/NATS/S3
def fetch_production_traces(self, limit=100):
logger.info(f"Fetching {limit} traces from storage...")
traces = []
for i in range(limit):
# Simulate a JSON payload captured from prod
traces.append(Trace(
trace_id=f"trace-{i}",
method="POST",
path="/api/payment",
headers={"Content-Type": "application/json", "Authorization": "Bearer SANITIZED_TOKEN"},
body=json.dumps({"amount": 1000, "user_id": "sanitized_123"}),
timestamp=time.time() - np.random.exponential(10) # Simulate past events
))
return traces
# --- Replay Logic ---
def replay_single_trace(self, trace: Trace) -> ReplayResult:
url = f"{self.shadow_url}{trace.path}"
# Time Shifting: We ignore the original timestamp for replay timing,
# but we might use it for 'time-travel' debugging.
start_time = time.perf_counter()
try:
response = requests.request(
method=trace.method,
url=url,
headers=trace.headers,
data=trace.body,
timeout=10 # Strict timeout for the shadow env
)
latency = (time.perf_counter() - start_time) * 1000
return ReplayResult(
trace_id=trace.trace_id,
status_code=response.status_code,
latency_ms=latency,
success=(200 <= response.status_code < 300)
)
except Exception as e:
latency = (time.perf_counter() - start_time) * 1000
return ReplayResult(
trace_id=trace.trace_id,
status_code=0,
latency_ms=latency,
success=False,
error_message=str(e)
)
# --- Analysis Logic ---
def evaluate_slos(self, results: List[ReplayResult]):
total_requests = len(results)
if total_requests == 0:
return
# Extract data for calculations
latencies = [r.latency_ms for r in results]
successful_requests = [r for r in results if r.success]
error_codes = [r for r in results if r.status_code >= 500 or r.status_code == 0]
logger.info(f"--- VERIFICATION REPORT ({total_requests} samples) ---")
all_passed = True
for slo in self.slos:
passed = False
actual_value = 0
if slo.slo_type == 'availability':
actual_value = (len(successful_requests) / total_requests) * 100
passed = actual_value >= slo.target
elif slo.slo_type == 'latency':
# Calculate Percentile (e.g., P99)
actual_value = np.percentile(latencies, slo.percentile * 100)
passed = actual_value <= slo.target
elif slo.slo_type == 'error_rate':
actual_value = (len(error_codes) / total_requests) * 100
passed = actual_value <= slo.target
status_icon = "✅ PASS" if passed else "❌ FAIL"
logger.info(f"SLO [{slo.name}]: Target={slo.target}{self._get_unit(slo.slo_type)} | Actual={actual_value:.2f}{self._get_unit(slo.slo_type)} | {status_icon}")
if not passed:
all_passed = False
return all_passed
def _get_unit(self, slo_type):
return "%" if slo_type in ['availability', 'error_rate'] else "ms"
# --- Main Execution Loop ---
def run_pipeline(self, batch_size=100, concurrency=10):
logger.info("Starting Continuous Verification Pipeline...")
# 1. Ingest
traces = self.fetch_production_traces(limit=batch_size)
# 2. Replay (Parallelized)
logger.info(f"Replaying traces against {self.shadow_url} with {concurrency} workers...")
results = []
with ThreadPoolExecutor(max_workers=concurrency) as executor:
future_to_trace = {executor.submit(self.replay_single_trace, trace): trace for trace in traces}
for future in as_completed(future_to_trace):
res = future.result()
results.append(res)
# 3. Evaluate
passed = self.evaluate_slos(results)
# 4. Gate (Exit Code)
if not passed:
logger.error("Verification Failed. Halting deployment.")
# In a CI/CD context, we would exit(1) here to stop the pipeline
return False
logger.info("Verification Successful.")
return True
# --- Mock Server for Demonstration ---
# To run this locally, you need a simple Flask server running on 5001
# app.py (Mock):
# @app.route('/api/payment', methods=['POST'])
# def pay():
# time.sleep(random.uniform(0.05, 0.2)) # Simulate work
# if random.random() > 0.01: # 99% success rate
# return jsonify({"status": "ok"}), 200
# return jsonify({"error": "declined"}), 500
if __name__ == "__main__":
# Setup mock config
with open('config/slo.yaml', 'w') as f:
f.write("""
service: mock-service
slos:
- name: availability
target: 95.0
type: availability
- name: latency-p95
target: 300
type: latency
percentile: 0.95
""")
# Initialize Verifier pointing to a local shadow service
# Ensure you have a service running at http://localhost:5001
verifier = ContinuousVerifier("config/slo.yaml", "http://localhost:5001")
# Run Pipeline
verifier.run_pipeline(batch_size=50)
4. Detailed Component Breakdown
1. Traffic Capture & Anonymization
Real production traces often contain PII (emails, credit cards). Before the trace hits the storage layer for replay, you must implement a "Sanitizer".
- Technique: Use a proxy (like Envoy or Nginx) or an Application Performance Monitoring (APM) SDK to intercept the request body.
- Action: Regex replace emails, tokens, and credit card numbers with
REDACTED or deterministic hashes (so the shadow env can still validate format).
2. The Shadow Environment
This environment must be stateful regarding code but stateless regarding data.
- Database: You cannot write to the production DB. You have two choices:
- Read-Only Replica: Route shadow traffic to a read-replica of the DB.
- Transaction Rollback: Begin a DB transaction, execute the logic, assert results, then Rollback.
- External APIs: Use Service Virtualization (e.g., Hoverfly, Mountebank) to mock 3rd party APIs (Stripe, Twilio) so the shadow environment doesn't trigger real world side effects.
3. Time-Travel & Determinism
Production traffic is "bursty". Replaying it 1:1 might not stress the system enough to find concurrency bugs, or might stress it too much.
- Speed Control: The pipeline script allows you to replay at 10x speed to test load handling.
- Clock Skew: If your business logic depends on "Time of Day" (e.g., "Cannot process order after 5 PM"), your shadow environment needs its system clock mocked, or the replayer needs to shift timestamps in the payload to match the current time.
5. Deployment Strategy (CI/CD Integration)
This pipeline is intended to run as a step in your deployment process (e.g., Jenkins, GitHub Actions, Argo Rollouts).
Workflow:
- Build: Create the Docker image for the new version of the service.
- Deploy Shadow: Deploy this image to the
verification-namespace in Kubernetes.
- Run Pipeline: Execute the Python script above.
- If Exit Code 0: Proceed to Canary deployment in Production.
- If Exit Code 1: Fire alerts, block deployment, and trigger a rollback.
6. Advanced Considerations
- Baseline Comparison: Instead of absolute SLOs (e.g., P99 < 200ms), use Relative SLOs. Compare the Shadow P99 to the Production P99. If Shadow is > 5% slower, fail the build. This catches "slow creep" even if you are within the hard SLO limit.
- Stateful Replay: For complex user flows (Login -> Add to Cart -> Checkout), you cannot just replay individual HTTP requests. You must capture the Session Token generated in the Login replay and inject it into the Checkout replay. This requires a "Scenario Replayer" (like Gatling or k6) rather than a simple HTTP replayer.