MD5 Modulo Deterministic A/B Buckets

Assign A/B variants by hashing the user id with md5 and taking modulo 100, so bucketing is deterministic and needs no stored state.

SqlConfig Management

Code

snippet
-- deterministic A/B assignment: md5 the user_id, take the 32-bit integer modulo 100
-- the same user always lands in the same bucket: nothing to store, buckets survive replays and migrations
CREATE TABLE experiment_users (
    user_id text PRIMARY KEY
);

INSERT INTO experiment_users VALUES
    ('u-1001'), ('u-1002'), ('u-1003'), ('u-1004'),
    ('u-1005'), ('u-1006'), ('u-1007'), ('u-1008');

-- md5 returns hex text: prefix the first 8 characters with 'x' to cast through bit(32) into an integer
-- abs() guards against negative ints: Postgres % returns a negative remainder for negative input
SELECT
    user_id,
    abs(('x' || substr(md5(user_id), 1, 8))::bit(32)::int) % 100 AS bucket,
    CASE
        WHEN abs(('x' || substr(md5(user_id), 1, 8))::bit(32)::int) % 100 < 50 THEN 'control'
        ELSE 'treatment'
    END AS variant
FROM experiment_users
ORDER BY bucket, user_id;

How the pieces fit

What runs here is SELECT / INSERT / CREATE — experiment_users are the objects involved.

Mechanically, the statements are built from: an ORDER BY that fixes the output order; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the experiment_users table.

Statements that matter

SELECT
    user_id,
    abs(('x' || substr(md5(user_id), 1, 8))::bit(32)::int) % 100 AS bucket,
    CASE
        WHEN abs(('x' || substr(md5(user_id), 1, 8))::bit(32)::int) % 100 < 50 THEN 'control'
        ELSE 'treatment'
    END AS variant
FROM experiment_users
ORDER BY bucket, user_id;
INSERT INTO experiment_users VALUES
    ('u-1001'), ('u-1002'), ('u-1003'), ('u-1004'),
    ('u-1005'), ('u-1006'), ('u-1007'), ('u-1008');
CREATE TABLE experiment_users (
    user_id text PRIMARY KEY
);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`experiment_users`.