Troubleshooting

CAPTCHA Solving Timeout: Network and Configuration Fixes

Timeouts during CAPTCHA solving fall into three categories: submission timeouts, polling timeouts, and solve timeouts. Each has different causes and fixes.


Timeout Types

Type Where Typical Cause
Connection timeout Client → CaptchaAI API DNS, firewall, proxy issues
Read timeout Waiting for API response Server load, large payload
Solve timeout Polling for result Wrong polling interval, CAPTCHA complexity
Token expiry After solve completes Too slow to use the token

Fix 1: Connection and Read Timeouts

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry


def create_robust_session():
    """Session with retries and proper timeouts."""
    session = requests.Session()

    # Retry on transient failures
    retry = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[500, 502, 503, 504],
        allowed_methods=["GET", "POST"],
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("https://", adapter)
    session.mount("http://", adapter)

    return session


session = create_robust_session()

# Always set both connect and read timeouts
try:
    resp = session.post(
        "https://ocr.captchaai.com/in.php",
        data={"key": "YOUR_API_KEY", "method": "userrecaptcha", "json": 1},
        timeout=(10, 30),  # (connect_timeout, read_timeout)
    )
except requests.ConnectionError:
    print("Cannot reach CaptchaAI — check network/DNS")
except requests.Timeout:
    print("Request timed out — try again")

Fix 2: Optimal Polling Configuration

Different CAPTCHA types have different solve times. Polling too fast wastes requests; polling too slow wastes time.

import time

SOLVE_TIMES = {
    "recaptcha_v2":     {"initial_wait": 15, "poll_interval": 5, "max_polls": 24},
    "recaptcha_v3":     {"initial_wait": 10, "poll_interval": 5, "max_polls": 16},
    "turnstile":        {"initial_wait": 5,  "poll_interval": 3, "max_polls": 20},
    "geetest":          {"initial_wait": 10, "poll_interval": 5, "max_polls": 20},
    "image":            {"initial_wait": 5,  "poll_interval": 3, "max_polls": 12},
    "bls":              {"initial_wait": 5,  "poll_interval": 3, "max_polls": 15},
}


def poll_result(api_key, task_id, captcha_type="recaptcha_v2"):
    """Poll with type-appropriate timing."""
    config = SOLVE_TIMES.get(captcha_type, SOLVE_TIMES["recaptcha_v2"])

    time.sleep(config["initial_wait"])

    for attempt in range(config["max_polls"]):
        try:
            resp = requests.get(
                "https://ocr.captchaai.com/res.php",
                params={"key": api_key, "action": "get", "id": task_id, "json": 1},
                timeout=(10, 15),
            )
            data = resp.json()
        except (requests.Timeout, requests.ConnectionError):
            time.sleep(config["poll_interval"])
            continue

        if data.get("status") == 1:
            return data["request"]

        error = data.get("request", "")
        if error != "CAPCHA_NOT_READY":
            raise RuntimeError(f"Solve error: {error}")

        time.sleep(config["poll_interval"])

    raise TimeoutError(
        f"{captcha_type} solve timeout after "
        f"{config['initial_wait'] + config['max_polls'] * config['poll_interval']}s"
    )

Fix 3: DNS and Network Diagnostics

import socket
import time


def diagnose_network():
    """Check connectivity to CaptchaAI API."""
    results = {}

    # DNS resolution
    try:
        start = time.time()
        ip = socket.gethostbyname("ocr.captchaai.com")
        dns_ms = (time.time() - start) * 1000
        results["dns"] = {"status": "ok", "ip": ip, "ms": round(dns_ms)}
    except socket.gaierror as e:
        results["dns"] = {"status": "fail", "error": str(e)}

    # TCP connection
    try:
        start = time.time()
        sock = socket.create_connection(("ocr.captchaai.com", 443), timeout=10)
        tcp_ms = (time.time() - start) * 1000
        sock.close()
        results["tcp"] = {"status": "ok", "ms": round(tcp_ms)}
    except (socket.timeout, OSError) as e:
        results["tcp"] = {"status": "fail", "error": str(e)}

    # HTTPS request
    try:
        start = time.time()
        resp = requests.get(
            "https://ocr.captchaai.com/res.php",
            params={"key": "test", "action": "getbalance"},
            timeout=10,
        )
        http_ms = (time.time() - start) * 1000
        results["https"] = {"status": "ok", "ms": round(http_ms), "code": resp.status_code}
    except Exception as e:
        results["https"] = {"status": "fail", "error": str(e)}

    return results


diag = diagnose_network()
for check, result in diag.items():
    status = result["status"]
    if status == "ok":
        print(f"{check}: OK ({result.get('ms', '?')}ms)")
    else:
        print(f"{check}: FAIL — {result.get('error')}")

Fix 4: Timeout-Aware Solver

import time
import requests


class TimeoutAwareSolver:
    """Solver that handles all timeout scenarios gracefully."""

    def __init__(self, api_key):
        self.api_key = api_key
        self.session = create_robust_session()

    def solve(self, captcha_type, params, max_total_seconds=180):
        """Solve with a hard total time limit."""
        deadline = time.time() + max_total_seconds

        # Submit with retry
        task_id = self._submit_with_retry(params, deadline)
        if not task_id:
            raise TimeoutError("Could not submit within time limit")

        # Poll with deadline
        config = SOLVE_TIMES.get(captcha_type, SOLVE_TIMES["recaptcha_v2"])
        time.sleep(min(config["initial_wait"], deadline - time.time()))

        while time.time() < deadline:
            try:
                resp = self.session.get(
                    "https://ocr.captchaai.com/res.php",
                    params={
                        "key": self.api_key, "action": "get",
                        "id": task_id, "json": 1,
                    },
                    timeout=(5, 10),
                )
                data = resp.json()
            except (requests.Timeout, requests.ConnectionError):
                time.sleep(config["poll_interval"])
                continue

            if data.get("status") == 1:
                return data["request"]

            error = data.get("request", "")
            if error != "CAPCHA_NOT_READY":
                raise RuntimeError(f"Solve error: {error}")

            remaining = deadline - time.time()
            sleep_time = min(config["poll_interval"], max(0, remaining))
            time.sleep(sleep_time)

        raise TimeoutError(f"Solve exceeded {max_total_seconds}s limit")

    def _submit_with_retry(self, params, deadline, max_retries=3):
        """Submit task with retries."""
        data = {"key": self.api_key, "json": 1, **params}

        for attempt in range(max_retries):
            if time.time() >= deadline:
                return None
            try:
                resp = self.session.post(
                    "https://ocr.captchaai.com/in.php",
                    data=data,
                    timeout=(10, 30),
                )
                result = resp.json()
                if result.get("status") == 1:
                    return result["request"]

                error = result.get("request", "")
                if error == "ERROR_NO_SLOT_AVAILABLE":
                    time.sleep(5)
                    continue
                raise RuntimeError(f"Submit failed: {error}")
            except (requests.Timeout, requests.ConnectionError):
                time.sleep(2 ** attempt)

        return None


# Usage
solver = TimeoutAwareSolver("YOUR_API_KEY")
token = solver.solve("recaptcha_v2", {
    "method": "userrecaptcha",
    "googlekey": "SITEKEY",
    "pageurl": "https://example.com",
}, max_total_seconds=120)

Token Expiry Reference

Tokens expire. Solve and use them quickly:

CAPTCHA Type Token Lifetime
reCAPTCHA v2 ~120 seconds
reCAPTCHA v3 ~120 seconds
Turnstile ~300 seconds
GeeTest v3 ~60 seconds
Image CAPTCHA N/A (text answer)

Troubleshooting

Symptom Cause Fix
ConnectionError immediately DNS/firewall block Run network diagnostics
Timeout on submit Slow network or large payload Increase connect timeout
CAPCHA_NOT_READY forever Polling too short before max Increase max_polls or max_total_seconds
Token expired after solve Too slow to use result Use token within 30s of receiving it
Intermittent timeouts Unstable connection Use session with retries

FAQ

What's the maximum solve time for any CAPTCHA type?

reCAPTCHA v2 can take up to 120 seconds in edge cases. Image CAPTCHAs are typically under 15 seconds. Set your maximum timeout to at least 2 minutes for v2/v3.

Should I retry on timeout?

Yes, for transient network issues. Use exponential backoff. If the CAPTCHA itself timed out on CaptchaAI's side, submit a new task.

Does a faster internet connection help?

For submission and polling, slightly. The bottleneck is usually the solve time on CaptchaAI's side, not network speed.



Solve faster — try CaptchaAI.

Discussions (0)

No comments yet.