An interview question: "Turn a new checkout on for 20% of users. Each user must get the same answer on every request and on every server. How?" A random number on each request fails: one user would flip between the old and the new checkout from page to page.
The idea: compute the number from the user id. A stable hash like SHA-256 turns the same text into the same huge number on every run and every machine. Modulo 100 that gives a bucket from 0 to 99, and a user gets the feature when their bucket is below the percentage: buckets 0 to 19 are 20% of users. Put the feature's name in the hashed text too, so each feature picks its own 20%.
>>> import hashlib
>>> hashlib.sha256("hello".encode()).hexdigest()[:12]
'2cf24dba5fb0'
>>> int("ff", 16)
255
>>> 1234 % 100
34
Don't use Python's built-in hash() for this: for text it is salted, so it gives a different number every time the program starts, and your servers would disagree about who is in.
GET /features?user=ben → 200 {"user": "ben", "bucket": 4, "new_checkout": true}
GET /features?user=ana → 200 {"user": "ana", "bucket": 86, "new_checkout": false}
GET /features?user=user6 → 200 {"user": "user6", "bucket": 19, "new_checkout": true}
GET /features?user=jon → 200 {"user": "jon", "bucket": 20, "new_checkout": false}
GET /features → 400 {"error": "user is required"}
GET /rollout → 200 {"users": 1000, "enabled": 211}
Asking for ben again gives bucket 4 again. GET /rollout counts how many of user1 to user1000 get the feature: 211, close to 20%.
Your task: FEATURE, PERCENT and both routes are given. Write bucket(user_id): join FEATURE, a colon and the user id, hash that text with SHA-256, and return the hex digest read as a base-16 number, modulo 100. Then write is_enabled(user_id), which returns whether the user's bucket is below PERCENT.
Assignment
Follow the Coding Tutorial to write bucket and is_enabled.
Hinthashlib.sha256(text.encode()).hexdigest() gives the hex digest, and int(digest, 16) reads it as a number. Below 20 means <, not <=: bucket 20 is out.
Free plan: 30 tutor messages. PRO is unlimited.
