How to hash user IDs to experiment buckets in Python
Deterministically map a user ID to an experiment bucket using MD5 hashing, ensuring stable and consistent assignment for A/B testing.
Python code
14 linesimport hashlib
def hash_user_to_bucket(user_id: str, num_buckets: int = 10) -> int:
"""Deterministically map a user ID to an experiment bucket (0..num_buckets-1)."""
digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
return int(digest, 16) % num_buckets
if __name__ == "__main__":
mock_users = ["alice", "bob", "carol", "dave", "eve"]
for user in mock_users:
bucket = hash_user_to_bucket(user)
print(f"{user}: bucket {bucket}")
Output
alice: bucket 5
bob: bucket 7
carol: bucket 4
dave: bucket 2
eve: bucket 6
How it works
The hashlib.md5 function generates a fixed-length hexadecimal digest from the user ID string. Converting this hex digest to an integer (int(digest, 16)) and taking the modulo with the number of buckets ensures even distribution across buckets. Because the hash is deterministic, the same user ID always maps to the same bucket, enabling consistent experiment assignment across sessions. For production systems, consider using SHA-256 instead of MD5 to avoid potential collision weaknesses, though MD5 is acceptable for bucketing where collisions are benign.
Common mistakes
- Using Python's built-in `hash()` function, which is randomized per process and not stable across runs
- Forgetting to encode the user ID as bytes before hashing, causing a TypeError
- Assuming the modulo operation yields perfectly uniform distribution when `num_buckets` is large
Variations
- Use `hashlib.sha256` instead of `md5` for stronger hashing without significant performance cost
- Use `uuid5` with a namespace for a UUID-based hashing approach
Real-world use cases
- Segmenting users into variant groups for A/B testing in a live web application.
- Assigning customers to pricing or feature experiment cohorts in a SaaS product.
- Distributing users to different recommendation engines for controlled rollout and comparison.
Sponsored
More from A/B testing & experimentation
Keep learning
Related tutorials and quizzes for this topic.