DataTalk Docs

Async Tasks

Understanding the asynchronous task pattern

Several DataTalk API operations are long-running — they involve AI processing. These operations use an async task pattern instead of blocking the request.

How It Works

  1. You call an endpoint (e.g., POST /generate-query)
  2. The API returns immediately with a taskId and status 202 Accepted
  3. You poll GET /task/:taskId until the task completes
  4. Alternatively, configure webhooks to receive push notifications when tasks complete

Endpoints That Create Tasks

EndpointTask Type
POST /generate-queryGENERATE_QUERY

Task Lifecycle

PENDING → PROCESSING → COMPLETED
                     → FAILED
StatusDescription
PENDINGTask is queued and waiting to be picked up
PROCESSINGTask is actively being processed by the AI
COMPLETEDTask finished successfully — check the result field
FAILEDTask failed — check the error field

Polling Strategy

The GET /task/:taskId endpoint returns a Retry-After: 2 header when the task is not yet complete. A recommended polling approach:

async function pollTask(taskId) {
  while (true) {
    const res = await fetch(`${API_BASE}/task/${taskId}`, {
      headers: { Authorization: `Bearer ${API_KEY}` },
    });
    const task = await res.json();

    if (task.status === "COMPLETED" || task.status === "FAILED") {
      if (task.status === "FAILED") {
        throw new Error(JSON.stringify(task.error));
      }
      return task;
    }

    // Respect the Retry-After header
    const retryAfter = res.headers.get("Retry-After") ?? "2";
    await new Promise((r) => setTimeout(r, parseInt(retryAfter) * 1000));
  }
}

Token Usage

Completed tasks include a usage object with AI token consumption:

{
  "usage": {
    "inputTokens": 1250,
    "outputTokens": 85,
    "totalTokens": 1335,
    "costUsd": 0.0042
  }
}

This lets you track AI costs per request.

Webhooks as Alternative

Instead of polling, you can receive push notifications by configuring webhook endpoints in your user settings. See Webhooks for details.

On this page