Say I need to get an oauth token before calling another service. Let’s also say that that token expires after 15 minutes and can be cached for use in multiple requests. How can I use akka or akka-http to prefetch and refresh that token asynchronously such that I don’t introduce api call latency due to the oauth server?
Hi @Marcus-Rosti,
here’s a sketch how this could be implemented. One way to handroll such a cache could be an AtomicReference
that contains a future with the token and its expiration time. When the token value is requested there are multiple possible states:
- Future not yet completed: token update currently in progress. Just subscribe to (or return) the future of the token as it should eventually return a valid token.
- Future already completed and token still valid: return the token
- Future already completed and token is expired: compare-and-swap the value to a new promise and start the process to refresh the token
With just that the token will be lazily refreshed, so some requests might have to wait every 15 minutes. You can also schedule a job (using Akka’s scheduler
) to refresh the token pre-actively in the background, maybe some time before it runs out to avoid the latency in all cases.
You could also create a single entry cache using the caching infrastructure in akka-http-caching
which basically implements something similar to the above.
Johannes