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.

Related Posts

DevOps & Scaling Ansible Playbooks for CaptchaAI Worker Deployment
Deploy and manage Captcha AI workers with Ansible — playbooks for provisioning, configuration, rolling updates, and health checks across your server fleet.

Deploy and manage Captcha AI workers with Ansible — playbooks for provisioning, configuration, rolling updates...

Automation Python All CAPTCHA Types
Apr 07, 2026
DevOps & Scaling Blue-Green Deployment for CAPTCHA Solving Infrastructure
Implement blue-green deployments for CAPTCHA solving infrastructure — zero-downtime upgrades, traffic switching, and rollback strategies with Captcha AI.

Implement blue-green deployments for CAPTCHA solving infrastructure — zero-downtime upgrades, traffic switchin...

Automation Python All CAPTCHA Types
Apr 07, 2026
Troubleshooting CaptchaAI API Error Handling: Complete Decision Tree
Complete decision tree for every Captcha AI API error.

Complete decision tree for every Captcha AI API error. Learn which errors are retryable, which need parameter...

Automation Python All CAPTCHA Types
Mar 17, 2026
Tutorials Using Fiddler to Inspect CaptchaAI API Traffic
How to use Fiddler Everywhere and Fiddler Classic to capture, inspect, and debug Captcha AI API requests and responses — filters, breakpoints, and replay for tr...

How to use Fiddler Everywhere and Fiddler Classic to capture, inspect, and debug Captcha AI API requests and r...

Automation Python All CAPTCHA Types
Mar 05, 2026
Tutorials CAPTCHA Handling in Mobile Apps with Appium
Handle CAPTCHAs in mobile app automation using Appium and Captcha AI — extract Web sitekeys, solve, and inject tokens on Android and i OS.

Handle CAPTCHAs in mobile app automation using Appium and Captcha AI — extract Web View sitekeys, solve, and i...

Automation Python All CAPTCHA Types
Feb 13, 2026
Tutorials Streaming Batch Results: Processing CAPTCHA Solutions as They Arrive
Process CAPTCHA solutions the moment they arrive instead of waiting for tasks to complete — use async generators, event emitters, and callback patterns for stre...

Process CAPTCHA solutions the moment they arrive instead of waiting for all tasks to complete — use async gene...

Automation Python All CAPTCHA Types
Apr 07, 2026
Reference CaptchaAI CLI Tool: Command-Line CAPTCHA Solving and Testing
A reference for building and using a Captcha AI command-line tool — solve CAPTCHAs, check balance, test parameters, and integrate with shell scripts and CI/CD p...

A reference for building and using a Captcha AI command-line tool — solve CAPTCHAs, check balance, test parame...

Automation Python All CAPTCHA Types
Feb 26, 2026
DevOps & Scaling Auto-Scaling CAPTCHA Solving Workers
Build auto-scaling CAPTCHA solving workers that adjust capacity based on queue depth, balance, and solve rates.

Build auto-scaling CAPTCHA solving workers that adjust capacity based on queue depth, balance, and solve rates...

Automation Python All CAPTCHA Types
Mar 23, 2026
DevOps & Scaling CaptchaAI Monitoring with Datadog: Metrics and Alerts
Monitor Captcha AI performance with Datadog — custom metrics, dashboards, anomaly detection alerts, and solve rate tracking for CAPTCHA solving pipelines.

Monitor Captcha AI performance with Datadog — custom metrics, dashboards, anomaly detection alerts, and solve...

Automation Python All CAPTCHA Types
Feb 19, 2026
Troubleshooting GeeTest v3 Error Codes: Complete Troubleshooting Reference
Complete reference for Gee Test v 3 error codes — from registration failures to validation errors — with causes, fixes, and Captcha AI-specific troubleshooting.

Complete reference for Gee Test v 3 error codes — from registration failures to validation errors — with cause...

Automation Testing GeeTest v3
Apr 08, 2026
Troubleshooting Turnstile Token Invalid After Solving: Diagnosis and Fixes
Fix Cloudflare Turnstile tokens that come back invalid after solving with Captcha AI.

Fix Cloudflare Turnstile tokens that come back invalid after solving with Captcha AI. Covers token expiry, sit...

Python Cloudflare Turnstile Web Scraping
Apr 08, 2026
Troubleshooting Common GeeTest v3 Errors and Fixes
Diagnose the most common Gee Test v 3 errors — stale challenge, bad parameters, validation failures — and fix them with practical troubleshooting steps.

Diagnose the most common Gee Test v 3 errors — stale challenge, bad parameters, validation failures — and fix...

Automation Testing GeeTest v3
Jan 24, 2026