Scrivio Interview library
ScenarioIntermediate8 min read · updated 12 November 2026

A permissions service resolves a user's effective roles by walking group memberships: groups can contain groups. Requests are slow for some users and one request ran until timeout. What went wrong and how would you redesign it?

The membership graph almost certainly has a cycle, such as group A inside group B and B inside A, and the traversal has no visited set, so it walks the loop until the request times out. The slowness for other users comes from re-walking deep or wide hierarchies on every request, often with a database call per group. I would redesign it with a BFS that keeps a visited set and a depth limit and loads each level in one query, cache the resolved closure per user or group with invalidation on membership changes or precompute it in a closure table, and prevent cycles at write time by checking reachability before adding a membership.

Why this question is asked

Nested groups are convenient for administrators and dangerous for engineers: a permissions check that looked like a simple loop becomes a graph traversal over data that anyone with admin rights can reshape. Because permission checks run on nearly every request, a slow or looping resolver hurts the whole platform. Interviewers ask this to see whether we can diagnose a graph bug from symptoms and design a resolver that stays fast and safe. In this answer, we will model the membership graph, explain both symptoms, fix the traversal, remove repeated work with caching or a precomputed closure, look at doing it in SQL, and prevent cycles when memberships are written.

1The Membership Graph

A user belongs to some groups directly. A group can itself be a member of other groups, and membership is transitive: if Alice is in Developers and Developers is in Engineering, Alice gets Engineering's roles too. So the resolver must find every group reachable from the user's direct groups by following "is a member of" edges, and then collect the roles of all of them. The set of all reachable groups is called the transitive closure.

Nothing in the data model stops an administrator from putting Engineering inside Developers as well. The groups now form a directed cycle, and the "hierarchy" is really a general graph.

2What Went Wrong

The request that ran until timeout is the signature of a cycle without a visited set. Here is a typical resolver that expands groups one at a time.

Java
Set<String> roles(String userId) {
Set<String> result = new HashSet<>();
Deque<Long> pending = new ArrayDeque<>(repo.directGroupIds(userId));
while (!pending.isEmpty()) {
long groupId = pending.poll();
result.addAll(repo.rolesOf(groupId)); // one query per group
pending.addAll(repo.parentGroupIds(groupId)); // another query per group
}
return result;
}
// Developers -> Engineering -> Developers -> Engineering -> ... until the request times out
Step throughOne request against a cyclic membership
RequestResolverDatabase
roles(alice)
direct groups of alice
Developers
roles and parents of Developers
parent: Engineering
roles and parents of Engineering
parent: Developers
roles and parents of Developers again
no answer: the request times out

9 messages in order. Play them, or step through them one at a time.

Without a visited set, the cycle is expanded forever, two queries per step.

Notice that result is a set, so the roles look correct, but nothing remembers which groups were already expanded. With Developers inside Engineering and Engineering inside Developers, the queue never empties. A recursive version would eventually throw StackOverflowError instead, but since each step makes database calls, the request usually hits its timeout first.

The users with slow requests have a different problem with the same root. Even without a cycle, a user in 20 groups whose ancestors add up to 300 distinct groups costs about 600 database queries per request. If groups are shared, like diamonds where two paths lead to the same parent, the resolver without a visited set expands the shared ancestors once per path, so the work can grow much faster than the number of groups. And all of it is repeated on every request, although memberships change maybe a few times a day.

3Fixing the Traversal

The immediate fix is a BFS with a visited set, a depth limit, and one query per level instead of one per group. The visited set guarantees each group is expanded once, so cycles and diamonds cost nothing extra. The depth limit, for example 10 levels, protects against pathological but acyclic chains and flags data that no real organisation needs.

Java
Set<String> roles(String userId) {
Set<Long> visited = new HashSet<>();
Set<Long> frontier = new HashSet<>(repo.directGroupIds(userId));
int depth = 0;
while (!frontier.isEmpty()) {
if (++depth > MAX_GROUP_DEPTH) {
metrics.counter("groups.depth_limit_hit").increment();
break; // or fail closed, see below
}
frontier.removeAll(visited);
visited.addAll(frontier);
frontier = new HashSet<>(repo.parentGroupIdsOf(frontier)); // one query for the whole level
frontier.removeAll(visited);
}
return repo.rolesOfGroups(visited); // one query for all roles
}
// Developers <-> Engineering cycle: visited = {Developers, Engineering}, finishes after 2 levels

Notice the decision when the depth limit is hit. For permissions, failing closed, denying or granting only what was resolved so far and alerting, is safer than guessing. The traversal is now O(V + E) over the user's reachable part of the graph, with a handful of queries in total.

4Removing Repeated Work: Caching or a Closure Table

Even a correct traversal repeats the same work on every request. Two designs remove it. The first is caching: store the resolved set of groups, or the final roles, per user, or better per group, since groups are shared, with a short expiry and explicit invalidation. When a membership changes, the service publishes an event, and the caches drop the entries for the affected group and everything below it. Per-group caching keeps invalidation small: changing Engineering's parent only invalidates groups that can reach Engineering.

The second is precomputing the closure in the database. A closure table stores one row for every pair (group, ancestor) with the distance between them. A user's roles are then a single indexed join: user's direct groups, joined to the closure table, joined to group roles. The table is maintained when memberships change, inside the same transaction, which is easy for adding an edge (connect every ancestor of the parent with every descendant of the child) and more work for removing one. Because memberships change rarely and reads happen on every request, paying on write is the right trade-off.

SQL
-- closure(group_id, ancestor_id, depth): one row per reachable pair, including (g, g, 0)
SELECT DISTINCT gr.role
FROM user_group ug
JOIN group_closure c ON c.group_id = ug.group_id
JOIN group_role gr ON gr.group_id = c.ancestor_id
WHERE ug.user_id = :userId; -- one indexed query, no traversal at request time

5Doing It in SQL With WITH RECURSIVE

If we do not want a closure table, a recursive query can walk the graph inside the database in one round trip. It must have a cycle guard and a depth limit, or it has exactly the same bug as the Java loop.

SQL
WITH RECURSIVE reach(group_id, depth, path) AS (
SELECT ug.group_id, 1, ARRAY[ug.group_id]
FROM user_group ug WHERE ug.user_id = :userId
UNION ALL
SELECT gm.parent_id, r.depth + 1, r.path || gm.parent_id
FROM reach r JOIN group_membership gm ON gm.child_id = r.group_id
WHERE NOT gm.parent_id = ANY(r.path) -- cycle guard
AND r.depth < 10 -- depth limit
)
SELECT DISTINCT gr.role
FROM reach JOIN group_role gr ON gr.group_id = reach.group_id;

PostgreSQL 14 and later can express the guard with the CYCLE clause instead of the path array. Note that the path guard stops cycles but, like the Java version without a visited set, can still expand a shared ancestor once per distinct path, so for wide, diamond-shaped hierarchies the closure table or cached BFS is better.

6Preventing Cycles at Write Time

The cleanest protection is to never store a cycle. Before adding "group C becomes a member of group P", the service checks whether P is already a member of C, directly or through other groups; in other words, whether C is an ancestor of P. If it is, the new edge would close a loop, and the request is rejected with a clear message. With a closure table this is one lookup: is there a row with group P and ancestor C? Without one, it is a BFS from P upwards with a visited set. Running the check and the insert in one transaction, with a lock on the affected groups, prevents two concurrent changes from creating a cycle together, a classic write skew.

7Follow-up questions

Why cache per group rather than per user?

Many users share the same groups, so caching each group's ancestor set means one computation serves thousands of users, and a membership change invalidates only the groups below the changed edge. A per-user cache needs a way to find every user affected by a change, which is harder and larger.

How would you clean up the cycles that already exist?

Run a cycle detection job over the whole membership graph, such as a DFS with three colours or Tarjan's strongly connected components algorithm, report each cycle to the owning administrators, and agree on which edge to remove. Until then, the resolver's visited set keeps requests safe.

Should a request fail when the depth limit is hit?

For authorisation it should fail closed: use only what was resolved within the limit, or deny the request, and alert, rather than silently granting more. Real hierarchies rarely exceed 5 or 6 levels, so hitting a limit of 10 almost always means bad data.

8Conclusion

In this answer, we saw that nested groups form a general graph, and a resolver without a visited set walks a cycle such as A in B and B in A until the request times out, while deep or diamond-shaped hierarchies make it slow by re-expanding groups with a query per group on every request. A BFS with a visited set, a depth limit and one query per level fixes correctness; caching per group with invalidation, or a closure table maintained on write, removes the repeated work; WITH RECURSIVE needs a cycle guard; and checking reachability before adding a membership stops cycles from being stored at all.

What to say in the interviewAbout 90 seconds aloud

Open with

Groups containing groups make this a graph, and the request that never finished is the classic sign of a cycle: say Developers is in Engineering and Engineering is in Developers, and the resolver has no visited set, so it keeps expanding the same two groups until the timeout.

Then, if they want more

The slow users have the same structural problem: the resolver walks deep or wide hierarchies on every request, probably with a database query per group, and without a visited set it re-expands shared ancestors once per path.

So first I would fix the traversal: a BFS with a visited set, so each group is expanded once, a depth limit around 10 that fails closed and raises a metric, and one query per level rather than per group.

Then I would remove the repeated work, since memberships change rarely but checks happen constantly: either cache the resolved ancestor set per group with invalidation driven by membership change events, or precompute a closure table of group and ancestor pairs, maintained in the same transaction as membership changes, so a user's roles become one indexed join.

A recursive SQL query is another option, but it needs a cycle guard and a depth limit too. Finally, I would prevent cycles at write time: before adding group C into group P, check whether C is already an ancestor of P and reject the change if so.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A permissions service resolves a user's effective roles by walking group memberships...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/2b83702815/