Flag Rule Resolver with Hash-Bucketed Rollouts
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a feature-flag service: match attribute rules, gate by a SHA-256 percentage bucket, and resolve conflicts so any matching "on" rule wins.
Flag Rule Resolver
You are building the core of a small feature-flag service. It is given a set of flag definitions, then answers a batch of queries asking whether a flag is on or off for a particular user.
Implement a single function that takes the flag definitions plus a list of commands and returns one result per command.
Data model
User: a dictionary with an "id" string and any number of other attributes (for example "country": "US" or "age": 28).
Flag: a dictionary with:
key: the unique name of the flag.default_value: the boolean used when no rule applies.rules: a list of rules, which may be empty.
Rule: a dictionary with:
conditions: a list of{"attribute": str, "operator": str, "value": Any}objects. A rule's conditions are satisfied only if every one of them holds. An empty list is satisfied by every user.rollout_percentage(optional): an integer from 0 to 100. If it is present, the user must also land inside the rollout for the rule to apply. If it is absent, there is no rollout restriction.serve: the boolean this rule yields when it applies.
Condition operators
Let actual be the user's value for the condition's attribute, and value the value stored in the condition.
EQUALS: holds whenactual == value.IN: holds whenactualis a member ofvalue(a list).GTE: holds whenactual >= value.- If the user has no such attribute, or its value is
None, the condition does not hold, whatever the operator. - Any other operator name never holds.
Rollout bucketing
For a rule that has rollout_percentage, compute the user's bucket for that flag:
- Build the ASCII string
"{flag_key}:{user_id}". - Take its SHA-256 digest as a hexadecimal string and read it as a base-16 integer.
- The bucket is that integer modulo 100.
The user is inside the rollout when bucket < rollout_percentage. A percentage of 0 therefore admits nobody and 100 admits everybody. The rollout check is only relevant for a rule whose conditions are already satisfied.
Resolving a flag for a user
A rule applies when all of its conditions hold and, if it has a rollout percentage, the user is inside the rollout.
- If at least one applying rule has
serveequal toTrue, the flag isTrue. - Otherwise, if at least one rule applies (so all applying rules serve
False), the flag isFalse, even whendefault_valueisTrue. - Otherwise (no rule applies, including when
rulesis empty), the result is the flag'sdefault_value. - If the requested flag key does not exist, the result is
False.
Commands
commands and command_args have equal length, and command_args[i] holds the arguments for commands[i]. Process them in order. Each command adds exactly one element to the output list.
"evaluate"with arguments[flag_key, user]: output the boolean for that flag and user."evaluate_all"with arguments[user]: output a dictionary mapping every flag key to its boolean for that user, with keys in the same order as the flags appear inflag_defs.
The inputs must not be modified.
Constraints
- Flag keys are unique, non-empty ASCII strings. User IDs are non-empty ASCII strings.
rollout_percentage, when present, is an integer in[0, 100].- Every command name is either
"evaluate"or"evaluate_all". - Looking up a flag should take constant time, and the function should stay efficient with thousands of commands.
Examples
Example 1
Input: resolve_flag_states([{'key': 'beta_dashboard', 'default_value': False, 'rules': [{'conditions': [{'attribute': 'country', 'operator': 'IN', 'value': ['US', 'CA']}], 'rollout_percentage': 50, 'serve': True}, {'conditions': [{'attribute': 'beta_tester', 'operator': 'EQUALS', 'value': True}], 'serve': True}]}], ['evaluate', 'evaluate', 'evaluate_all'], [['beta_dashboard', {'id': 'u123', 'country': 'US', 'beta_tester': False}], ['beta_dashboard', {'id': 'u456', 'country': 'UK', 'beta_tester': True}], [{'id': 'u789', 'country': 'CA', 'beta_tester': False}]])
Output: [False, True, {'beta_dashboard': False}]
Hints
Hint 1
Index the flags in a dictionary by key once, up front, so each query is a constant-time lookup instead of a scan.
Hint 2
Check a rule's conditions first and compute the SHA-256 bucket only if they all hold. Treat a missing attribute or a None value as a failed condition before applying any operator.
Hint 3
Track whether any rule applied. Return True immediately when an applying rule serves True. At the end, return False if some rule applied, otherwise default_value.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a small rules engine, so the main risk is a slip in the details rather than a hard algorithm. The solution has three layers.
- Index the flags. Build a dictionary from flag key to flag definition once. Each
evaluatecommand then looks up its flag in constant time, andevaluate_alliterates the dictionary in config order. - Check a single condition. Fetch the user's value for the attribute. If it is missing or
None, the condition fails. Otherwise applyEQUALS(==),IN(membership) orGTE(>=). Any unknown operator fails. - Resolve a flag. Walk the rules in order. A rule is skipped if any condition fails. If it has a rollout percentage, compute
int(sha256("{flag}:{id}").hexdigest(), 16) % 100and skip the rule when the bucket is not below the percentage. A rule that survives both checks counts as applied. If it servesTrue, returnTrueimmediately. After the loop, returnFalseif some rule applied, otherwise the flag'sdefault_value. An unknown flag key yieldsFalse.
Why it is correct
all()over an empty list isTrue, so a rule with no conditions applies to everyone, which gives a pure percentage rollout when combined withrollout_percentage.- The result is
Trueexactly when some applying rule servesTrue, so returning at the first one is safe. Rule order affects speed only, never the answer. - A matching rule that serves
Falseoverrides aTruedefault, becauseany_appliedis tracked separately from the default. - The hash is computed only after the conditions pass, and it is deterministic across runs, unlike Python's built-in
hash(). Including the flag key in the hashed string makes a user's bucket independent between flags. - Nothing is mutated; the code only reads the flag definitions and users.
Complexity
Let F be the number of flags, R the rules per flag and C the conditions per rule.
- Indexing:
O(F)time and space. evaluate:O(1)lookup plusO(R·C)condition checks, with at most one SHA-256 per rule that passes its conditions.INcosts time proportional to the list length.evaluate_all:O(F·R·C).- Extra space:
O(F)for the index, plus the output.
Reference solution
import hashlib
from typing import Any, Dict, List
def resolve_flag_states(flag_defs: List[Dict[str, Any]], commands: List[str], command_args: List[List[Any]]) -> List[Any]:
flags = {flag['key']: flag for flag in flag_defs}
def condition_holds(condition, user):
actual = user.get(condition['attribute'])
if actual is None:
return False
op = condition['operator']
expected = condition['value']
if op == 'EQUALS':
return actual == expected
if op == 'IN':
return actual in expected
if op == 'GTE':
return actual >= expected
return False
def resolve(flag_key, user):
flag = flags.get(flag_key)
if flag is None:
return False
any_applied = False
for rule in flag.get('rules', []):
if not all(condition_holds(c, user) for c in rule.get('conditions', [])):
continue
pct = rule.get('rollout_percentage')
if pct is not None:
raw = f"{flag_key}:{user['id']}".encode('ascii')
bucket = int(hashlib.sha256(raw).hexdigest(), 16) % 100
if bucket >= pct:
continue
any_applied = True
if rule['serve']:
return True
return False if any_applied else flag['default_value']
output = []
for cmd, args in zip(commands, command_args):
if cmd == 'evaluate':
output.append(resolve(args[0], args[1]))
elif cmd == 'evaluate_all':
user = args[0]
output.append({key: resolve(key, user) for key in flags})
else:
raise ValueError(f'Unknown operation: {cmd}')
return output