Processar 10.000 CAPTCHAs por hora significa aproximadamente 2,8 soluções por segundo sustentado. Isso é possível com a arquitetura certa. Este guia aborda a matemática, o código e o ajuste necessário para atingir esse rendimento usandoCaptchaAI.
A matemática
Se uma única resolução de reCAPTCHA v2 levar 15 segundos (mediana):
- Sequencial: 3.600s / 15s = 240 soluções/hour
- Para alcançar 10.000/hour: você precisa de ~42 soluções simultâneas em voo o tempo todo
O principal insight: você não está esperando que o CaptchaAI seja com menor latência – você está sobrepondo solicitações suficientes para que 42 soluções sejam concluídas durante a mesma janela de 15 segundos.
Arquitetura
┌──────────┐ ┌────────────┐ ┌─────────────┐ ┌──────────┐
│ Task │────▶│ Submit │────▶│ CaptchaAI │────▶│ Result │
│ Queue │ │ Workers │ │ API │ │ Store │
│ (Redis) │ │ (async) │ │ │ │ (DB) │
└──────────┘ └────────────┘ └─────────────┘ └──────────┘
│ ▲
│ ┌──────────┐ │
└───▶│ Poll │────┘
│ Workers │
└──────────┘
Componentes:
- Fila de tarefas — Mantém tarefas CAPTCHA pendentes com chaves de site e URLs
- Enviar trabalhadores — Envie tarefas para a API CaptchaAI simultaneamente
- Pesquisadores — Verifique os resultados em intervalos otimizados
- Loja de resultados — Salva tokens à medida que chegam
Python: pipeline assíncrono
# high_throughput_solver.py
import os
import asyncio
import time
import aiohttp
API_KEY = os.environ.get("CAPTCHAAI_KEY", "YOUR_API_KEY")
BASE_URL = "https://ocr.captchaai.com"
MAX_CONCURRENT = 50 # Max simultaneous solves
POLL_INTERVAL = 5 # Seconds between polls
INITIAL_WAIT = 12 # Seconds before first poll
semaphore = asyncio.Semaphore(MAX_CONCURRENT)
stats = {"submitted": 0, "solved": 0, "failed": 0, "start": 0}
async def solve_one(session, sitekey, pageurl, task_num):
"""Submit and poll a single CAPTCHA."""
async with semaphore:
try:
# Submit
async with session.get(f"{BASE_URL}/in.php", params={
"key": API_KEY, "method": "userrecaptcha",
"googlekey": sitekey, "pageurl": pageurl, "json": "1",
}) as resp:
result = await resp.json(content_type=None)
if result.get("status") != 1:
stats["failed"] += 1
return None
stats["submitted"] += 1
task_id = result["request"]
# Wait before first poll
await asyncio.sleep(INITIAL_WAIT)
# Poll
for _ in range(25):
async with session.get(f"{BASE_URL}/res.php", params={
"key": API_KEY, "action": "get",
"id": task_id, "json": "1",
}) as resp:
poll_result = await resp.json(content_type=None)
if poll_result.get("status") == 1:
stats["solved"] += 1
return poll_result["request"]
if poll_result.get("request") != "CAPCHA_NOT_READY":
stats["failed"] += 1
return None
await asyncio.sleep(POLL_INTERVAL)
stats["failed"] += 1
return None
except Exception as e:
stats["failed"] += 1
return None
async def run_batch(tasks):
"""Process a batch of CAPTCHA tasks concurrently."""
connector = aiohttp.TCPConnector(
limit=MAX_CONCURRENT,
keepalive_timeout=60,
)
async with aiohttp.ClientSession(connector=connector) as session:
coros = [
solve_one(session, task["sitekey"], task["pageurl"], i)
for i, task in enumerate(tasks)
]
results = await asyncio.gather(*coros)
return results
async def main():
# Generate test tasks (replace with your task source)
tasks = [
{
"sitekey": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
"pageurl": "https://www.google.com/recaptcha/api2/demo",
}
for _ in range(100) # Start with 100 tasks
]
stats["start"] = time.time()
print(f"Processing {len(tasks)} tasks with {MAX_CONCURRENT} concurrent workers")
results = await run_batch(tasks)
elapsed = time.time() - stats["start"]
print(f"\nCompleted in {elapsed:.0f}s")
print(f"Submitted: {stats['submitted']}")
print(f"Solved: {stats['solved']}")
print(f"Failed: {stats['failed']}")
print(f"Throughput: {stats['solved'] / (elapsed / 3600):.0f} solves/hour")
asyncio.run(main())
JavaScript: pipeline simultâneo
// high_throughput_solver.js
const axios = require('axios');
const https = require('https');
const API_KEY = process.env.CAPTCHAAI_KEY || 'YOUR_API_KEY';
const BASE = 'https://ocr.captchaai.com';
const MAX_CONCURRENT = 50;
const agent = new https.Agent({ keepAlive: true, maxSockets: MAX_CONCURRENT });
const api = axios.create({ baseURL: BASE, httpsAgent: agent, timeout: 30000 });
const stats = { submitted: 0, solved: 0, failed: 0 };
async function solveOne(sitekey, pageurl) {
try {
const submit = await api.get('/in.php', {
params: { key: API_KEY, method: 'userrecaptcha', googlekey: sitekey, pageurl, json: '1' },
});
if (submit.data.status !== 1) { stats.failed++; return null; }
stats.submitted++;
await new Promise(r => setTimeout(r, 12000));
for (let i = 0; i < 25; i++) {
const poll = await api.get('/res.php', {
params: { key: API_KEY, action: 'get', id: submit.data.request, json: '1' },
});
if (poll.data.status === 1) { stats.solved++; return poll.data.request; }
if (poll.data.request !== 'CAPCHA_NOT_READY') { stats.failed++; return null; }
await new Promise(r => setTimeout(r, 5000));
}
stats.failed++;
return null;
} catch { stats.failed++; return null; }
}
async function runWithConcurrency(tasks, limit) {
const results = [];
const executing = new Set();
for (const task of tasks) {
const p = solveOne(task.sitekey, task.pageurl).then(r => {
executing.delete(p);
return r;
});
executing.add(p);
results.push(p);
if (executing.size >= limit) {
await Promise.race(executing);
}
}
return Promise.all(results);
}
(async () => {
const tasks = Array.from({ length: 100 }, () => ({
sitekey: '6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
pageurl: 'https://www.google.com/recaptcha/api2/demo',
}));
const start = Date.now();
console.log(`Processing ${tasks.length} tasks, ${MAX_CONCURRENT} concurrent`);
await runWithConcurrency(tasks, MAX_CONCURRENT);
const elapsed = (Date.now() - start) / 1000;
console.log(`\nDone in ${elapsed.toFixed(0)}s`);
console.log(`Solved: ${stats.solved}, Failed: ${stats.failed}`);
console.log(`Throughput: ${(stats.solved / (elapsed / 3600)).toFixed(0)} solves/hour`);
agent.destroy();
})();
Parâmetros de ajuste
| Parâmetro | Conservador | Equilibrado | Agressivo |
|---|---|---|---|
| MAX_CONCURRENT | 20 | 50 | 100 |
| INITIAL_WAIT | 15s | 12s | 10s |
| POLL_INTERVAL | 7s | 5s | 3s |
| MAX_POLL_ATTEMPTS | 30 | 25 | 20 |
| Taxa de transferência esperada | ~4.800/hr | ~10.000/hr | ~18.000/hr |
Comece de forma conservadora e aumente MAX_CONCURRENT até ver retornos decrescentes ou taxas de erro aumentadas.
Monitorando a produtividade
Acompanhe essas métricas em tempo real:
- Resoluções por minuto — Deve ficar em aproximadamente 167 para a meta de 10K/hour
- Taxa de erros — Mantenha-se abaixo de 5%. Se houver picos, reduza a simultaneidade
- Profundidade da fila — Se estiver crescendo, aumente os trabalhadores. Se estiver vazio, você está superprovisionado
- Tempo de resolução P90 — Se aumentar, CaptchaAI pode limitar a taxa
Solução de problemas
| Problema | Causa | Correção |
|---|---|---|
| Platôs de rendimento em ~5K/hr | Simultaneidade insuficiente | Aumente MAX_CONCURRENT para 80–100 |
| Taxa de erro > 10% | Sobrecarregando API ou proxies ruins | Reduza a simultaneidade, verifique a integridade do proxy |
| Uso de memória crescendo | Acumulação ilimitada de tarefas | Processe os resultados à medida que chegam, não armazene em buffer |
ERROR_NO_SLOT_AVAILABLE |
Fila CaptchaAI cheia | Recue e tente novamente após 5 segundos |
Perguntas frequentes
Qual é o limite de simultaneidade CaptchaAI?
Não há limite rígido para solicitações simultâneas, mas uma simultaneidade extremamente alta (mais de 500) pode acionar a limitação de taxa. Comece aos 50 e vá aumentando.
Posso executar isso em várias máquinas?
Sim. Use uma fila compartilhada (Redis, RabbitMQ) e execute o script de trabalho em vários servidores. Cada trabalhador executa tarefas de forma independente.
E quanto ao consumo equilibrado nesse ritmo?
Com 10.000 soluções/hour, monitore seu saldo de perto. Use o endpoint de verificação de saldo (res.php?action=getbalance) e configure alertas.
Próximas etapas
Crie seu pipeline CAPTCHA de alto rendimento -obtenha sua chave API CaptchaAI.
Guias relacionados:
- Resolução paralela de CAPTCHA
- Conexão Keep-Alive
- Comparativo de tempos de resolução