Tutorials

HTTP Replay for CAPTCHA API Debugging: Save and Reproduce Errors

Intermittent CAPTCHA solving failures are the hardest to debug. By the time you check logs, the context is gone. HTTP replay solves this — capture the exact request and response, save it, and replay it later to reproduce the issue deterministically.

The Replay Debugging Workflow

Failure occurs → Request/response captured → Saved to file
    ↓
Later: Load saved request → Replay → Analyze → Fix

This is more effective than live debugging because:

Live Debugging Replay Debugging
Must reproduce the failure Failure is already captured
Timing-dependent issues may not recur Exact same request, every time
Requires production access Works offline with saved data
Disruptive to running systems Non-disruptive analysis

Python: Recording and Replaying Requests

Recording Requests

import requests
import json
import time
import os
from datetime import datetime, timezone

class CaptchaAPIRecorder:
    def __init__(self, api_key, record_dir="captcha_recordings"):
        self.api_key = api_key
        self.submit_url = "https://ocr.captchaai.com/in.php"
        self.result_url = "https://ocr.captchaai.com/res.php"
        self.record_dir = record_dir
        os.makedirs(record_dir, exist_ok=True)

    def _record_exchange(self, request_data, response_data, metadata):
        """Save a request/response pair to disk."""
        timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S_%f")
        filename = f"{self.record_dir}/{timestamp}_{metadata.get('step', 'unknown')}.json"

        # Redact API key before saving
        safe_request = {**request_data}
        if "key" in safe_request.get("params", {}):
            safe_request["params"]["key"] = "REDACTED"
        if "key" in safe_request.get("data", {}):
            safe_request["data"]["key"] = "REDACTED"

        record = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "metadata": metadata,
            "request": safe_request,
            "response": response_data,
        }

        with open(filename, "w") as f:
            json.dump(record, f, indent=2)

        return filename

    def solve_recaptcha(self, sitekey, pageurl, **kwargs):
        # Submit
        submit_params = {
            "key": self.api_key,
            "method": "userrecaptcha",
            "googlekey": sitekey,
            "pageurl": pageurl,
            "json": 1,
            **kwargs,
        }

        start = time.monotonic()
        response = requests.post(self.submit_url, data=submit_params, timeout=30)
        duration = time.monotonic() - start

        response_data = {
            "status_code": response.status_code,
            "body": response.text,
            "headers": dict(response.headers),
            "duration_ms": round(duration * 1000),
        }

        file = self._record_exchange(
            {"method": "POST", "url": self.submit_url, "data": submit_params},
            response_data,
            {"step": "submit", "captcha_type": "recaptcha_v2"},
        )

        result = response.json()
        if result.get("status") != 1:
            print(f"Submit failed — recorded to {file}")
            return None

        task_id = result["request"]

        # Poll
        for attempt in range(1, 61):
            time.sleep(5)
            poll_params = {
                "key": self.api_key,
                "action": "get",
                "id": task_id,
                "json": 1,
            }

            start = time.monotonic()
            response = requests.get(
                self.result_url, params=poll_params, timeout=15
            )
            duration = time.monotonic() - start

            response_data = {
                "status_code": response.status_code,
                "body": response.text,
                "headers": dict(response.headers),
                "duration_ms": round(duration * 1000),
            }

            result = response.json()

            # Record errors and final results (skip NOT_READY to reduce noise)
            if result.get("request") != "CAPCHA_NOT_READY":
                self._record_exchange(
                    {"method": "GET", "url": self.result_url, "params": poll_params},
                    response_data,
                    {"step": "poll", "attempt": attempt, "task_id": task_id},
                )

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

            if result.get("request") not in ("CAPCHA_NOT_READY",):
                print(f"Poll error — recorded to {self.record_dir}/")
                return None

        return None

Replaying Saved Requests

import json
import glob
import requests


def replay_recording(filepath, api_key=None):
    """Replay a saved request to reproduce the error."""
    with open(filepath) as f:
        record = json.load(f)

    req = record["request"]
    original_response = record["response"]

    print(f"Original: {original_response['status_code']} — {original_response['body'][:200]}")

    if api_key:
        # Replay with real API key
        if "data" in req:
            req["data"]["key"] = api_key
        if "params" in req:
            req["params"]["key"] = api_key

        if req["method"] == "POST":
            response = requests.post(req["url"], data=req["data"], timeout=30)
        else:
            response = requests.get(req["url"], params=req["params"], timeout=15)

        print(f"Replay:   {response.status_code} — {response.text[:200]}")
        return response
    else:
        print("No API key — showing original response only")
        return None


def analyze_recordings(record_dir="captcha_recordings"):
    """Summarize all recorded exchanges."""
    files = sorted(glob.glob(f"{record_dir}/*.json"))
    print(f"Found {len(files)} recorded exchanges\n")

    errors = []
    for filepath in files:
        with open(filepath) as f:
            record = json.load(f)

        resp = record["response"]
        meta = record["metadata"]
        status = resp["status_code"]
        body = json.loads(resp["body"]) if resp["body"].startswith("{") else resp["body"]

        if isinstance(body, dict) and body.get("status") == 0:
            errors.append({
                "file": filepath,
                "step": meta.get("step"),
                "error": body.get("request"),
                "timestamp": record["timestamp"],
            })

    if errors:
        print(f"Errors found: {len(errors)}")
        for err in errors:
            print(f"  [{err['timestamp']}] {err['step']}: {err['error']}")
    else:
        print("No errors in recordings")


# Usage
analyze_recordings()
replay_recording("captcha_recordings/20260404_143201_submit.json", "YOUR_API_KEY")

JavaScript: Recording and Replaying Requests

const fs = require("fs");
const path = require("path");

class CaptchaAPIRecorder {
  constructor(apiKey, recordDir = "captcha_recordings") {
    this.apiKey = apiKey;
    this.submitUrl = "https://ocr.captchaai.com/in.php";
    this.resultUrl = "https://ocr.captchaai.com/res.php";
    this.recordDir = recordDir;

    if (!fs.existsSync(recordDir)) {
      fs.mkdirSync(recordDir, { recursive: true });
    }
  }

  _recordExchange(requestData, responseData, metadata) {
    const timestamp = new Date()
      .toISOString()
      .replace(/[-:T]/g, "")
      .slice(0, 18);
    const filename = path.join(
      this.recordDir,
      `${timestamp}_${metadata.step || "unknown"}.json`
    );

    // Redact API key
    const safeRequest = JSON.parse(JSON.stringify(requestData));
    if (safeRequest.params?.key) safeRequest.params.key = "REDACTED";
    if (safeRequest.body?.key) safeRequest.body.key = "REDACTED";

    const record = {
      timestamp: new Date().toISOString(),
      metadata,
      request: safeRequest,
      response: responseData,
    };

    fs.writeFileSync(filename, JSON.stringify(record, null, 2));
    return filename;
  }

  async solveRecaptcha(sitekey, pageurl, extraParams = {}) {
    const submitBody = new URLSearchParams({
      key: this.apiKey,
      method: "userrecaptcha",
      googlekey: sitekey,
      pageurl,
      json: 1,
      ...extraParams,
    });

    const start = performance.now();
    const response = await fetch(this.submitUrl, {
      method: "POST",
      body: submitBody,
    });
    const duration = Math.round(performance.now() - start);
    const text = await response.text();

    this._recordExchange(
      { method: "POST", url: this.submitUrl, body: Object.fromEntries(submitBody) },
      { statusCode: response.status, body: text, durationMs: duration },
      { step: "submit", captchaType: "recaptcha_v2" }
    );

    const result = JSON.parse(text);
    if (result.status !== 1) return null;

    const taskId = result.request;

    // Poll
    for (let attempt = 1; attempt <= 60; attempt++) {
      await new Promise((r) => setTimeout(r, 5000));

      const url = new URL(this.resultUrl);
      url.searchParams.set("key", this.apiKey);
      url.searchParams.set("action", "get");
      url.searchParams.set("id", taskId);
      url.searchParams.set("json", "1");

      const pollStart = performance.now();
      const pollResponse = await fetch(url);
      const pollDuration = Math.round(performance.now() - pollStart);
      const pollText = await pollResponse.text();
      const pollResult = JSON.parse(pollText);

      if (pollResult.request !== "CAPCHA_NOT_READY") {
        this._recordExchange(
          { method: "GET", url: url.toString(), params: { action: "get", id: taskId } },
          { statusCode: pollResponse.status, body: pollText, durationMs: pollDuration },
          { step: "poll", attempt, taskId }
        );
      }

      if (pollResult.status === 1) return pollResult.request;
      if (pollResult.request !== "CAPCHA_NOT_READY") return null;
    }

    return null;
  }
}

// Replay utility
function replayRecording(filepath) {
  const record = JSON.parse(fs.readFileSync(filepath, "utf8"));
  console.log(`Timestamp: ${record.timestamp}`);
  console.log(`Step: ${record.metadata.step}`);
  console.log(`Status: ${record.response.statusCode}`);
  console.log(`Response: ${record.response.body.slice(0, 200)}`);
  console.log(`Duration: ${record.response.durationMs}ms`);
  return record;
}

// Analyze all recordings
function analyzeRecordings(recordDir = "captcha_recordings") {
  const files = fs.readdirSync(recordDir)
    .filter((f) => f.endsWith(".json"))
    .sort();

  console.log(`Found ${files.length} recordings\n`);

  const errors = files
    .map((f) => JSON.parse(fs.readFileSync(path.join(recordDir, f), "utf8")))
    .filter((r) => {
      try {
        return JSON.parse(r.response.body).status === 0;
      } catch {
        return false;
      }
    });

  console.log(`Errors: ${errors.length}`);
  errors.forEach((e) => {
    const body = JSON.parse(e.response.body);
    console.log(`  [${e.timestamp}] ${e.metadata.step}: ${body.request}`);
  });
}

module.exports = { CaptchaAPIRecorder, replayRecording, analyzeRecordings };

HAR File Recording

For browser-based debugging, export HAR files from Chrome DevTools:

Capturing

  1. Open DevTools → Network tab
  2. Check "Preserve log"
  3. Trigger the CAPTCHA workflow
  4. Right-click → Save all as HAR with content

Analyzing HAR Files

import json

def analyze_har(filepath):
    """Extract CaptchaAI requests from a HAR file."""
    with open(filepath) as f:
        har = json.load(f)

    captcha_entries = [
        entry for entry in har["log"]["entries"]
        if "captchaai.com" in entry["request"]["url"]
    ]

    for entry in captcha_entries:
        req = entry["request"]
        resp = entry["response"]
        print(f"{req['method']} {req['url']}")
        print(f"  Status: {resp['status']}")
        print(f"  Time: {entry['time']:.0f}ms")

        if resp["content"].get("text"):
            print(f"  Body: {resp['content']['text'][:200]}")
        print()

analyze_har("network_capture.har")

What to Record

Always Record Skip
Failed submissions (status=0) Successful NOT_READY polls
Error poll responses Routine successful solves
Unexpected HTTP status codes Balance check responses
Timeout events Normal timing polls
First and last poll of a session Middle polls when NOT_READY

Recording every poll creates noise. Focus on transitions: submission, errors, and completion.

Troubleshooting

Issue Cause Fix
Recordings contain API key Redaction not applied Check key redaction logic runs before saving
Replay returns different result Server state changed between original and replay Expected — replay verifies the request format, not server state
HAR file too large Captured all page traffic, not just CAPTCHA Filter HAR entries to captchaai.com before saving
Recording directory fills up Not cleaning old recordings Add a retention policy — delete recordings older than 7 days
Cannot replay — file corrupted Write interrupted during recording Use atomic writes: write to temp file, then rename

FAQ

Should I record every API interaction?

No — record selectively. Capture all errors and the first/last interaction of each solve session. Skip intermediate NOT_READY polls to keep recordings manageable.

Is it safe to share recordings with support?

Yes, if you redact the API key. The recorder code above removes the key automatically. Double-check before sharing any file externally.

How long should I keep recordings?

7 days is usually sufficient for debugging intermittent issues. For compliance or audit requirements, adjust based on your organization's data retention policies.

Next Steps

Start recording your CaptchaAI API interactions to catch and reproduce errors — get your API key and add the recorder to your integration.

Related guides:

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
Tutorials Pytest Fixtures for CaptchaAI API Testing
Build reusable pytest fixtures to test CAPTCHA-solving workflows with Captcha AI.

Build reusable pytest fixtures to test CAPTCHA-solving workflows with Captcha AI. Covers mocking, live integra...

Automation Python reCAPTCHA v2
Apr 08, 2026
Tutorials GeeTest Token Injection in Browser Automation Frameworks
how to inject Gee Test v 3 solution tokens into Playwright, Puppeteer, and Selenium — including the three-value response, callback triggering, and form submissi...

Learn how to inject Gee Test v 3 solution tokens into Playwright, Puppeteer, and Selenium — including the thre...

Automation Python Testing
Jan 18, 2026