# Working with large batches

> Run thousands of SERP, profile or page tasks with task arrays, queues and callbacks while staying inside rate limits and your wallet.

For thousands of tasks, the pattern is the same on every family: chunk into arrays of 100, post them to a queue, and collect results as they finish.

## Plan the run

| Question | Answer |
|---|---|
| How many requests? | `ceil(tasks / 100)`. 10,000 keywords is 100 `task_post` requests. |
| How fast can I send them? | 120 requests per minute per key, so 100 requests take under a minute. |
| What will it cost? | Tasks × unit price × units per task. 10,000 keywords at depth 10 in the standard queue: 10,000 × $0.00054 = $5.40, if every task returns results. |
| Will my wallet cover it? | Each request checks that the balance covers its own worst case before it runs. For a queued SERP task with `auto_upgrade` on, that's the live price, so 100 tasks at depth 10 need $0.18 of balance to be accepted. Charges settle as tasks finish, so top up for the expected cost of the whole run. |

## Post in chunks

```python
import os
import time
import requests

BASE = "https://api.dataforgaio.com/v1"
AUTH = ("api", os.environ["DATAFORGAIO_API_KEY"])

def chunks(items, size=100):
    for i in range(0, len(items), size):
        yield items[i:i + size]

keywords = [line.strip() for line in open("keywords.txt") if line.strip()]
posted = {}

for chunk in chunks(keywords):
    tasks = [
        {"keyword": kw, "location_code": 2840, "language_code": "en", "depth": 10, "tag": kw[:255]}
        for kw in chunk
    ]
    res = requests.post(f"{BASE}/serp/google/organic/task_post", auth=AUTH, json=tasks, timeout=60)
    if res.status_code == 429:
        time.sleep(int(res.headers.get("Retry-After", "5")))
        res = requests.post(f"{BASE}/serp/google/organic/task_post", auth=AUTH, json=tasks, timeout=60)
    body = res.json()
    if body["status_code"] != 20000:
        raise SystemExit(f'{body["status_code"]} {body["status_message"]}')
    for t in body["tasks"]:
        if t["status_code"] == 20100:
            posted[t["id"]] = t["data"]["keyword"]
        else:
            print("not queued:", t["data"].get("keyword"), t["status_code"], t["status_message"])
```

Keep the returned ids. They're how you collect results and how you avoid posting the same work twice.

## Collect results

Either set `postback_url` on each task and let results come to you (see [Handling webhooks securely](https://dataforgaio.com/docs/webhooks.md)), or poll:

```python
results = {}
while len(results) < len(posted):
    ready = requests.get(f"{BASE}/serp/google/organic/tasks_ready", auth=AUTH, timeout=60).json()
    for row in ready["tasks"][0]["result"] or []:
        got = requests.get(f'https://api.dataforgaio.com{row["endpoint_advanced"]}', auth=AUTH, timeout=60).json()
        task = got["tasks"][0]
        results[task["id"]] = task
    time.sleep(30)
```

`tasks_ready` returns up to 1,000 uncollected tasks per call, and `task_get` marks each one collected. Failed tasks never show up in `tasks_ready`, so the loop above would wait forever on one. In production, also check ids you've waited on for a while with `task_get` directly, or list failures with `POST /v1/account/errors`.

Each `task_get` counts against the 120-per-minute budget. For very large runs, postbacks avoid that cost.

## Crawl API batches

The Crawl API batches up to 100 URLs per `POST /v1/crawls/batch`, returns a `job_id` at once, and can post the finished job to `webhook_url`:

```bash
curl -X POST "https://api.dataforgaio.com/v1/crawls/batch" \
  -H "Authorization: Bearer $DATAFORGAIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "targets": [{"url": "https://example.com/a"}, {"url": "https://example.com/b"}],
    "output_format": "markdown",
    "max_level": "rendered",
    "webhook_url": "https://your-app.example/hooks/crawls/SECRET"
  }'
```

If any target URL is invalid, the whole batch is refused with `422 invalid_target` and `details.targets` naming each bad index. Nothing is queued or billed.

## Checklist

- Chunk into 100 and pace requests to stay under 120 per minute per key.
- Use the standard queue unless you need results within the hour.
- Set `max_cost` per task when you want a hard ceiling.
- Store task ids and tags as you post.
- Collect with postbacks, with `tasks_ready` as a backstop.
- Re-post only tasks that failed with `50000`.
