Cloudflare
How to reuse cf_clearance cookies safely
A cf_clearance cookie can carry hundreds of requests past the Cloudflare challenge, but only under the conditions it was issued for. Designing your sessions around those conditions is what makes it last.
What the cookie is tied to
When a browser passes a Cloudflare challenge, Cloudflare sets cf_clearance for the site's domain. On later requests, Cloudflare checks not only that the cookie is valid but that the request still fits the visitor who earned it. In practice three bindings matter:
- IP address. The cookie is linked to the IP that passed the challenge. A request from another IP with the same cookie is challenged again.
- User agent. The cookie is linked to the browser that earned it. Changing the
User-Agentheader invalidates it. - Time. The site owner sets how long a clearance lasts with Cloudflare's Challenge Passage setting. 30 minutes is the default at the time of writing, and owners can choose shorter or much longer periods.
Beyond these, Cloudflare can re-challenge a visitor whenever its signals change, for example after a jump in request rate. Treat the cookie as a lease that can end early, not a guarantee.
One clearance per identity
The simplest correct model is an identity: one proxy exit IP, one user agent string and the clearance obtained for them. Everything that sends requests belongs to exactly one identity. Never copy a cookie from one identity to another, never let two IPs share it, and never send a different user agent with it. When you get a clearance from AntiCloudflareTask, the solution includes the userAgent it was produced with; that string becomes part of the identity.
This also settles the proxy question. Rotating proxies that change IP per request break the model. Use sticky sessions whose lifetime is at least as long as you intend to reuse the cookie, or static IPs.
Store the identity, not just the cookie
Workers restart, jobs get rescheduled, containers move. If you persist only the cookie value, you lose the IP and user agent it depends on. Store all three together, plus the time you obtained it.
import json
import time
from dataclasses import dataclass, asdict, field
from pathlib import Path
@dataclass
class CfIdentity:
site: str # e.g. "catalog.example.com"
proxy: str # the sticky proxy URL the clearance was solved through
user_agent: str # solution["userAgent"]
cookies: dict # solution["cookies"], includes cf_clearance
obtained: float = field(default_factory=time.time)
uses: int = 0
def age_minutes(self) -> float:
return (time.time() - self.obtained) / 60
def save_identities(items: list[CfIdentity], path: Path) -> None:
path.write_text(json.dumps([asdict(i) for i in items], indent=1))
def load_identities(path: Path) -> list[CfIdentity]:
if not path.exists():
return []
return [CfIdentity(**row) for row in json.loads(path.read_text())]
A JSON file is enough for one machine. For several workers, put the same record in Redis or a database row keyed by site and proxy, so any worker that picks up the proxy also picks up its cookie and user agent.
Decide when to refresh
There are two sensible triggers, and you should use both:
- Reactive. When a response shows the challenge again (
cf-mitigated: challengeor the "Just a moment" page), solve a new clearance for that identity and retry the request once. - Proactive. If you know or have measured the site's passage period, refresh a little before it ends, between batches rather than mid batch.
The solution does not include the cookie's expiry, so measure it. Log age_minutes() at the moment each identity first meets the challenge again. After a few cycles you will see the site's passage period clearly, and you can set the proactive threshold just below it. Until then, rely on the reactive trigger alone.
Using an identity
import requests
def session_for(ident: CfIdentity) -> requests.Session:
http = requests.Session()
http.proxies = {"http": ident.proxy, "https": ident.proxy}
http.headers["User-Agent"] = ident.user_agent
for key, val in ident.cookies.items():
http.cookies.set(key, val, domain=ident.site)
return http
def fetch(ident: CfIdentity, url: str, solve_again) -> requests.Response:
resp = session_for(ident).get(url, timeout=30)
ident.uses += 1
if resp.headers.get("cf-mitigated") == "challenge":
fresh = solve_again(ident.site, ident.proxy) # returns a new solution dict
ident.cookies, ident.user_agent, ident.obtained = fresh["cookies"], fresh["userAgent"], time.time()
resp = session_for(ident).get(url, timeout=30)
return resp
solve_again is your function that runs the challenge task through the identity's proxy; the solving flow itself is in the Python challenge guide. Building a new session from the identity each time keeps the example short; in a busy crawler, keep one session per identity and update its cookies in place.
Pacing keeps clearances alive
A clearance survives longest when traffic under it looks like one ordinary visitor. Spread requests evenly instead of in bursts, keep the concurrency per identity low (one or two requests in flight), and give each identity its own work queue. If you need more throughput, add identities rather than pushing harder on one. When an identity is re-challenged much sooner than its usual period, take it out of rotation for a while; it is a sign that its request pattern or IP reputation needs attention.
How many identities you need
A rough sizing rule follows from two numbers you can measure: how many requests one identity can make before it is re-challenged or reaches the end of its passage period, and how many requests per hour the job needs. Divide the second by the first to get solves per hour, and size the number of concurrent identities so that each stays at a calm pace. Start small and add identities only when the measured numbers call for it.
Things not to do
- Share cookies across sites. Each site behind Cloudflare issues its own clearance for its own domain.
- Mix clients. Getting the cookie in one client and using it from another with a different TLS stack can trigger new challenges on strict sites. Keep each identity on one client type.
- Treat blocks as expired clearances. A 403 with Error 1020 or another firewall code is not a challenge. A new cookie will not change it; see telling Cloudflare protections apart.
- Prefetch clearances in bulk. Unused clearances age out while they wait, and each one was a solved task.
Cost in practice
Each clearance is one solved task at $0.84 per 1,000. Because a good identity carries many requests, the cost per page is mostly a function of how long you keep each clearance valid, which is exactly what this design aims for. Failed challenge tasks are free. The task's fields are documented on the Cloudflare Challenge page.
Common questions
How long does a cf_clearance cookie last?
As long as the site owner's Challenge Passage setting allows, 30 minutes by default at the time of writing, unless Cloudflare re-challenges sooner.
Can I use one cf_clearance with several proxies?
No. It is tied to the IP that passed the challenge. Each IP needs its own clearance.
What happens if I change the user agent?
The clearance stops matching and Cloudflare challenges again. Keep the userAgent from the solution for the cookie's whole life.
Does the solution include the cookie expiry?
No. Track when you obtained each clearance and when the challenge returns to learn the site's period.
Should I refresh on a timer or on demand?
Both: refresh when the challenge reappears, and once you know the period, a little before it ends between batches.
Keep reading
- cf_clearance cookieThe cookie Cloudflare sets after a passed challenge, why it only works from one IP and user agent, and its lifespan.
- Get past the Cloudflare challenge page in PythonGet a cf_clearance cookie with AntiCloudflareTask and your own proxy, then reuse it from Python with the matching user agent.
- Sticky sessionA sticky session pins one exit IP for a while, so cookies and CAPTCHA answers earned on that address keep working.
- Cloudflare Challenge solver$0.84 per 1,000 tasks, answers under 10 seconds.