The Token That Expired Mid-Run: OAuth Refresh in Long n8n Workflows
Описание и применение
В n8n‑рабочих процессах, где токен OAuth используется один раз, токен истекает в середине выполнения, вызывая ошибки 401 и частичные сбои. Решение: проверять срок действия токена перед каждым батчем, обновлять его заранее, использовать атомарный захват токена, сохранять новую пару токенов в общей базе и ограничивать попытки обновления.
Задача
Long n8n workflows that reuse a single OAuth access token fail when the token expires mid‑run, causing 401 errors and partial failures.
Результат
Implementing proactive token refresh, single atomic refresher, and persistent token storage prevents mid‑run failures and ensures consistent workflow execution.
Рабочий процесс
- Fetch access token at start
- For each batch of calls: check token expiry; if less than 10 minutes remaining, refresh token atomically
- Make API calls with current token
- If 401 occurs, retry with refreshed token (safety net)
- Write new token pair atomically to shared store
- Re‑read token before next batch
- Handle revoked tokens by capping refresh attempts and sending review record
Доказательства
The access token lived for sixty minutes. The workflow fetched it once at the start and reused it for every downstream call.
The worker now checks the token's expiry before each batch of calls, with a margin. If the token expires in less than ten minutes, it refreshes first, then proceeds.
Token state lives in one database row, not in each execution's memory. Refreshing means claiming that row — an atomic update that only succeeds for one execution — doing the refresh, writing the new tokens back to the same row, and releasing the claim.
The refresh writes back to the same place every run reads from: the credential store, or a single token row that the workflow reads at start.
- Дата записи: 2026-11-02T11:44:00.980Z