The user wants to build a safe A/B testing framework server-side.
This implies a system that can:
- Bucketing: Assign users/requests to specific experiment variants consistently.
- Exposure: Track when users are actually exposed to an experiment (logging/tracking).
- Checks (Safety/Guardrails): Ensure validity, prevent conflicts, and handle errors gracefully.
Scope of the Response:
- Conceptual Architecture: Explain how the pieces fit together.
- Code Implementation: Provide a concrete code example (likely Python or Go, Python is generally more accessible for pseudo-code/prototyping, but Go is great for high-performance servers. I'll stick to Python for readability and ease of understanding the logic, but structure it like a library).
- Key Algorithms: Hashing for bucketing (e.g., MurmurHash, SHA-256).
- Safety Features: Consistency, Sampling, Collision detection, Data integrity.
Step-by-Step Plan:
-
Core Logic - Bucketing:
- Need a deterministic hash function. Input:
User ID + Experiment Name. Output: Integer.
- Map the integer to a range (0-100 or 0-999 for precision).
- Assign variant based on allocation percentages (e.g., Control: 50%, Treatment: 50%).
-
Core Logic - Exposure:
- Need an event logger.
- When
get_variant() is called, log an "exposure" event.
- Idempotency is key here (don't log the same exposure twice if the logic runs again, or at least handle it downstream).
-
Core Logic - Checks (Safety):
- Input Validation: Are the percentages valid? Do they sum to 100%?
- Consistency: Same user must get same variant.
- Guardrails: Is the experiment active? Is the user in a specific allowlist/blocklist?
- ** collisions (theoretical):** While hard to solve perfectly in a simple snippet, acknowledging hash distribution quality is important.
-
Implementation Structure:
Experiment class: Holds config (name, variants, %s).
ExperimentService class: Manages experiments, performs bucketing.
Bucketizer (Helper): The math part.
Logger: The exposure part.
-
Refining the Code (Self-Correction/Edge Cases):
- Edge Case: What if allocations don't sum to 100? -> Throw error or normalize. Normalization is safer for usability, strict validation is safer for science. I'll choose strict validation.
- Edge Case: Changing allocations while experiment is running. -> This breaks consistency. I should mention "Salt" or "Versioning" in the hashing to ensure if config changes, we don't randomly flip users. Correction: Actually, if allocations change, users might shift buckets. A robust framework often locks allocations or uses a consistent hashing ring, but for a "basic" framework, standard hashing with a warning is sufficient.
- Safety: "Sample Rate Mismatch" (SRM) is a statistical check. I can't implement the stats engine here, but I can implement the hooks for data validation.
-
Drafting the Content:
- Introduction: Define the goals (Consistency, Scalability, Safety).
- Component 1: The Bucketing Engine (The Math):
- Use MD5 or SHA256. Take the hex digest, convert to int, modulo 100.
- Component 2: The Configuration Store:
- Define the structure (JSON/Dict).
- Component 3: The Service Logic:
assign(user_id, experiment_key).
- Component 4: Exposure Logging:
- Async logging is best for performance.
- Component 5: Safety Checks:
- Check active status.
- Check allocation sums.
- Check eligibility (targeting).
-
Writing the Code (Mental Draft):
def get_bucket(user_id, exp_name):
hash_val = hash(user_id + exp_name)
bucket = hash_val % 100
# logic to map bucket to variant
-
Adding "Safety" Specifics:
- sticky bucketing: Use a database/cookie to ensure a user stays in a group even if the hash function changes or if they log in on a new device (if using account ID). For this server-side snippet, we assume
user_id is stable.
- oversampling: Check if the user is already in a conflicting experiment.
-
Final Polish:
- Organize into clear sections.
- Provide a complete Python Class structure.
- Add a "Production Considerations" section for things like Race Conditions, DB Storage, and SRM.
(Self-Correction during drafting): I need to make sure I don't use Python's built-in hash() function because it is not deterministic across processes/versions (randomized seed). I must use hashlib.
Let's structure the response:
- Architecture Overview: The mental model.
- The Code: A Python implementation of a
ExperimentService.
- Deep Dive into Components:
- Bucketing: Consistent Hashing.
- Exposure: Logging & Idempotency.
- Checks: Allocation validation & Targeting.
- Safety Best Practices: Guardrails.
Let's write the code.
- Bucketization: Use
mmh3 (MurmurHash) if available, otherwise hashlib.md5. I'll use hashlib for standard lib compatibility.
- Allocation Logic: Convert [A:50, B:50] into ranges [0-50, 50-100].
Refining "Checks":
What is a "safe" check?
- Validation: Config sanity (sums to 100).
- ** Eligibility:** Is this user allowed? (e.g., employees only, specific country).
- Collision/Interaction: Is this incompatible with another active test? (Mutually exclusive groups).
I will implement a check_mutual_exclusivity example because that's a classic advanced feature.
Let's finalize the output format. Clear headers, code blocks, and bullet points.
Code Structure:
class ExperimentConfig: ...
class ExperimentClient:
def assign(user_id, experiment_key): ...
def _hash(): ...
def _log_exposure(): ...
Looks good. Proceeding with generation.
Building a server-side A/B testing framework requires balancing determinism (users must not switch groups) with performance and safety.
Here is a comprehensive guide and a production-ready Python implementation covering Consistent Bucketing, Safe Exposure Logging, and Validity Checks.
1. Architecture Overview
- Bucketing (Assignment): Uses a deterministic hash (MurmurHash or SHA256) of the
User ID + Experiment Name. This ensures that the same user always gets the same variant without needing to store state in a database for every single request.
- Exposure (Logging): When a user is assigned a variant, we fire an asynchronous event (to Kafka, stdout, or an analytics service). This is the "data" part of the test.
- Checks (Safety):
- Sample Ratio Mismatch (SRM): Checking if the split matches the config (e.g., 50/50).
- Config Validation: Ensuring percentages sum to 100%.
- Mutual Exclusivity: Preventing UI-breaking experiment collisions.
2. The Implementation (Python)
We will use Python's standard hashlib for deterministic bucketing. This code is framework-agnostic (works with Flask, Django, FastAPI).
import hashlib
import json
import logging
from dataclasses import dataclass
from typing import Dict, Optional, List
# Configure logging to simulate our "Exposure" tracking
logger = logging.getLogger("ab_framework")
logging.basicConfig(level=logging.INFO)
# --- 1. Data Structures ---
@dataclass
class Variant:
name: str
allocation: float # e.g., 50.0 for 50%
@dataclass
class Experiment:
name: str
variants: List[Variant]
is_active: bool = True
salt: str = "" # Optional salt to force re-randomization
# --- 2. The Core Logic ---
class ABTestingFramework:
def __init__(self):
# In a real app, this might be loaded from a remote config service (LaunchDarkly, Statsig, etc)
self.experiments: Dict[str, Experiment] = {}
self.exposure_callbacks = []
def register_experiment(self, experiment: Experiment):
"""Load experiment config with Safety Checks."""
total_alloc = sum(v.allocation for v in experiment.variants)
# SAFETY CHECK: Allocation Logic
if not (99.9 <= total_alloc <= 100.1):
raise ValueError(f"Experiment '{experiment.name}' allocations sum to {total_alloc}, not 100%.")
if not experiment.salt:
experiment.salt = experiment.name
self.experiments[experiment.name] = experiment
def _get_bucket_value(self, user_id: str, experiment: Experiment) -> int:
"""
Core Bucketing Logic.
Returns a value between 0 and 99 (representing percentiles).
Uses SHA256 for deterministic distribution.
"""
# Composite key prevents correlation across experiments
composite_key = f"{experiment.salt}.{user_id}"
# Get hex digest
hash_digest = hashlib.sha256(composite_key.encode()).hexdigest()
# Convert first 8 chars of hex to integer
hash_int = int(hash_digest[:8], 16)
# Modulo 100 to get a number between 0-99
return hash_int % 100
def get_variant(self, user_id: str, experiment_name: str, attributes: Optional[Dict] = None) -> Optional[str]:
"""
Main entry point. Returns the variant name or None.
"""
experiment = self.experiments.get(experiment_name)
# CHECK 1: Existence & Active Status
if not experiment or not experiment.is_active:
return None
# CHECK 2: Targeting (Custom Logic)
# e.g., if attributes.get('country') != 'US': return None
# Implementation skipped for brevity, but crucial for safety.
# BUCKETING
bucket_val = self._get_bucket_value(user_id, experiment)
assigned_variant = None
cumulative_weight = 0.0
# Determine which bucket the user falls into
for variant in experiment.variants:
cumulative_weight += variant.allocation
if bucket_val < cumulative_weight:
assigned_variant = variant.name
break
# EXPOSURE LOGGING
if assigned_variant:
self._log_exposure(user_id, experiment_name, assigned_variant, attributes)
return assigned_variant
def _log_exposure(self, user_id, experiment_name, variant_name, attributes):
"""
Logs that a user saw the experiment.
In production, this should be non-blocking (e.g., put on a queue).
"""
event = {
"event_type": "experiment_exposure",
"user_id": user_id,
"experiment_name": experiment_name,
"variant": variant_name,
"timestamp": "2023-10-27T10:00:00Z", # Use actual timestamp
"attributes": attributes
}
# Simulate sending to analytics
logger.info(f"EXPOSURE: {json.dumps(event)}")
# --- 3. Usage Example & Checks ---
if __name__ == "__main__":
framework = ABTestingFramework()
# Define an experiment: Button Color
# 50% Control (Blue), 50% Treatment (Red)
exp = Experiment(
name="checkout_btn_color",
variants=[
Variant(name="control", allocation=50.0),
Variant(name="red_button", allocation=50.0)
]
)
framework.register_experiment(exp)
# --- Simulate Traffic ---
print("--- Simulating Traffic ---")
# User "alice" will always get the same variant
v1 = framework.get_variant("alice", "checkout_btn_color")
v2 = framework.get_variant("alice", "checkout_btn_color")
print(f"Alice's Variant 1: {v1}")
print(f"Alice's Variant 2: {v2} (Consistency Check)")
# --- Simulate SRM Check (Sample Ratio Mismatch) ---
# We generate 10,000 users and check distribution
print("\n--- Running Distribution Check (SRM) ---")
counts = {"control": 0, "red_button": 0}
num_users = 10000
for i in range(num_users):
uid = f"user_{i}"
variant = framework.get_variant(uid, "checkout_btn_color")
if variant:
counts[variant] += 1
print(f"Total Users: {num_users}")
print(f"Control: {counts['control']} ({counts['control']/num_users*100:.2f}%)")
print(f"Treatment: {counts['red_button']} ({counts['red_button']/num_users*100:.2f}%)")
# Basic variance check (should be extremely close to 50/50)
assert 4800 < counts['control'] < 5200, "SRM Check Failed: Distribution skewed!"
3. Detailed Breakdown of Components
A. Bucketing (The Math)
To keep the server stateless, we use Deterministic Hashing.
- Input:
UserID + ExperimentKey.
- Process: Hash -> Integer -> Modulo 100.
- Result: A number between 0 and 99. If Variant A is allocated 50%, any user hashing to 0-49 gets Variant A. Users hashing to 50-99 get Variant B.
- Why this is safe: It ensures
User_1 always hashes to the same bucket on Server A and Server B without sharing a database.
B. Exposure (The Analytics)
Server-side exposure is safer than client-side because ad-blockers cannot prevent it.
- The Event: You must log
user_id, experiment_id, variant_id, and a timestamp.
- Performance: The
_log_exposure function should never block the main request thread. In Python, use a background task (Celery) or a fire-and-forget buffer. In Node.js/Go, use goroutines or async functions.
- Idempotency: If you log exposures to a database, ensure
INSERT uses an ON CONFLICT (upsert) logic or a unique constraint on (user_id, experiment_id) so you don't count the same user entering the experiment multiple times as multiple "enrollments."
C. Checks & Guardrails
-
Configuration Validation (The "Sum to 100" Rule):
In the register_experiment method, we verify allocations sum to 100%. If they don't, the framework refuses to load the experiment. This prevents "dark launches" where no one sees the feature.
-
Sample Ratio Mismatch (SRM):
In the usage example, we counted the buckets. In a real production environment, you should run a Chi-Squared test on the bucket counts. If you configured 50/50 but the traffic comes in 40/60, your hash function is biased, or your randomization unit is flawed. SRM checks detect bugs in the bucketing logic itself.
-
Collision Prevention (Mutual Exclusivity):
If Experiment A changes the "Checkout Button" and Experiment B changes the "Checkout Header", running them together might break the UI.
- Solution: Implement "Namespaces" or "Layers".
- Logic: If
Experiment A is in "Layer 1", Experiment B in "Layer 1" cannot overlap users. However, Experiment C in "Layer 2" can overlap with A. This is usually done by hashing a Layer ID + User ID instead of just Experiment ID.
-
Immutable Variants:
Once an experiment has started collecting data, you should not be able to change the percentages (e.g., from 50/50 to 80/20). Changing percentages mid-stream causes "bucket jumping," which invalidates statistical results. Ideally, the config system should lock the experiment or require a "Reset" (clearing all previous exposure data) to change percentages.