Mid-batch 401 errors during Genesys Cloud API polling loop

We are executing a batch synchronization job that iterates through thousands of routing attributes via the /api/v2/routing/attributes endpoint. The initial OAuth client credentials flow succeeds, and we cache the access token in our Terraform local-exec script. The problem arises when the iteration duration exceeds the standard token validity window. The job proceeds for a few hundred items before the API returns HTTP 401 Unauthorized responses without any retry mechanism built into our current curl wrapper. We need to implement a transparent token refresh logic within the polling loop to prevent premature termination. Has anyone implemented a solid refresh pattern for this specific scenario? The current implementation simply fails hard.

Token expiry is the usual culprit here. Just add a simple check before each call. If the token’s older than 55 minutes, refresh it. Here’s the basic logic in Node:

if (Date.now() - tokenIssuedAt > 3300000) {
 await refreshToken();
}

Keeps the batch running without 401s.