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.
Code
-- 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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.
FAQ
- Name the tables involved in this file.
- `experiment_users`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.