Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Your domain has users, groups and permissions with many-to-many links that are queried in authorization checks on every request. How would you design the model and its access patterns?

We model the user-group, group-permission and any direct user-permission links as explicit link tables (as entities or plain SQL) with indexes on both foreign keys, and we never load object graphs to answer an authorization check. Instead one query returns the user's effective permission set, which we cache per user with clear invalidation when memberships or grants change. If checks are still hot, we precompute an effective-permission table, and we decide which service owns this data so other teams consume it rather than copy it.

Background to this question

Authorization runs on every request, so its data model has a direct effect on latency and database load across the whole system. A mapping that is fine for an admin screen, User with a Set of Group each with a Set of Permission, becomes a disaster when it is walked on every API call. This question is asked at a senior level because the answer must cover the schema, the query, caching with correctness, and ownership across teams. In this answer, we will recap the data, design the tables, write the access query, add caching and invalidation, consider precomputation, and settle ownership.

1A Quick Recap of the Data

Users belong to groups, groups are granted permissions, and sometimes users are granted permissions directly. All three relationships are many-to-many: one user is in several groups, one group has many users, and so on. The question an authorization check asks is always the same: does user 42 have permission orders:refund? The answer is the user's effective permissions, the union of direct grants and grants through every group.

2Designing the Tables

We make the link tables explicit rather than hiding them behind @ManyToMany. Each one has a composite primary key and an index on the reverse direction, because we query both ways: which groups is this user in, and which users are in this group.

SQL
CREATE TABLE user_group (
user_id BIGINT NOT NULL REFERENCES app_user(id),
group_id BIGINT NOT NULL REFERENCES app_group(id),
added_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, group_id) -- serves: groups of a user
);
CREATE INDEX ix_user_group_group ON user_group (group_id); -- serves: users of a group
CREATE TABLE group_permission (
group_id BIGINT NOT NULL REFERENCES app_group(id),
permission_id BIGINT NOT NULL REFERENCES permission(id),
PRIMARY KEY (group_id, permission_id)
);
CREATE INDEX ix_group_permission_perm ON group_permission (permission_id);

Explicit link tables also leave room for data on the link, such as added_at or an expiry, which audits usually want. In JPA they can be mapped as join entities (UserGroup with two @ManyToOne) for the admin screens, while the hot path uses a direct query.

3Querying the Permission Set Directly

The mistake to avoid is answering the check through the object graph: load the user, iterate groups, iterate each group's permissions. With 5 groups that is at least 1 + 5 + 5 queries, plus hundreds of entities in the persistence context, on every request. Instead we ask the database for exactly what we need, the permission names, in one query.

Java
@Query(value = """
SELECT p.name FROM permission p
JOIN group_permission gp ON gp.permission_id = p.id
JOIN user_group ug ON ug.group_id = gp.group_id
WHERE ug.user_id = :userId
UNION
SELECT p.name FROM permission p
JOIN user_permission up ON up.permission_id = p.id
WHERE up.user_id = :userId""", nativeQuery = true)
Set<String> effectivePermissions(long userId);
effectivePermissions(42); // [orders:read, orders:refund, reports:view] in about 1 ms with the indexes
Step throughAuthorization check with a cached permission set
RequestAuth serviceCacheDatabase
can user 42 refund?
get perms:42
miss
effectivePermissions(42)
{orders:read, orders:refund}
put perms:42, version 17
allowed

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

Only a cache miss reaches the database; the check itself is a set lookup.

Notice that the result is a set of strings, not entities: nothing is tracked, nothing lazy can escape, and it maps directly onto Spring Security authorities.

4Caching Effective Permissions and Invalidating Them

Even a 1 ms query adds up at thousands of requests per second, so we cache the effective set per user. The hard part is invalidation, because a stale cache in authorization is a security bug: a user removed from the admins group must lose access promptly. We invalidate on every change that can affect a user's set. Adding or removing a user from a group evicts that user. Changing a group's permissions affects all its members, so rather than evicting thousands of keys we keep a version number per group (or one global permissions version) and include it in the cache key or entry, so bumping it makes old entries miss.

We also cap staleness with a short time to live, say 60 seconds, as a safety net for missed events, and we publish change events so that every instance's local cache is evicted, not only the one that handled the change. For high-risk permissions, such as refunds above a threshold, we can skip the cache and check the database, accepting the extra query.

5Precomputing When Checks Are Very Hot

If the union query is still too expensive, for example with nested groups that require recursive queries, we can precompute an effective_permission(user_id, permission_id) table. It is denormalized, derived data maintained when memberships or grants change, either synchronously in the same transaction or by a job reacting to change events. The check becomes a primary key lookup. The cost is write amplification: granting a permission to a group of 10,000 users writes 10,000 rows, and the table must be rebuildable from the source tables if it ever drifts. That trade-off is worth it when reads outnumber permission changes by orders of magnitude, which is typical.

6Deciding Who Owns Authorization Data

Finally, across teams, authorization data needs one owner. If every service copies user and group tables into its own database, permissions diverge and revoking access becomes a hunt. A common design is an identity or authorization service that owns users, groups and grants, exposes the effective set through an API or embeds coarse permissions in tokens (for example JWT scopes), and publishes change events. Services then cache what they receive and evaluate fine-grained rules locally. Whichever model we choose, we write down who owns the data, how changes propagate and the maximum staleness each service may tolerate.

7Follow-up questions

Why not put all permissions in the JWT and skip the database?

Tokens are great for coarse permissions, but they cannot be revoked before they expire without extra machinery, and large permission sets bloat every request. A common compromise is short-lived tokens with coarse roles, plus a cached lookup for fine-grained permissions.

How do nested groups change the design?

Resolving groups inside groups needs a recursive query (WITH RECURSIVE in PostgreSQL) or a closure table that stores every ancestor-descendant pair. Both work; the closure table pairs naturally with the precomputed effective-permission approach.

How would you test the invalidation?

With an integration test that grants a permission, checks it is allowed, removes the user from the group, and asserts the next check is denied, across two application instances sharing the event channel. That proves eviction reaches every node.

8Conclusion

In this answer, we designed users, groups and permissions for an authorization check on every request. Link tables are explicit with indexes on both foreign keys, the check runs one query for the effective permission set instead of loading object graphs, the set is cached per user with versioned invalidation and a short time to live, a precomputed effective-permission table handles very hot or nested cases, and one service clearly owns the data and publishes its changes.

What to say in the interviewAbout 80 seconds aloud

Open with

Since this runs on every request, I'd design for the check, not for the object model. I'd make the link tables explicit, user_group, group_permission and user_permission, each with a composite primary key and an index on the reverse foreign key so both directions are fast.

Then, if they want more

For admin screens they can be join entities, but for the authorization path I'd never load User, then groups, then permissions through JPA associations, because that's several queries and lots of managed entities per request. Instead I'd write one query that returns the user's effective permission names, the union of group grants and direct grants, as a set of strings.

Then I'd cache that set per user. Invalidation is the important part because stale permissions are a security issue, so I'd evict a user on membership changes, use a per-group or global version number so a group's permission change invalidates all its members cheaply, broadcast change events to all instances, and keep a short TTL as a safety net.

If it's still hot, or we have nested groups, I'd precompute an effective_permission table that's maintained on change and rebuildable. And I'd agree which service owns authorization data, with others consuming its API or events rather than copying tables.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 "Your domain has users, groups and permissions with many-to-many links that are queried...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/c3311a2afd/