Quick question, has anyone seen this weird error? with my token refresh logic when processing high-volume Architect flow executions. My Rails middleware uses Faraday to ingest webhooks and then dispatches Sidekiq jobs to batch-update call recordings. The issue is that my access token expires exactly in the middle of a batch of 50 requests, causing the subsequent calls to fail with a 401 Unauthorized.
I am using a simple in-memory cache with a TTL slightly less than the token’s lifetime. The refresh logic looks like this:
def get_valid_token
return @token if @token && @token.expires_at > Time.now + 5.minutes
refresh_token!
end
The problem is that multiple Sidekiq workers call get_valid_token concurrently. They all see the token as expired, trigger a refresh, and some complete before the refresh is actually persisted, or they get a new token while others are still using the old one.
Environment details:
- Ruby 3.2.2
- Sidekiq 7.2.0
- Faraday 2.9.0
- Genesys Cloud Platform API v2
I need a thread-safe way to ensure only one refresh happens and that all waiting threads get the new token. Should I use a Mutex around the refresh logic, or is there a better pattern for this in a multi-worker environment?