Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Several services need the same complex authorization rules (attribute-based, depending on user department, data classification and region). Compare embedding rules in each service with a central policy engine such as OPA or Cedar.

Rules embedded in Java in each service are fast and simple, but copies drift apart as services change at different speeds. A policy engine such as OPA or Cedar keeps the rules in one language and one repository, with tests, review and an audit trail of decisions. The price is a decision call with its latency and availability risk, which we reduce by running the engine as a sidecar or an in-process library, and a new dependency on consistent attributes from every service. In Spring we integrate through a custom AuthorizationManager so application code does not change.

Why this question is asked

Attribute-based rules, where access depends on properties of the user, the resource and the environment, grow quickly. A rule like analysts may read documents of their own department, unless the document is restricted, and only in their own region, is easy to write once. Written in eight services by eight teams, it becomes eight slightly different rules, and an auditor's question about who can read restricted EU documents has eight answers. Interviewers ask this design question to see how we weigh consistency against latency and operational cost. In this answer, we will recap ABAC, look at the embedded approach and its drift, see how a policy engine works, deal with latency and attributes, and connect it to Spring.

1A Quick Recap: Attribute-Based Access Control

Role-based access control asks which role the user has. Attribute-based access control (ABAC) asks a richer question: given attributes of the subject (department, clearance, region), the resource (owner department, data classification, region) and the context (time, network), is this action allowed? Roles are just one attribute among many.

ABAC rules are more expressive, which is exactly why they are harder to keep consistent: there are more inputs to get wrong, and small differences, such as one service treating confidential like restricted, change who sees what.

2Option 1: Rules Embedded in Each Service

The simplest approach is a Java class or an authorization bean in each service.

Java
boolean canRead(User u, Document d) {
return u.department().equals(d.department())
&& !d.classification().equals(Classification.RESTRICTED)
&& u.region().equals(d.region());
}
// Service A: as above
// Service B, two years later: also allows classification CONFIDENTIAL only for managers
// Service C: forgot the region check after a refactor

The strengths are real: the check is a method call taking microseconds, there is nothing extra to deploy, and developers debug it with their usual tools. The weakness is drift. Each copy evolves with its own service, and nobody can see all copies at once. A shared Java library reduces copying, but services upgrade the library at different times, and services in other languages cannot use it.

3Option 2: A Central Policy Engine

A policy engine separates the decision from the enforcement. Services ask the question, and the engine answers using policies written in a dedicated language and stored in one repository. OPA (Open Policy Agent) uses a language called Rego; Cedar, created by AWS, has a smaller language designed to be analysable. The same rule in each looks like this.

Java
# OPA, Rego (v1 syntax)
package docs.authz
default allow := false
allow if {
input.user.department == input.resource.department
input.resource.classification != "restricted"
input.user.region == input.resource.region
}
// Cedar
permit (principal, action == Action::"read", resource)
when {
principal.department == resource.department &&
resource.classification != "restricted" &&
principal.region == resource.region
};
Embedded rules versus a policy engine
AspectEmbedded in JavaPolicy engine
Decision latencyMicroseconds, in processMicroseconds as library, about 1 ms as sidecar
ConsistencyDrifts per serviceOne policy, one version
AuditRead code in every servicePolicy repo plus decision logs
LanguagesJava only, or reimplementedAny service that can call it
New dependencyNoneEngine availability and policy distribution
SkillsOrdinary JavaRego or Cedar for policy authors

Because policies live in one repository, they get code review by the security team, unit tests with sample inputs, versioned releases and a log of every decision with its inputs, which is very useful for audits. Changing the rule changes it everywhere at the same time.

4Latency and Availability of Decision Calls

The obvious worry is that every request now needs another call. A central OPA cluster reached over the network adds a few milliseconds per decision and, worse, becomes a single point of failure. So we avoid the network: OPA usually runs as a sidecar next to each service, where a decision over localhost takes around a millisecond, and policies are pushed to it as bundles from a central server. Cedar is commonly embedded as a library, through its Java bindings, so a decision is an in-process call.

The engine must fail closed: if it cannot answer, the request is denied. Because of that, the sidecar must be as reliable as the service itself, with health checks and alerts. Policy bundles are cached locally, so a broken policy server delays updates but does not stop decisions.

5Attributes Become Part of Authorization

A policy is only as correct as its inputs. If service A sends the user's department from the token and service B from a stale local copy, they get different answers from the same policy. So we define a shared input schema: where each subject attribute comes from (ideally claims in the access token or one directory lookup), how resource attributes are named, and which values are allowed, such as the exact spelling of classifications. Data quality becomes a security concern; a document stored without a classification needs a defined default, and the safe default is the most restrictive one.

6Connecting It to Spring With an AuthorizationManager

We keep Spring code unchanged by putting the engine behind an AuthorizationManager. The manager builds the input, asks the engine and returns the decision.

Java
@Component
class OpaAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
private final RestClient opa = RestClient.create("http://localhost:8181"); // sidecar
@Override
public AuthorizationDecision check(Supplier<Authentication> auth, RequestAuthorizationContext ctx) {
Jwt jwt = ((JwtAuthenticationToken) auth.get()).getToken();
Map<String, Object> input = Map.of(
"user", Map.of("department", jwt.getClaimAsString("department"),
"region", jwt.getClaimAsString("region")),
"action", ctx.getRequest().getMethod(),
"path", ctx.getRequest().getRequestURI());
try {
OpaResult r = opa.post().uri("/v1/data/docs/authz/allow")
.body(Map.of("input", input)).retrieve().body(OpaResult.class);
return new AuthorizationDecision(r != null && Boolean.TRUE.equals(r.result())); // {"result": true}
} catch (RestClientException e) {
return new AuthorizationDecision(false); // fail closed
}
}
record OpaResult(Boolean result) {}
}

URL-level checks often lack resource attributes such as the document's classification, so for object rules the same idea runs in method security: a bean called from @PreAuthorize or @PostAuthorize sends the loaded document's attributes to the engine. In both cases, controllers and services stay unaware of OPA or Cedar, and switching engines later touches one class.

7Follow-up questions

When would you keep rules embedded?

When rules are simple, owned by one service and not shared, such as only the author may edit a draft. Bringing in a policy engine for that adds a language and a component for no consistency gain.

How do you test policies?

Both OPA and Cedar support policy tests with sample inputs and expected decisions, run in CI on every change to the policy repository. We add a few end-to-end tests per service to prove the inputs it sends are correct.

Can a policy engine filter lists, not just answer yes or no?

Answering per item does not scale for a page of 10,000 documents. OPA supports partial evaluation, which turns a policy into conditions that can be translated into a query filter, and other systems offer similar features. Otherwise the service applies the same attributes as a database filter.

8Conclusion

In this answer, we compared rules embedded in each service, which are fast and simple but drift, with a central policy engine such as OPA or Cedar, which keeps one tested and audited policy. We handled decision latency with sidecars or in-process libraries and fail-closed behaviour, treated consistent attributes as part of authorization, and integrated the engine through a custom AuthorizationManager so Spring code stays unchanged.

What to say in the interviewAbout 90 seconds aloud

Open with

Embedding the rules in Java in each service is the fastest and simplest option: a method call, no new component, normal debugging. The problem is drift. Eight services with the same department, classification and region rule end up with eight slightly different versions, and an auditor cannot get one answer.

Then, if they want more

A policy engine like OPA with Rego, or Cedar, keeps the rules in one language and one repository, with review, tests, versioned releases and decision logs, and changing a rule changes it everywhere. The costs are a decision call and a new dependency.

I would avoid network calls by running OPA as a sidecar, about a millisecond over localhost, with policy bundles pushed and cached, or by embedding Cedar as a library, and the integration must fail closed.

The less obvious cost is attributes: every service must send the same subject and resource attributes with the same meaning, so we define an input schema and treat missing classifications as restricted.

In Spring I would hide the engine behind a custom AuthorizationManager for request rules, and a bean called from method security for object rules, so the rest of the code does not change. For rules shared across many services I would choose the engine; for simple rules owned by one service I would keep them embedded.

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.
Official documentation
Spring Security reference
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 "Several services need the same complex authorization rules (attribute-based, depending...": https://scrivio-interview-library.netlify.app/spring-boot/authorization/9d86c991da/