Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

A shared library injects a request-scoped 'CurrentUser' proxy into singletons across 50 services. Some services now run the same code from Kafka listeners and fail. How would you redesign it?

The request-scoped CurrentUser proxy can only find a user while an HTTP request is bound to the current thread, so the same library code fails when a Kafka listener calls it. We redesign it as a CurrentUser abstraction that does not know where the user comes from, with one adapter for web requests and one for messaging that set and clear the user at each entry point, or we pass the user explicitly from the edge of each entry point. Either way, the library fails with a clear message when no user context exists, and it is tested from both web and non-web entry points.

Why this question is asked

Shared libraries often start life in web services, where a request-scoped bean is the easiest way to know who is calling. Years later, the same services consume Kafka topics, and the same library code runs on a listener thread with no HTTP request in sight. Across 50 services, that becomes a steady stream of failures, or worse, actions recorded without a user. Interviewers ask this design question to see whether we can fix the root cause in the library rather than patching each service. In this answer, we will see exactly why the proxy fails from Kafka, design a CurrentUser abstraction with adapters, compare it with passing the user explicitly, and look at failure messages, tests and rollout.

1Why the Proxy Fails From a Kafka Listener

The library declares something like @RequestScope class CurrentUser, filled by a web filter from the security token. Singletons across the services inject it, and @RequestScope gives them a scoped proxy. Each call on the proxy asks the request scope for the instance of the current request, and the request scope finds the current request through RequestContextHolder, which holds it in a ThreadLocal on the thread handling the HTTP request.

A Kafka listener runs on the listener container's consumer thread. No HTTP request was ever bound to that thread, so the first call on the proxy fails with a ScopeNotActiveException caused by an IllegalStateException saying no thread-bound request was found. The library was never wrong for web callers; it just encoded the assumption that every caller is a web request.

Java
@Component @RequestScope
public class CurrentUser { // in the shared library today
private String userId;
public String id() { return userId; }
}
@Service
class AuditService { // shared library, used by 50 services
private final CurrentUser user;
AuditService(CurrentUser user) { this.user = user; }
void record(String action) { log.info("{} did {}", user.id(), action); }
}
// From a controller: alice did approve-order
// From a @KafkaListener: ScopeNotActiveException ... No thread-bound request found

2Design 1: A CurrentUser Abstraction With Adapters

The first redesign separates the question "who is the current user?" from the question "where does that information come from?". The library defines a small interface, and its implementation reads from a framework-neutral holder. Each kind of entry point has an adapter that fills the holder before the work starts and clears it afterwards: a servlet filter for HTTP, using the authenticated principal, and a wrapper for Kafka listeners, using a header that the producer sets.

Java
public interface CurrentUser {
UserId id(); // throws if no user context
Optional<UserId> find();
}
public final class UserContext implements CurrentUser {
private static final ThreadLocal<UserId> CURRENT = new ThreadLocal<>();
public static <T> T runAs(UserId user, Supplier<T> work) {
UserId previous = CURRENT.get();
CURRENT.set(user);
try { return work.get(); } finally { CURRENT.set(previous); }
}
@Override public Optional<UserId> find() { return Optional.ofNullable(CURRENT.get()); }
@Override public UserId id() {
return find().orElseThrow(() -> new MissingUserContextException(
"No user context on thread " + Thread.currentThread().getName()
+ ": wrap the entry point with UserContext.runAs (HTTP filter or Kafka adapter)"));
}
}
// Kafka adapter in the library
@KafkaListener(topics = "orders")
void onOrder(ConsumerRecord<String, OrderEvent> rec) {
UserId user = UserId.of(new String(rec.headers().lastHeader("x-user-id").value(), UTF_8));
UserContext.runAs(user, () -> { orders.handle(rec.value()); return null; });
}
// From a controller: alice did approve-order
// From a @KafkaListener: bob did approve-order (bob from the x-user-id header)
Step throughCurrentUser after the redesign
  1. Entry pointsHTTP request, Kafka record, batch job
  2. Adaptersfilter, Kafka wrapper, job launcher set and clear the user
  3. CurrentUser interfaceid() or a clear MissingUserContextException
  4. Shared library codeAuditService, data filters, clients

4 layers, from the top down. Step through them one at a time.

The library no longer knows about HTTP; each entry point supplies the user.

Notice that the shared AuditService does not change at all except for depending on the interface instead of the request-scoped class. In practice, the library would ship the Kafka adapter as a reusable piece, for example a RecordInterceptor or a small listener wrapper, so service teams do not write header parsing themselves. If the services already use Spring Security, the holder can be SecurityContextHolder itself, which is thread-bound but not tied to HTTP, and the Kafka adapter sets an Authentication instead.

3Design 2: Pass the User Explicitly

The second option is to stop looking the user up at all. The edge of each entry point, the controller or the listener method, determines the user and passes it as a parameter to the library methods that need it, such as audit.record(user, action). This makes every dependency on the user visible in the signatures, works across threads and async calls without any propagation, and makes tests trivial.

The cost is changing signatures across the library and its callers in 50 services, which is a large, coordinated change. A practical path is to do both: the abstraction fixes the Kafka failures quickly, and the most important operations, such as authorisation and audit, move to explicit parameters over time.

4Failing Clearly When There Is No User

Whichever design we choose, the worst outcome is silent: a library that catches the error and records "anonymous" or a default user. That hides bugs and can break auditing and authorisation. So the library should fail fast with a message that names the problem and the fix, as the MissingUserContextException above does. For code paths that legitimately run without a user, such as a system job, the adapter should set an explicit system identity, for example UserId.system("nightly-reconciliation"), so the audit trail says exactly what happened.

5Testing and Rolling It Out

The bug existed because the library was only tested from web requests. The new version should have tests that call each public operation from three contexts: inside an HTTP request through MockMvc, inside a Kafka listener with an embedded broker or Testcontainers, and with no context at all, which must produce the clear exception. A test with a single-thread executor should also check that the user does not leak from one task to the next.

For the rollout, we release the library with the new interface while keeping the old request-scoped bean as a deprecated adapter that fills the holder, so web services keep working without changes. Kafka-consuming services adopt the new adapter first, and we remove the deprecated bean once no service uses it.

6Follow-up questions

Why not make the web filter also set the user for Kafka by copying it into the message?

Copying the user into a message header is part of the answer, but on the producer side. The consumer still needs an adapter that reads the header and sets the context, because the consumer thread has no request. The header also needs care: it should carry a verified identity, for example a signed token or a service identity, not a value any producer can forge.

Would a TaskDecorator solve the Kafka problem?

No. A TaskDecorator copies context from the submitting thread to an executor thread, which helps @Async. A Kafka listener is not submitted from a request thread; its work starts on the consumer thread with a message. The context must come from the message itself, which is why messaging needs its own adapter.

Should the library use ScopedValue instead of ThreadLocal?

Scoped values, final in Java 25, fit this design well, because runAs is exactly a bounded scope where the value is set and automatically unset at the end. They are immutable and cannot leak past the scope. The library can switch the holder's implementation later without changing the CurrentUser interface, which is another benefit of the abstraction.

7Conclusion

In this answer, we saw that a request-scoped CurrentUser proxy only works while an HTTP request is bound to the thread, so shared code fails when called from Kafka listeners. We redesigned it as a CurrentUser interface backed by a neutral holder, with adapters for HTTP and messaging that set and clear the user, and compared that with passing the user explicitly from each entry point. In both cases the library fails with a clear message when no user exists, uses an explicit system identity for jobs, and is tested from web, messaging and no-context entry points.

What to say in the interviewAbout 90 seconds aloud

Open with

The root cause is that the request-scoped proxy finds the user through the HTTP request bound to the current thread, and a Kafka listener's consumer thread never has one, so the library fails with a no thread-bound request error.

Then, if they want more

The library encoded the assumption that every caller is a web request. I would redesign it so the library asks a CurrentUser interface, which does not care where the user comes from.

Its implementation reads a framework-neutral holder, a ThreadLocal or Spring Security's SecurityContextHolder, and each entry point has an adapter that sets the user and clears it in a finally block: a servlet filter from the authenticated principal, and a Kafka wrapper or record interceptor from a verified header set by the producer.

The library ships those adapters so 50 teams do not each write them. For the most important operations, like audit and authorisation, I would move over time to passing the user explicitly from the controller or listener, because that cannot be lost across threads.

If there is no user, the library throws a clear exception that says how to fix it, never a silent anonymous user, and batch jobs set an explicit system identity. I would test every operation from MockMvc, from a Kafka listener and with no context, and roll out with the old bean as a deprecated adapter.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
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 "A shared library injects a request-scoped 'CurrentUser' proxy into singletons across 50...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/0375bc44b1/