Feature flags at scale
The product team wants to ship a new checkout flow. The ops team wants to be able to turn it off instantly if it misbehaves. Feature flags give them both what they want: the code ships to production, but a runtime switch decides who actually sees it.
A production flag system evaluates rules. Is the flag on globally? Is this user in a targeting list? Does their user id hash into the enabled percentage? The answer is a boolean. The important thing is that evaluation is fast, because every request asks about flags and you do not want to block.
import crypto from 'crypto';
interface Flag {
name: string;
enabled: boolean; // global kill switch
allowUserIds: number[]; // explicit allow list
rolloutPercent: number; // 0-100
}
export function isEnabled(flag: Flag, userId: number): boolean {
if (!flag.enabled) return false; // kill switch wins
if (flag.allowUserIds.includes(userId)) return true;
const hash = crypto
.createHash('md5')
.update(flag.name + ':' + userId)
.digest('hex');
const bucket = parseInt(hash.slice(0, 8), 16) % 100;
return bucket < flag.rolloutPercent;
}Evaluate a flag with a kill switch, allow list, and percentage rollout.
Notice the hash uses both the flag name and the user id. That way, a given user either sees the feature or not, consistently across every request. If you hashed only the user id, two different flags at 50 percent would either show the same half of users or opposite halves, neither of which is what you want.
Quiz: Quiz
Loading practice…