Quick revision
The short answer
We implement Caffeine's Expiry interface so that expireAfterCreate and expireAfterUpdate return the time until the token's own expiry minus 30 seconds, clamped at zero, and expireAfterRead returns currentDuration so reads do not extend it. In Redis we store the token with SET token:<partner> <value> PXAT <expiry in epoch milliseconds minus 30000>, an absolute expiry time available since Redis 6.2.
What to remember
In this answer, we saw that per-entry expiry in Caffeine comes from the Expiry interface: create and update return the token's remaining life minus 30 seconds, read returns currentDuration so tokens never slide, and the value is clamped at zero so tokens near expiry are not cached. In Redis, SET with PXAT gives the same absolute expiry since 6.2 and avoids drift from late relative TTLs. Early refresh hides the fetch from callers, and a 401 invalidates the token and retries once.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We implement Caffeine's Expiry interface so that expireAfterCreate and expireAfterUpdate return the time until the token's own expiry minus 30 seconds, clamped at zero, and expireAfterRead returns currentDuration so reads do not extend it. In Redis we store the token with SET token:<partner> <value> PXAT <expiry in epoch milliseconds minus 30000>, an absolute expiry time available since Redis 6.2.
Why this question is asked
Access tokens are a perfect example of data where one TTL does not fit all entries: each partner tells us how long its token lives, and using a token after that moment fails the call. Interviewers ask this because it tests whether we know that Caffeine supports per-entry expiry and whether we think about clocks, safety margins and failure handling. In this answer, we will see why a fixed TTL fails here, implement the Expiry interface, build the cache, handle tokens close to expiry, write the Redis equivalent with an absolute expiry, and finish with refreshing early and reacting to a 401.
1Why a Fixed TTL Does Not Work
Each token response carries its lifetime, for example expires_in: 300 for one partner and expires_in: 3600 for another. With expireAfterWrite of 5 minutes for everyone, we would fetch the one-hour tokens twelve times more often than needed. With 60 minutes, the five-minute tokens would be served long after they died, and every call would fail until the entry expired.
Even with the right lifetime, a token that is valid when we read it from the cache can expire while the request is on its way to the partner. A request that takes two seconds, plus some clock difference between our server and theirs, is enough. So we drop each token a little before its real expiry, here 30 seconds, which gives in-flight calls room to finish.
2Implementing the Expiry Interface
Caffeine's Expiry interface lets the cache ask, for each entry, how long it should live. It has three methods, called when an entry is created, when it is replaced, and when it is read. Each returns a duration in nanoseconds from now. First we turn the token response into an absolute expiry time at the moment we receive it.
Notice what each method does. expireAfterCreate computes the remaining time from the token itself, so a 300-second token lives 270 seconds and a 3,600-second token lives 3,570. expireAfterUpdate does the same, because a refreshed token must get its own lifetime rather than keep the old one's. expireAfterRead returns currentDuration, the time the entry already had left, which means a read changes nothing; returning anything else would turn this into sliding expiry, and a token must never live longer because it is popular.
3Building the Cache
We plug the Expiry into the builder and give the cache a loader, so a missing or expired token is fetched automatically.
Because a LoadingCache runs the loader at most once per key at a time, twenty threads that need the acme token at the moment it expires cause one fetch, not twenty. The maximumSize is only a guard; with one token per partner we will never reach it.
Recent Caffeine versions (3.1 and later; check your version) also offer static factories such as Expiry.creating((key, value) -> duration) and Expiry.writing(...), which build an Expiry from a lambda. creating only sets the duration when the entry is created, so for tokens that are also replaced in place, writing, which covers both create and update, is the closer match. Writing the class by hand, as above, keeps all three decisions visible.
4Tokens That Are Already Close to Expiry
Sometimes a token response arrives with a very short lifetime, or our clock is ahead of the partner's, so expiry minus 30 seconds is already in the past. That is why nanosLeft clamps the value at zero. A duration of zero tells Caffeine the entry is already expired, so the caller gets this one token but the cache does not keep it, and the next call fetches a new one.
Without the clamp we would return a negative number. Caffeine expects a non-negative duration, and we should not rely on what an odd value happens to do; the clamp states the intent clearly.
5The Same Rule in Redis
If the tokens are shared by several instances through Redis, we want the same behaviour: each key expires 30 seconds before its token. Redis 6.2 added PXAT and EXAT to SET, which take an absolute Unix time in milliseconds or seconds rather than a relative TTL.
The reason to prefer the absolute form is that the expiry is calculated once, from the token's own expiry time. With a relative TTL we would compute expiresAt minus now at the moment of writing, and any delay between computing and writing, such as a retry or a slow connection, would make the key outlive the token by that delay. PXAT also makes the guard simple: if the target time is already past, we do not write at all.
6Refreshing Early and Handling a 401
Expiry alone means that, once per token lifetime, a request finds no token and waits for a fetch. To avoid that pause we can refresh early: when a read sees that less than, say, two minutes remain, it calls tokens.refresh(partner), which reloads the token in the background while callers keep using the current one. Caffeine's refreshAfterWrite uses one fixed duration for all entries, so with varying lifetimes an explicit check like this is the simpler option.
Finally, the partner is the authority on whether a token is valid. If a call returns 401 Unauthorized, the token may have been revoked or the clocks may disagree more than we assumed. The client should call tokens.invalidate(partner), fetch a fresh token, and retry the call once. Retrying only once matters: if the new token is also refused, the problem is not the cache, and looping would just hammer the partner's token endpoint.
- tokens.get(partner)Loads once if missing or expired
- Less than 2 minutes left?Remaining life of the tokenYesrefresh(partner) in backgroundNoUse it as is
- Call the partner APIBearer token in the header
- Response is 401?Token refusedYesinvalidate, fetch, retry onceNoDone
4 steps in order. Play them, or step through them one at a time.
7Follow-up questions
Why is an absolute expiry safer than a relative one here?
Because the token's death is an absolute moment chosen by the partner. A relative TTL has to be recomputed from the current time whenever we write, and any delay or retry between computing and writing stretches the key past that moment. With PXAT, or with an Instant stored in the token for Caffeine, the expiry is fixed once from the response and cannot drift.
Why use a Clock instead of Instant.now()?
So tests can control time. With an adjustable Clock, a test can create a token that expires in 40 seconds and check that the cache keeps it for 10, or one that expires in 20 seconds and check that it is not kept at all. Caffeine accepts a Ticker for the same reason.
8Conclusion
In this answer, we saw that per-entry expiry in Caffeine comes from the Expiry interface: create and update return the token's remaining life minus 30 seconds, read returns currentDuration so tokens never slide, and the value is clamped at zero so tokens near expiry are not cached. In Redis, SET with PXAT gives the same absolute expiry since 6.2 and avoids drift from late relative TTLs. Early refresh hides the fetch from callers, and a 401 invalidates the token and retries once.
Open with
I would implement Caffeine's Expiry interface. When I receive a token I convert expires_in into an absolute Instant right away. Then expireAfterCreate returns the time from now until that Instant minus 30 seconds, in nanoseconds, and expireAfterUpdate does the same so a replaced token gets its own lifetime. expireAfterRead returns currentDuration, so reading a token never extends it.
Then, if they want more
I clamp the result at zero: if a token is already within 30 seconds of expiry, the caller can use it, but the cache drops it immediately. The cache is Caffeine.newBuilder().expireAfter(new TokenExpiry(clock)).maximumSize(1000).build with the token client as loader, so concurrent misses for one partner cause one fetch.
Newer Caffeine versions have Expiry factory methods too, but the explicit class makes the read behaviour obvious. In Redis I would use SET with PXAT, the expiry time in epoch milliseconds minus 30 seconds, which exists since 6.2. It is safer than a relative TTL because the deadline is fixed once and does not stretch if the write is delayed.
On top, I refresh in the background when less than two minutes remain, and on a 401 I invalidate the token, fetch a new one and retry once.
About this answer
- Last updated
- 13 November 2026
- Versions it names
- Redis 6
- 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 "Implement per-entry expiry in Caffeine so each token is dropped 30 seconds before it...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/631fbd45bf/