Preventing Duplicate Zoho CRM Token Refreshes in FastAPI (Fix “Too Many Requests” Errors)
Originally discussed at Zoho CRM: Getting “too many requests” even when caching access token until expiry. This guide expands on that question with verified Zoho limits and production-ready patterns.
Your integration works in testing. Then, in production, your FastAPI app starts failing with a “too many requests” error from Zoho’s OAuth endpoint, even though you cache the access token until it expires.
The usual cause is that your cache works, but refreshes aren’t coordinated. When the token expires, several requests can notice at the same instant and each fetch a new token. Zoho’s limits punish exactly that.
If a sales or support workflow depends on Zoho CRM data, a blocked token means broken lead syncs, failed updates, and frustrated teams. This guide explains why it happens and how to fix it.
What You’ll Learn
- Why caching alone doesn’t stop duplicate Zoho token refreshes
- Zoho’s current token limits, checked against official documentation
- How to diagnose the real cause in about 15 minutes
- Six fixes, from a simple
asyncio.Lockto a shared Redis lock for multi-pod deployments - Which fix matches your deployment
1. The Problem in Plain Language
Short answer: Duplicate refreshes from concurrent requests are the most likely cause. A lock, also called a single-flight refresh, is the right fix. The lock has to match how your app is deployed, though, and a few other bugs produce the same symptom.
Zoho’s Verified Token Limits
| Item | Detail |
|---|---|
| Token endpoint | https://accounts.zoho.<dc>/oauth/v2/token with grant_type=refresh_token (the domain depends on your data center) |
| Access token lifetime | 3,600 seconds (1 hour) |
| Refresh throttle | Zoho allows 10 access-token requests per refresh token within 10 minutes. Once you hit it, token creation is blocked for the rest of that window. |
| Active tokens | Zoho’s current token-limits page says a refresh token can have a maximum of 10 active access tokens. Older community posts mention 15, so design for 10. |
| Refresh tokens | A maximum of 20 active refresh tokens per user per client. |
Note on the error text: Many developers report the message “Access denied! You have made too many requests continuously. Please try again after some time.” We couldn’t find that exact string in Zoho’s official documentation. Treat it as commonly observed behavior, not a guaranteed contract. Detect the failure by the absence of
access_tokenin the response, not by matching the text.
Why Your Cache Doesn’t Prevent the Error
- Thundering herd (check-then-act race). When the token expires, N concurrent requests all see “expired” before any of them has stored the new token. All N call Zoho. This matches the original poster’s hypothesis.
- Multiple processes or pods. An in-memory cache and an
asyncio.Lockexist per process. Withuvicorn --workers N, gunicorn, or several containers, each process refreshes on its own. - Cache loss. Restarts,
--reload, serverless cold starts, and crash loops empty the cache, so every start triggers a refresh. - Expiry-math bugs. Zoho’s current documentation shows
expires_inin seconds (3600). Some older or product-specific responses have been reported to return milliseconds and add anexpires_in_secfield. That field isn’t covered in the OAuth refresh documentation. If you mix units or subtract a margin incorrectly, a fresh token looks expired immediately and every request refreshes. - Failed refreshes aren’t remembered. If a refresh is rate-limited and you cache nothing, every later request retries, and the lockout keeps extending.
- Other token-generating code. Creating a new SDK client per request, or repeatedly exchanging a grant code, uses up the same quota.
Visual suggestion: a timeline diagram showing 20 requests arriving at the moment of expiry, with and without a lock.
2. Diagnose First (About 15 Minutes)
Don’t guess. Instrument the refresh path first:
- Log every refresh call with PID, hostname, timestamp, and reason (
cache_miss,expired,401_retry). Expect about one refresh per hour per refresh token. More than a handful per hour points to a bug. - Print
expires_in(andexpires_in_secif present) from a real response. Confirm your math uses the right unit. - Check worker and replica counts in your deployment config.
- Check who else shares the refresh token. A dev laptop, staging server, or cron job using the same credentials draws from the same quota.
3. Solutions, From Most to Least Practical
Solution A: Single-Flight Refresh with asyncio.Lock (Single Process)
Use when: you run exactly one worker process and one instance.
The pattern is double-checked locking. Check the cache without the lock for speed, take the lock, then check again. Another request may have refreshed while you waited.
import asyncio, time, httpx
class ZohoTokenManager:
def __init__(self, client_id, client_secret, refresh_token,
accounts_url="https://accounts.zoho.com", margin=120):
self._cid, self._secret, self._rt = client_id, client_secret, refresh_token
self._url = f"{accounts_url}/oauth/v2/token"
self._margin = margin
self._token = None
self._exp = 0.0
self._lock = asyncio.Lock()
self._cooldown_until = 0.0
def _valid(self):
return self._token and time.time() < self._exp - self._margin
async def get_token(self, client: httpx.AsyncClient) -> str:
if self._valid(): # fast path, no lock
return self._token
async with self._lock: # only one refresher
if self._valid(): # double-check after waiting
return self._token
if time.time() < self._cooldown_until:
raise RuntimeError("Zoho refresh in cooldown")
r = await client.post(self._url, data={
"refresh_token": self._rt, "client_id": self._cid,
"client_secret": self._secret, "grant_type": "refresh_token"})
body = r.json()
if r.status_code != 200 or "access_token" not in body:
self._cooldown_until = time.time() + 60 # negative caching
raise RuntimeError(f"Zoho refresh failed: {body}")
self._token = body["access_token"]
ttl = body.get("expires_in_sec") or body["expires_in"]
if ttl > 100_000: # defensive: value was in ms
ttl //= 1000
self._exp = time.time() + ttl
return self._tokenCreate the manager once, not per request. In FastAPI, use the lifespan handler and store it on app.state:
from contextlib import asynccontextmanager
from fastapi import FastAPI
import httpx
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(timeout=10)
app.state.zoho = ZohoTokenManager(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN)
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)Limitation: it doesn’t help across workers or pods.
Solution B: Distributed Lock Plus Shared Cache (Multi-Worker or Multi-Pod)
Use when: more than one process shares the refresh token. This is the production choice for that setup.
Store the token in Redis with a TTL slightly shorter than its lifetime, so expiry is automatic. Guard the refresh with a Redis lock and re-check the cache after acquiring it.
import redis.asyncio as redis
r = redis.from_url("redis://...")
KEY, LOCK, COOL = "zoho:access_token", "zoho:refresh_lock", "zoho:cooldown"
async def get_token(http):
if tok := await r.get(KEY):
return tok.decode()
async with r.lock(LOCK, timeout=30, blocking_timeout=35):
if tok := await r.get(KEY): # someone else refreshed
return tok.decode()
if await r.exists(COOL):
raise RuntimeError("Zoho refresh in cooldown")
resp = await http.post(TOKEN_URL, data={...})
body = resp.json()
if "access_token" not in body:
await r.set(COOL, 1, ex=60)
raise RuntimeError(body)
ttl = int(body.get("expires_in_sec") or body["expires_in"])
if ttl > 100_000: # defensive: value was in ms
ttl //= 1000
await r.set(KEY, body["access_token"], ex=max(ttl - 120, 30))
return body["access_token"]Notes:
- The lock
timeoutmust exceed the worst-case refresh time, HTTP timeout included. Otherwise the lock can expire mid-refresh. - A single-instance Redis lock is adequate here. A rare duplicate refresh is harmless, because you only need to stay well under 10 per 10 minutes. You don’t need strict mutual exclusion.
- No Redis? The same pattern works with:
- PostgreSQL advisory locks (
pg_advisory_xact_lock) and the token in a database row SELECT ... FOR UPDATEon a token row- A file lock (
filelock) with a token file, which only works for multiple workers on one host
- PostgreSQL advisory locks (
Solution C: Reactive Refresh on 401 (Single-Flight Retry)
Use this alongside A or B, not instead of them. If Zoho returns INVALID_TOKEN or a 401, for example because the token was revoked, invalidate the cached token only if it still equals the token that failed, then retry once. Without that comparison, 50 concurrent failures trigger 50 invalidations and 50 refreshes.
async def call_zoho(...):
tok = await get_token()
resp = await send(tok)
if resp.status_code == 401:
await invalidate_if_current(tok) # compare-and-delete
resp = await send(await get_token())
return respWith Redis, make the compare-and-delete atomic with a small Lua script:
CAD = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"
async def invalidate_if_current(tok: str):
await r.eval(CAD, 1, KEY, tok)Solution D: Proactive Background Refresh
Run one scheduled task that refreshes about every 50 minutes and writes the token to shared storage. Options include APScheduler, Celery beat, or a Kubernetes CronJob. Request handlers only read the token, so refreshes leave the request path entirely.
Limitation: it adds a component, and you still need the reactive fallback (C) in case a token is invalidated early.
Solution E: Use Zoho’s Official SDK with a Persistent Token Store
The Zoho CRM Python SDK supports token persistence through FileStore, DBStore, or a custom token store. It handles lookup, refresh, and persistence for you.
- Initialize the SDK once at startup, not per request.
FileStoresuits single-process or development setups.DBStoreor a custom store (Redis- or secrets-manager-backed) suits multiple workers.- With several workers refreshing for the same user, the store must be shared or concurrency-safe. Otherwise you get duplicate refreshes and inconsistent saved state.
- The SDK isn’t designed around async FastAPI handlers, so check its concurrency behavior for your version. Consider running SDK calls in a thread pool.
Solution F: Reduce the Load (Architecture)
- Build a single “Zoho gateway” service or worker that owns the token and exposes an internal API or queue. Other services never touch the refresh token.
- Use separate Zoho clients or refresh tokens per environment (dev, staging, prod).
- Throttle outbound API calls with a semaphore or queue. Zoho also enforces separate API credit limits.
For no-code or low-code orchestration, Zoho Flow can handle CRM connections and OAuth for you. Tools like Make.com or n8n can do the same when a lightweight workflow is easier to maintain than custom FastAPI code. Our guide on mastering Zoho Flow custom function outputs shows how to get clean data out of those flows.
4. Which Fix Should You Use?
| Your setup | Do this |
|---|---|
| Single worker | A (+ C) |
| Multiple workers or pods | B (+ C), optionally D |
| Token shared across environments | F first, then A or B |
| Already locked out | Stop all refreshing for about 10 minutes, deploy the fix, then resume. Retrying while blocked prolongs the problem. |
5. Implementation Checklist
- One token manager instance per process, created in
lifespan - Double-checked locking (check, lock, re-check)
- A shared cache if you have more than one process
- A refresh margin of 1–5 minutes, with the correct time unit
- A cooldown or backoff after failed refreshes
- Compare-and-invalidate on 401
- A reused
httpx.AsyncClientwith timeouts - The correct data-center accounts domain (
accounts.zoho.com,.eu,.in,.com.au,.jp,.sa,.uk,.com.cn, oraccounts.zohocloud.ca) - API calls sent to the
api_domainreturned in the token response (for examplehttps://www.zohoapis.eu), not the accounts domain - Metrics or logging for refresh counts
6. Related Reading
Running into other Zoho API errors? These guides may help:
- How to fix “invalid request” issues in Zoho Mail
- Resolving missing leads from Zoho CRM forms
- How to avoid hitting limits in Zoho Creator
7. Practical Next Steps
- Add the refresh logging from section 2 and run it for a day.
- Pick the fix from the table in section 4.
- Separate your dev, staging, and production OAuth clients.
- If you don’t have a Zoho CRM account for testing, you can start a trial of Zoho CRM and create a dedicated sandbox client.
Key Takeaways
- Zoho allows 10 access-token requests per refresh token per 10 minutes. A healthy integration refreshes about once an hour.
- A cache by itself doesn’t stop a stampede at expiry. Use double-checked locking.
- An
asyncio.Lockonly protects one process. For multiple workers or pods, use Redis or a database lock with a shared cache. - Cache failures briefly (cooldown) and use compare-and-invalidate on 401s.
- Confirm your
expires_inunits, use the right data-center domain, and don’t share a refresh token across environments. - If you’re already blocked, stop all refreshing for about 10 minutes before resuming.
Sources and References
Verified against Zoho’s current documentation:
- Zoho OAuth token limits
- Refresh access token, web server apps
- Refresh access token, non-browser apps
- Zoho OAuth multi-DC support
- Zoho CRM API v7 multi-DC
- Kaizen: Tokens and limitations
Technical references:
- Python
asyncio.Lock - Redis distributed locks pattern
- redis-py documentation
- PostgreSQL advisory locks
- FastAPI lifespan events
Zoho occasionally changes OAuth limits, so recheck the token-limits page before you finalize capacity planning.
Source discussion: Zoho CRM: Getting “too many requests” even when caching access token until expiry.
Need Help Hardening Your Zoho Integration?
Token handling is one of the most common reasons Zoho integrations fail in production. The team at Creator Scripts builds and audits Zoho CRM, Creator, and Flow integrations.