Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A team proposes a custom annotation @Cacheable-like @Memoize that a library processes at run time with reflection on every call. Review this design: what are the costs and the alternatives?

Processing @Memoize with reflection on every call is slow unless the annotation metadata is cached per Method, and run-time processing needs proxies or bytecode weaving, which miss self-calls and cannot intercept final or private methods. Alternatives are compile-time annotation processing, which generates the caching code so no reflection runs per call, or, usually best, an existing mechanism such as Spring's cache abstraction with @Cacheable and a real cache like Caffeine. Whatever we choose, the annotation's contract must define keys, expiry, size limits, null and exception handling, and thread safety.

Why this question is asked

A team proposing its own caching annotation is a common design review, and it is a good test of judgement: the idea is easy to sketch and hard to get right. Interviewers ask it to see whether we can find the hidden costs in a run-time annotation design and whether we know when to reuse an existing tool. In this answer, we will walk through what the proposed library does on each call, find its performance cost and its proxy limits, compare a compile-time approach and Spring's cache abstraction, define the semantics the annotation must promise, and finish with how to test that it is actually honoured.

1What the Proposal Does on Every Call

As proposed, every call to a @Memoize method goes through an interceptor that asks the Method for its annotation, reads its attributes, builds a key from the arguments, looks in a map, and either returns the cached value or calls the real method and stores the result.

Java
// The proposal, simplified
Object intercept(Object target, Method m, Object[] args) throws Throwable {
Memoize memo = m.getAnnotation(Memoize.class); // reflective lookup on every call
if (memo == null) return m.invoke(target, args);
List<Object> key = List.of(m.getName(), Arrays.asList(args)); // key from method name and args
Object hit = cache.get(key);
if (hit != null) return hit;
Object result = m.invoke(target, args); // reflective invoke
cache.put(key, result); // unbounded map, no expiry
return result;
}
Step throughA @Memoize call as proposed
CallerProxy / interceptorCache mapReal method
price(sku)
getAnnotation(Memoize.class) every call
get(key)
miss
Method.invoke(target, args)
result
put(key, result), no bound or expiry

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

It works in a demo. Each line, though, hides a question we have to answer before it goes into production code that many services depend on.

2Cost 1: Reflection on Every Call

Method.getAnnotation is not free: it looks up the annotation in the method's annotation map and returns a proxy object for it, and reading attributes goes through that proxy. Method.invoke adds argument boxing and access checks, although modern JDKs make it much faster than it used to be. Spread over a hot method called 50,000 times a second, these costs show up in profiles, and they are pure overhead because the answer never changes: a method either has @Memoize or it does not.

The fix is to resolve metadata once per Method and cache it, for example in a ConcurrentHashMap<Method, MemoPlan> computed on first use, where the plan holds the parsed attributes and the key strategy. Spring does exactly this in its cache and transaction interceptors.

Java
private final Map<Method, Optional<MemoPlan>> plans = new ConcurrentHashMap<>();
Optional<MemoPlan> plan(Method m) {
return plans.computeIfAbsent(m, k -> Optional.ofNullable(k.getAnnotation(Memoize.class)).map(MemoPlan::of));
}

3Cost 2: Proxies and Weaving Have Blind Spots

A library processing annotations at run time can only intervene if calls pass through it. That means either a proxy around the object, as Spring AOP uses, or bytecode weaving that rewrites the class, as AspectJ does. Proxies have well-known limits. A call from one method to another inside the same object, this.price(sku), never passes through the proxy, so memoization silently does not happen. Final methods cannot be overridden by a subclass proxy, private methods cannot be intercepted, and JDK interface proxies only see interface methods.

Weaving removes those limits but adds a build or agent step, makes stack traces harder to read, and is one more thing to keep working across JDK upgrades. Neither is wrong, but the team must choose one deliberately and document its limits in the annotation's Javadoc.

4Alternative 1: Generate the Code at Compile Time

A compile-time annotation processor can read @Memoize during compilation and generate a decorator class, for example PriceServiceMemoized, that wraps the original and contains plain, ordinary caching code. There is no reflection per call, nothing to discover at startup, and the generated code is visible and debuggable. It suits GraalVM native images and fast-starting services well.

The cost is that standard annotation processors cannot modify existing classes, only generate new ones, so callers must use the generated type, typically through dependency injection. Writing and maintaining a processor is also more specialised work than an interceptor.

5Alternative 2: Reuse Spring's Cache Abstraction

In a Spring application the strongest option is usually not to build anything. Spring's cache abstraction already does what @Memoize proposes, with the metadata caching, key generation and proxy support solved, and it delegates storage to a real cache library.

Java
@Configuration
@EnableCaching
class CacheConfig {
@Bean
CacheManager cacheManager() {
CaffeineCacheManager m = new CaffeineCacheManager("prices");
m.setCaffeine(Caffeine.newBuilder().maximumSize(10_000).expireAfterWrite(Duration.ofMinutes(5)));
return m;
}
}
@Service
class PriceService {
@Cacheable(cacheNames = "prices", key = "#sku", sync = true) // sync: one computation per key under load
public Price price(String sku) { ... }
}
Comparing the options
OptionPer-call costMain limits
Proposed: reflection every callAnnotation lookup + invokeSlow, unbounded, proxy blind spots
Run-time with cached metadataMap lookup + invokeProxy or weaving limits remain
Compile-time generated decoratorPlain method callCallers use generated type; processor upkeep
Spring @Cacheable + CaffeineMap lookup via proxySelf-calls skip the proxy, as documented

It has the same self-call limit as any proxy, but the limit is documented and familiar to every Spring developer, along with eviction through @CacheEvict, metrics, and tested integration with Caffeine, Redis and others. A custom annotation is only justified if it adds something Spring's cache cannot, and then it can often be a composed annotation over @Cacheable.

6Semantics the Annotation Must Define

Whatever the implementation, the annotation's contract must say what memoization means. Keys: which arguments form the key, and whether those types have correct equals and hashCode; an array argument, for instance, compares by identity. Expiry and size: an unbounded map is a memory leak waiting to happen, so we need a maximum size and a time to live. Nulls and exceptions: is a null result cached, and are exceptions cached or retried. Thread safety: two threads missing the same key at once should not both run an expensive computation, which is the cache stampede problem; Caffeine's get(key, loader) or @Cacheable(sync = true) solve it.

Writing these rules down usually decides the debate. Most teams find that a well-configured existing cache already answers every one of them.

7Follow-up questions

How would you test that the annotation is actually honoured?

Through the real mechanism, never by calling the class directly. In a Spring test we load a context with the caching configuration, call the annotated method twice through the injected bean, and assert with a spy or a counter on the underlying dependency that it ran only once. We add a test for a different argument causing a second computation, a test for expiry using a controllable clock or ticker, and a test that documents the self-call limit, so nobody assumes it works there.

Is Method.invoke still slow in recent JDKs?

Much less than it was. Since Java 18, core reflection is implemented with method handles, and the JIT can optimise hot reflective calls well. The bigger cost in this design is repeated annotation lookup and the unbounded map, and the most expensive problem is correctness, not speed.

When is a custom memoization annotation justified?

When it encodes an organisational rule Spring's annotations cannot, such as a mandatory tenant id in every key, and then it is best built as a thin composed annotation or a custom KeyGenerator on top of Spring's cache abstraction rather than a new interception mechanism.

8Conclusion

In this answer, we reviewed a run-time @Memoize design. Reflective lookup on every call is wasted work unless metadata is cached per Method, and run-time processing relies on proxies or weaving, which miss self-calls and final or private methods. A compile-time processor can generate caching code with no reflection, and Spring's cache abstraction with Caffeine already provides the feature with known limits. Whichever we pick, the contract must define keys, expiry, size, nulls, exceptions and thread safety, and tests must call through the real mechanism to prove the annotation is honoured.

What to say in the interviewAbout 90 seconds aloud

Open with

I would push back on building it as proposed. First, cost: reading the annotation reflectively on every call is pure overhead, since whether a method has @Memoize never changes, so at minimum the metadata must be resolved once per Method and cached, which is what Spring's own interceptors do.

Then, if they want more

Second, mechanism: processing at run time means proxies or bytecode weaving. With proxies, self-calls inside the class skip the cache, and final or private methods cannot be intercepted; weaving fixes that but adds a build or agent step. Third, alternatives.

A compile-time annotation processor could generate a decorator with plain caching code and no reflection, which is great for startup and native images, but processors cannot modify existing classes, so callers use the generated type.

In a Spring application, though, I would mostly ask why not use @Cacheable with Caffeine, which already handles keys, metadata caching, eviction, metrics and sync loading.

Fourth, semantics, which the proposal does not define: which arguments form the key and whether they have proper equals and hashCode, maximum size and expiry, because an unbounded map is a leak, whether nulls and exceptions are cached, and how concurrent misses are handled to avoid a stampede.

Finally, I would require tests that call through the Spring proxy twice and assert the underlying method ran once.

About this answer

Last updated
12 November 2026
Versions it names
Java 18
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 team proposes a custom annotation @Cacheable-like @Memoize that a library processes at...": https://scrivio-interview-library.netlify.app/java/annotations/2ab08558f4/