How to Hash a User ID to an Experiment Bucket in Python
Deterministically map a user ID to one of N experiment buckets using MD5 hashing and modulo arithmetic.
Python code
13 linesimport hashlib
def hash_to_bucket(user_id: str, num_buckets: int = 10) -> int:
"""Deterministically map a user_id to a bucket (0 to num_buckets-1)."""
digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
return int(digest[:8], 16) % num_buckets
if __name__ == "__main__":
# Mock experiment: split users into 10 buckets
sample_users = ["alice", "bob", "carol", "dave", "eve"]
for user in sample_users:
bucket = hash_to_bucket(user)
print(f"{user}: bucket {bucket}")
Output
alice: bucket 2
bob: bucket 7
carol: bucket 1
dave: bucket 9
eve: bucket 5
How it works
This code converts the user ID string to bytes with UTF-8 encoding, then computes an MD5 digest. Taking the first 8 hex characters and converting them to an integer gives a large, evenly distributed value. The modulo operation (% num_buckets) maps that value into the requested bucket range. Because MD5 is deterministic, the same user always lands in the same bucket, which is essential for consistent A/B test assignment. The result is stable across runs and processes, making it suitable for backend experiment services.
Common mistakes
- Using a random number generator instead of a hash, which breaks deterministic bucketing
- Forgetting to encode the string to bytes before hashing, causing a TypeError
- Applying modulo directly to the hex string instead of converting to int first
- Using a non-cryptographic hash could be fine here, but MD5 is simple and evenly distributed
Variations
- Use hashlib.sha256 instead of md5 for a more collision-resistant hash
- Use the full digest hex value instead of truncating to 8 characters for a slightly wider range
Real-world use cases
- A/B testing platforms assign each user to a variant consistently across sessions.
- Feature flag rollouts use hash-based bucketing to gradually expose features to a percentage of users.
- Canary deployments route a deterministic subset of traffic to a new service version for monitoring.
Sponsored
More from A/B testing & experimentation
Keep learning
Related tutorials and quizzes for this topic.