Hello everyone. What would be the best way to co-ordinate refresh and access tokens in Cloudflare fu

Hello everyone. What would be the best way to co-ordinate refresh and access tokens in Cloudflare functions? My function will login to an ATProto personal data server and get the access and refresh tokens in return. I'm then thinking about storing these tokens and then refreshing on demand.

A Durable Object would allow me to co-ordinate the renewal, but adds complexity and latency as it is only hosted in one datacenter. I could potentially cache the token values in memory on the workers as I know the expiry time. It seems using Durable Objects with a Pages project would require you to create a separate worker for the durable object and then binding the durable object to the pages project complicating things a bit more.

KV storage might be used, but don't offer the one off guarantee for renewing values. Two function invocations might end up updating the tokens at the same time. This might not be a huge issue in reality?

D1 might be used as well, but seems overkill to introduce SQL for such a simple task. And I'm not sure I can lock a table while waiting for the token refresh in any case.

Maybe I should instead introduce a Cloudflare Cron Trigger that runs and renews the tokens and then have the scheduler event function stash the tokens in KV so workers can access them when needing to make authenticated requests. Only "issue" with this is that I'd renew the token more often than possibly needed given my traffic patterns.
Was this page helpful?