> ## Documentation Index
> Fetch the complete documentation index at: https://developers.pleo.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Race Condition Prevention

When multiple processes or threads detect that an OAuth 2.0 access token is expired, attempting to refresh the token simultaneously can cause **race conditions**. This may result in:

* Invalid or revoked refresh tokens
* Failed API calls due to stale tokens
* Inconsistent token state across different processes or servers

Proper handling of race conditions ensures your integration refreshes tokens safely and reliably.

## Recommended Patterns

### Single Refresh Lock

Allow only **one process** to perform a token refresh at a time. Other processes must wait until the new access and refresh tokens are available.

### Atomic Token Update

After a successful refresh, update access and refresh tokens **atomically** in your storage system. This prevents other processes from using partially updated tokens.

### Exponential Backoff for Waiting Processes

Processes waiting on the refresh lock should retry safely using an exponential backoff strategy to avoid overwhelming the token endpoint.

### Centralised Refresh Service

Consider implementing a **dedicated service** or singleton responsible for refreshing tokens. Other parts of your system should query this service for the latest token instead of refreshing independently.

## Implementation Tips

* **Server-side applications:** Use a distributed lock (e.g., Redis lock) when running multiple instances.
* **Multi-threaded applications:** Use a mutex, semaphore, or similar concurrency control.
* **Logging and monitoring:** Track refresh attempts, lock waits, and failures to detect potential race conditions.

## What to Avoid

* Performing simultaneous token refreshes across threads or processes
* Allowing old or invalid tokens to persist after a refresh
* Ignoring errors during refresh, which can lead to inconsistent token state

## Related Reading

* **[OAuth 2.0 Overview](/docs/current/integration-design/auth/oauth/integration-design-auth-oauth-overview)** - introduction to OAuth 2.0 for Pleo integrations
* **[API Keys Overview](/docs/current/authentication/standalone-api-keys-overview)** – alternative authentication method
* **[Tokens Overview](/docs/current/integration-design/auth/oauth/token-lifecycle/integration-design-auth-oauth-token-overview)** – understanding access and refresh tokens
* **[Secure Token Storage](/docs/current/integration-design/auth/oauth/token-lifecycle/integration-design-auth-oauth-secure-token-storage)** – storing credentials securely
* **[Centralised Token Refresh](/docs/current/integration-design/auth/oauth/token-lifecycle/integration-design-auth-oauth-centralised-token-refresh)** – safe token refresh patterns
* **[OAuth 2.0 Setup Workflow Guide](/docs/current/guides/oauth-workflow-guide)** - Step-by-step guide to configure OAuth 2.0 for your integration
