Access token expires mid-batch processing in C# service

Hey folks. I’m running into a headache with token refresh logic in my C# backend service. We have a job that pulls a large batch of interaction records from Genesys Cloud via the API, processes them locally, and then pushes updates back. The batch size is around 5,000 records, which takes about 12 minutes to process end-to-end.

The issue is that the standard access token expires in 3600 seconds. My service fetches a new token at startup, but halfway through the batch, the token is stale. The HTTP client throws a 401 Unauthorized error on the third API call within the loop. I know I need to implement a refresh mechanism, but I’m unsure about the best pattern for a long-running batch job.

Here is the relevant part of my code:

var client = new RestClient("https://api.mypurecloud.com");
var request = new RestRequest("/api/v2/analytics/conversations/summary", Method.Post);
request.AddHeader("Authorization", "Bearer " + _currentAccessToken);
// ... processing loop ...
foreach (var record in batch) { 
 // 401 happens here after ~10 mins
 var response = await client.ExecutePostAsync(request); 
}

I tried adding a simple check before each request to see if the token is older than 3500 seconds, then calling the OAuth endpoint to get a new one. But this introduces a delay and feels clunky. Is there a way to hook into the RestClient to automatically retry with a new token on 401? Or should I be using the refresh_token grant type to get a new access token without re-authenticating the client credentials? The docs mention refresh tokens, but they seem tied to user login flows, not machine-to-machine service accounts. I don’t want to restart the whole job just because a token expired. What’s the standard approach for this scenario in .NET?