# Batch & bulk valuations

Value a stock list, a portfolio or a nightly feed without tripping limits or paying twice. There is no separate bulk endpoint: you send one `POST /v1/valuations` per vehicle, in parallel, within your workspace's limits. This guide gives you a worker that does that safely.

## The limits that matter

| Limit | Default | When you exceed it |
| --- | --- | --- |
| Valuation requests per minute, per workspace | 60 (shared by `POST /v1/valuations`, `POST /v1/selling-times`, `GET /v1/valuations/{id}` and `GET /v1/account`) | `429` [`rate_limited`](/docs/errors#rate_limited) |
| Valuations in progress at once, per workspace | 4 live, and separately 4 test | `429` [`concurrency_limited`](/docs/errors#concurrency_limited) |
| Valuations in progress per market and across the platform | Shared capacity | `503` [`engine_busy`](/docs/errors#engine_busy) |
| Catalogue requests per minute, per workspace | 120 | `429` `rate_limited` |

Your workspace's valuation rate limit is `rate_limit_per_minute` in [GET /v1/account](/docs/reference/account). Every response carries `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` (seconds until the window resets). [Contact sales](/contact-sales) if you need higher limits. See [rate & concurrency limits](/docs/concepts/limits) for the details.

The important property: **`rate_limited`, `concurrency_limited`, `engine_busy` and `rate_limit_unavailable` are rejected before anything is reserved, charged or recorded.** Each carries `retry_after` (seconds) in the body, and REST also sends a `Retry-After` header. Wait that long and resend **the same request with the same idempotency key**.

## Design the batch

1. **One idempotency key per vehicle per run**, derived from your data: `<batch id>-<row id>`, for example `stock-2026-10-26-stock-1001`. Running the same batch again replays recorded results for free instead of valuing twice.
2. **At most 4 requests in flight** and **at most one request start per second** (60 per minute). Lower both if other parts of your system use the same workspace at the same time.
3. **Classify every outcome:**

| Outcome | Action |
| --- | --- |
| Network error, timeout, or a response you cannot parse | Unknown outcome. Back off, resend the same key and body. |
| `rate_limited`, `concurrency_limited`, `engine_busy`, `rate_limit_unavailable`, `request_in_progress` | Not started. Wait `retry_after`, resend the same key and body. |
| `status: "failed"` with `retryable: true` | A recorded failure. Back off, then retry with a **new** key. |
| `status: "refused"`, or any other 4xx | Final for this run. Log `error.code` and `error.fix`; fix the input later. |
| `status: "valued"` | Done. Store the result. |

4. **Cap attempts** (for example five) and report what gave up. Never loop forever, and never retry `insufficient_credits`, `key_spend_limit_reached`, authentication or validation errors.

## Python worker

Needs Python 3.9+ and `requests`.

```python
import os
import random
import threading
import time
from concurrent.futures import ThreadPoolExecutor

import requests

API_URL = "https://data-services.autouncle.com/v1/valuations"
API_KEY = os.environ["AUTOUNCLE_API_KEY"]
MAX_PARALLEL = 4           # default per-workspace limit for concurrent valuations
MIN_INTERVAL = 1.0         # seconds between request starts: 60 per minute
MAX_ATTEMPTS = 5
# Rejected before anything was recorded: wait, then resend the same key and body.
NOT_STARTED = {"rate_limited", "concurrency_limited", "engine_busy", "rate_limit_unavailable", "request_in_progress"}

_pace_lock = threading.Lock()
_next_start = 0.0


def pace():
    """Space request starts so the batch stays under the per-minute rate limit."""
    global _next_start
    with _pace_lock:
        now = time.monotonic()
        wait = max(0.0, _next_start - now)
        _next_start = max(now, _next_start) + MIN_INTERVAL
    if wait:
        time.sleep(wait)


def retry_delay(response, attempt):
    """Seconds to wait: retry_after in the body, else Retry-After, else backoff."""
    try:
        body = response.json()
        error = body.get("error", body)
        if error.get("retry_after"):
            return float(error["retry_after"])
    except ValueError:
        pass
    if response.headers.get("Retry-After"):
        return float(response.headers["Retry-After"])
    return min(30.0, 2 ** attempt) + random.random()


def value(row_id, body, batch_id):
    base_key = f"{batch_id}-{row_id}"
    key = base_key
    for attempt in range(1, MAX_ATTEMPTS + 1):
        pace()
        try:
            response = requests.post(
                API_URL,
                headers={"Authorization": f"Bearer {API_KEY}", "Idempotency-Key": key},
                json=body,
                timeout=30,
            )
            data = response.json()
        except (requests.RequestException, ValueError):
            # Unknown outcome: resend the same key and body. A replay never charges twice.
            time.sleep(min(30.0, 2 ** attempt) + random.random())
            continue

        error = data.get("error", data) if response.status_code >= 400 else {}
        code = error.get("code")

        if code in NOT_STARTED:
            time.sleep(retry_delay(response, attempt))
            continue  # same key: nothing was recorded
        if data.get("status") == "failed" and error.get("retryable"):
            # A recorded, retryable failure: wait, then make a fresh attempt with a new key.
            time.sleep(min(30.0, 2 ** attempt) + random.random())
            key = f"{base_key}-retry{attempt}"
            continue
        return row_id, response.status_code, data

    return row_id, None, {"status": "gave_up"}


def run(rows, batch_id):
    with ThreadPoolExecutor(max_workers=MAX_PARALLEL) as pool:
        futures = [pool.submit(value, row_id, body, batch_id) for row_id, body in rows]
        for future in futures:
            row_id, http_status, data = future.result()
            error = data.get("error") or {}
            print(row_id, http_status, data.get("status"), data.get("request_id"),
                  data.get("valuation", {}).get("price"), error.get("code"))


if __name__ == "__main__":
    rows = [
        ("stock-1001", {"country": "DK", "vehicle": {"make": "VW", "model": "Golf", "model_year": 2020,
                                                      "mileage": {"value": 60000, "unit": "km"}}}),
        ("stock-1002", {"country": "DK", "vehicle": {"make": "Skoda", "model": "Octavia", "model_year": 2019,
                                                      "mileage": {"value": 85000, "unit": "km"}}}),
        ("stock-1003", {"country": "DK", "vehicle": {"make": "VW", "model": "Golf", "model_year": 2021}}),
    ]
    run(rows, batch_id="stock-2026-10-26")
```

## Node.js worker

Needs Node.js 18 or later. Save it as `batch.mjs` and run `node batch.mjs`.

```javascript
const API_URL = "https://data-services.autouncle.com/v1/valuations";
const API_KEY = process.env.AUTOUNCLE_API_KEY;
const MAX_PARALLEL = 4; // default per-workspace limit for concurrent valuations
const MIN_INTERVAL_MS = 1000; // 60 request starts per minute
const MAX_ATTEMPTS = 5;
// Rejected before anything was recorded: wait, then resend the same key and body.
const NOT_STARTED = new Set(["rate_limited", "concurrency_limited", "engine_busy", "rate_limit_unavailable", "request_in_progress"]);

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const backoff = (attempt) => Math.min(30_000, 2 ** attempt * 1000) + Math.random() * 1000;

let nextStart = 0;
async function pace() {
  const now = Date.now();
  const wait = Math.max(0, nextStart - now);
  nextStart = Math.max(now, nextStart) + MIN_INTERVAL_MS;
  if (wait) await sleep(wait);
}

async function value(rowId, body, batchId) {
  const baseKey = `${batchId}-${rowId}`;
  let key = baseKey;
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
    await pace();
    let response;
    let data;
    try {
      response = await fetch(API_URL, {
        method: "POST",
        headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": key },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(30_000),
      });
      data = await response.json();
    } catch {
      // Unknown outcome: resend the same key and body. A replay never charges twice.
      await sleep(backoff(attempt));
      continue;
    }
    const error = response.status >= 400 ? data.error ?? data : {};
    if (NOT_STARTED.has(error.code)) {
      const seconds = error.retry_after ?? Number(response.headers.get("Retry-After"));
      await sleep(seconds ? seconds * 1000 : backoff(attempt));
      continue; // same key: nothing was recorded
    }
    if (data.status === "failed" && error.retryable) {
      // A recorded, retryable failure: wait, then make a fresh attempt with a new key.
      await sleep(backoff(attempt));
      key = `${baseKey}-retry${attempt}`;
      continue;
    }
    return { rowId, httpStatus: response.status, data };
  }
  return { rowId, httpStatus: null, data: { status: "gave_up" } };
}

async function run(rows, batchId) {
  const queue = [...rows];
  const results = [];
  const worker = async () => {
    for (let row = queue.shift(); row; row = queue.shift()) {
      results.push(await value(row.id, row.body, batchId));
    }
  };
  await Promise.all(Array.from({ length: MAX_PARALLEL }, worker));
  return results;
}

const rows = [
  { id: "stock-1001", body: { country: "DK", vehicle: { make: "VW", model: "Golf", model_year: 2020, mileage: { value: 60000, unit: "km" } } } },
  { id: "stock-1002", body: { country: "DK", vehicle: { make: "Skoda", model: "Octavia", model_year: 2019, mileage: { value: 85000, unit: "km" } } } },
  { id: "stock-1003", body: { country: "DK", vehicle: { make: "VW", model: "Golf", model_year: 2021 } } },
];
for (const { rowId, httpStatus, data } of await run(rows, "stock-2026-10-26")) {
  console.log(rowId, httpStatus, data.status, data.request_id, data.valuation?.price, data.error?.code);
}
```

Both print one line per vehicle. With the three example rows and a test key, the first two are `valued` and the third is `refused` with `missing_mileage`, because it has no mileage.

## Store and reconcile

- Store `request_id`, `status`, the price block, `precision.grade`, `notes` and `attributions` per row.
- For rows that gave up with an unknown outcome, run the batch again with the same batch ID. Rows that were recorded replay their stored result with `usage.idempotent_replay: true` and `credits_used: 0`; the rest are valued now.
- Use the console's **Request logs** (filter by status) and **Usage** (CSV export) to check the run. See [retrieve, replay & reconcile](/docs/guides/polling-and-replay).

## Credits in a batch

Each `valued` live row uses one credit; refusals and failures are free. If credits run out mid-batch, the remaining rows return `402` [`insufficient_credits`](/docs/errors#insufficient_credits) (or `key_spend_limit_reached` when the key's monthly limit is reached). Stop the batch on these codes rather than letting every remaining row fail. Check `credits_remaining` in [GET /v1/account](/docs/reference/account) before a large run, and see [credits & billing](/docs/credits).

## Pitfalls

- **Unbounded parallelism.** Firing hundreds of requests at once only produces `concurrency_limited` and `rate_limited` responses. They are free, but they slow the batch down.
- **Random idempotency keys.** A fresh random key on every retry turns an unknown outcome into a possible double charge. Derive keys from your data.
- **Retrying refusals.** A refused row will be refused again with the same input.
- **Mixing test and live.** Test and live keys have separate concurrency and separate idempotency. A test run proves your code, not your credit needs.

## Next steps

- [Rate & concurrency limits](/docs/concepts/limits).
- [Idempotency](/docs/concepts/idempotency).
- [Production checklist](/docs/production-checklist).
