A bit of context 👋🏽
When calling Apis that use OAuth as authentication process, you need to generate an access token. And to get an access token, we have to use a refresh token stored in the server.
Here's the OAuth workflow to generate this access token:
Image source: developer.ebay.com
So what was the need? 🤔
An access token expires after a certain time, in minutes, hours, days, depending on the provider. So we need to refresh it time to time.
The issue was that different processes were refreshing the token at the same time, invalidating other's freshly generated access token.
So we had to find a way to be sure that only one process can refresh the token.
Here comes the gem 🚀
Today we introduce our new gem: Potlock - a Distributed Read-Write lock using redis
(available on Github here: GitHub - potloc/potlock)
This brand new gem only allows one simultaneous reader or writer. And if the lock is taken, any readers or writers who come along will have to wait.
Here's an example of how we use this gem at Potloc:
def token
lock = Potlock::client.new(key: "snapchat_api")
# Fetch the token, refresh it if not present
token = lock.fetch { refresh_token! }
# A token is invalid when empty or expired
raise InvalidToken unless valid?(token)
token
rescue InvalidToken => _e
# Generate and save a new token
lock.set { refresh_token! }
token = lock.get
end
This way, we are sure that all the processes will have the same valid access token and won't overwrite it at the same time 🎉
Interested in what we do at Potloc? Come join us! We are hiring 🚀
Top comments (0)