Tasks API Documentation

The Tasks API allows you to schedule, manage, and execute HTTP callback tasks. Tasks are processed asynchronously by background workers with support for retries, delays, and completion webhooks.


Authentication

All task endpoints require API key authentication. You can provide your API key in one of two ways:

bash
# Using Authorization header (recommended)
Authorization: Bearer <your-api-key>

# Using X-API-Key header

X-API-Key: <your-api-key>

API keys are scoped to a team. All tasks created with an API key belong to that team.


Base URL

https://api.asyncqueue.io

Endpoints

Create Task

Create a new task to execute an HTTP callback.

POST /v1/tasks

Request Body

FieldTypeRequiredDefaultDescription
callbackUrlstringYes-The URL to call when the task executes. Must be a valid HTTP/HTTPS URL.
methodstringNo"POST"HTTP method: GET, POST, PUT, or DELETE
headersobjectNo{}Custom headers to include in the callback request
bodystringNo-Request body (JSON stringified). Ignored for GET requests.
maxWaitTimenumberNo30Maximum time (in seconds) to wait for the callback response
timeoutnumberNo30HTTP timeout (in seconds) for each attempt
delayUntilstringNo-ISO 8601 timestamp. Task won’t execute until this time.
maxRetriesnumberNo3Maximum retry attempts (0-10)
retryBackoffstringNo"exponential"Retry strategy: linear or exponential
onCompleteUrlstringNo-Webhook URL to notify when task completes (success or failure)

Example Request

bash
curl -X POST https://api.asyncqueue.io/v1/tasks \
-H "Authorization: Bearer your-api-key" \
-H "Content-Type: application/json" \
-d '{
  "callbackUrl": "https://api.example.com/webhook",
  "method": "POST",
  "headers": {
    "Authorization": "Bearer service-token",
    "X-Custom-Header": "value"
  },
  "body": "{\"action\": \"process\", \"data\": {\"id\": 123}}",
  "maxWaitTime": 60,
  "timeout": 30,
  "maxRetries": 3,
  "retryBackoff": "exponential",
  "onCompleteUrl": "https://api.example.com/task-complete"
}'

Example Response (201 Created)

json
{
"task": {
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "teamId": "team-uuid",
  "status": "pending",
  "callbackUrl": "https://api.example.com/webhook",
  "method": "POST",
  "headers": {
    "Authorization": "Bearer service-token",
    "X-Custom-Header": "value"
  },
  "body": "{\"action\": \"process\", \"data\": {\"id\": 123}}",
  "maxWaitTime": 60,
  "timeout": 30,
  "maxRetries": 3,
  "retryCount": 0,
  "retryBackoff": "exponential",
  "onCompleteUrl": "https://api.example.com/task-complete",
  "createdAt": "2024-01-15T10:30:00.000Z"
}
}

Creating a Delayed Task

To schedule a task for future execution, use the delayUntil parameter:

bash
curl -X POST https://api.asyncqueue.io/v1/tasks \
-H "Authorization: Bearer your-api-key" \
-H "Content-Type: application/json" \
-d '{
  "callbackUrl": "https://api.example.com/scheduled-job",
  "delayUntil": "2024-01-15T14:00:00.000Z"
}'

The task will have status delayed until the scheduled time.


Get Task

Retrieve a task by ID to check its status and result.

GET /v1/tasks/:id

Example Request

bash
curl https://api.asyncqueue.io/v1/tasks/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer your-api-key"

Example Response (200 OK) - Completed Task

json
{
"task": {
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "teamId": "team-uuid",
  "status": "completed",
  "callbackUrl": "https://api.example.com/webhook",
  "method": "POST",
  "maxWaitTime": 60,
  "timeout": 30,
  "maxRetries": 3,
  "retryCount": 0,
  "retryBackoff": "exponential",
  "result": {
    "statusCode": 200,
    "headers": {
      "content-type": "application/json"
    },
    "body": "{\"success\": true, \"processedId\": 123}",
    "duration": 1234
  },
  "createdAt": "2024-01-15T10:30:00.000Z",
  "startedAt": "2024-01-15T10:30:01.000Z",
  "completedAt": "2024-01-15T10:30:02.234Z"
}
}

Example Response - Failed Task

json
{
"task": {
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "teamId": "team-uuid",
  "status": "failed",
  "callbackUrl": "https://api.example.com/webhook",
  "method": "POST",
  "maxWaitTime": 60,
  "timeout": 30,
  "maxRetries": 3,
  "retryCount": 3,
  "retryBackoff": "exponential",
  "error": "fetch failed: ECONNREFUSED",
  "createdAt": "2024-01-15T10:30:00.000Z",
  "startedAt": "2024-01-15T10:30:01.000Z",
  "completedAt": "2024-01-15T10:30:15.000Z"
}
}

List Tasks

List all tasks for your team with optional filtering and pagination.

GET /v1/tasks

Query Parameters

ParameterTypeDefaultDescription
statusstring-Filter by status: pending, delayed, processing, completed, failed, timeout, cancelled
limitnumber50Number of results (max 100)
offsetnumber0Pagination offset
sortOrderstring"desc"Sort by createdAt: asc or desc

Example Request

bash
# Get the 10 most recent pending tasks
curl "https://api.asyncqueue.io/v1/tasks?status=pending&limit=10" \
-H "Authorization: Bearer your-api-key"

Example Response (200 OK)

json
{
"tasks": [
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "teamId": "team-uuid",
    "status": "pending",
    "callbackUrl": "https://api.example.com/webhook",
    "method": "POST",
    "maxWaitTime": 30,
    "timeout": 30,
    "maxRetries": 3,
    "retryCount": 0,
    "retryBackoff": "exponential",
    "createdAt": "2024-01-15T10:30:00.000Z"
  }
],
"pagination": {
  "total": 150,
  "limit": 10,
  "offset": 0,
  "hasMore": true
}
}

Cancel Task

Cancel a pending or delayed task before it starts processing.

POST /v1/tasks/:id/cancel

Only tasks with status pending or delayed can be cancelled.

Example Request

bash
curl -X POST https://api.asyncqueue.io/v1/tasks/550e8400-e29b-41d4-a716-446655440000/cancel \
-H "Authorization: Bearer your-api-key"

Example Response (200 OK)

json
{
"task": {
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "teamId": "team-uuid",
  "status": "cancelled",
  "callbackUrl": "https://api.example.com/webhook",
  "method": "POST",
  "maxWaitTime": 30,
  "timeout": 30,
  "maxRetries": 3,
  "retryCount": 0,
  "retryBackoff": "exponential",
  "createdAt": "2024-01-15T10:30:00.000Z",
  "completedAt": "2024-01-15T10:31:00.000Z"
}
}

Task Status Lifecycle

Tasks progress through the following statuses:

StatusDescription
pendingTask is queued and waiting to be processed
delayedTask is waiting for its delayUntil time
processingWorker is executing the callback
completedCallback returned successfully (any HTTP status)
failedAll retry attempts exhausted
timeoutTask exceeded maxWaitTime
cancelledTask was cancelled before processing

Retry Behavior

When a callback fails (network error, 5xx response, or timeout), the task will be retried according to your configuration.

Retry Strategies

Exponential Backoff (default):

  • Retry 1: 1 second delay
  • Retry 2: 2 seconds delay
  • Retry 3: 4 seconds delay
  • Retry 4: 8 seconds delay

Linear Backoff:

  • Retry 1: 1 second delay
  • Retry 2: 2 seconds delay
  • Retry 3: 3 seconds delay

What Triggers a Retry

  • Network errors (connection refused, DNS failure, etc.)
  • HTTP 5xx responses
  • Request timeout

What Does NOT Trigger a Retry

  • HTTP 2xx responses (success)
  • HTTP 3xx responses (redirects are followed automatically)
  • HTTP 4xx responses (client errors are considered “completed”)

onComplete Webhook

When you provide an onCompleteUrl, AsyncQueue will send a POST request to that URL when the task completes (success, failure, or timeout).

Webhook Payload

json
{
"event": "task.completed",
"task": {
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "result": {
    "statusCode": 200,
    "headers": {"content-type": "application/json"},
    "body": "{\"success\": true}",
    "duration": 1234
  },
  "error": null,
  "retryCount": 0,
  "createdAt": "2024-01-15T10:30:00.000Z",
  "completedAt": "2024-01-15T10:30:02.234Z"
}
}

Webhook Behavior

  • Webhooks are fire-and-forget with a 10-second timeout
  • Failed webhooks are logged but do not affect task status
  • Webhooks are not retried on failure

Error Responses

400 Bad Request

json
{
"error": "callbackUrl is required"
}

Common validation errors:

  • callbackUrl is required
  • callbackUrl must be a valid HTTP/HTTPS URL
  • method must be one of: GET, POST, PUT, DELETE
  • maxRetries must be a number between 0 and 10
  • delayUntil must be a valid ISO 8601 date

401 Unauthorized

json
{
"error": "API key required"
}

Or:

json
{
"error": "Invalid or revoked API key"
}

403 Forbidden

json
{
"error": "Access denied"
}

Returned when trying to access a task belonging to a different team.

404 Not Found

json
{
"error": "Task not found"
}

Code Examples

Node.js

asyncqueue.js
const API_KEY = 'your-api-key';
const BASE_URL = 'https://api.asyncqueue.io';

// Create a task
async function createTask(taskData) {
const response = await fetch(`${BASE_URL}/v1/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(taskData)
});
return response.json();
}

// Get task status
async function getTask(taskId) {
const response = await fetch(`${BASE_URL}/v1/tasks/${taskId}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
return response.json();
}

// Example usage
const { task } = await createTask({
callbackUrl: 'https://api.example.com/process',
body: JSON.stringify({ orderId: 12345 }),
maxRetries: 5
});

console.log(`Task created: ${task.id}`);

Python

asyncqueue.py
import requests

API_KEY = 'your-api-key'
BASE_URL = 'https://api.asyncqueue.io'

headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}

# Create a task

def create_task(task_data):
response = requests.post(
f'{BASE_URL}/v1/tasks',
headers=headers,
json=task_data
)
return response.json()

# Get task status

def get_task(task_id):
response = requests.get(
f'{BASE_URL}/v1/tasks/{task_id}',
headers=headers
)
return response.json()

# Example usage

result = create_task({
'callbackUrl': 'https://api.example.com/process',
'body': '{"orderId": 12345}',
'maxRetries': 5
})

print(f"Task created: {result['task']['id']}")

Rate Limits & Plan Limits

FeatureFree PlanPro Plan
Max Wait Time30 seconds120 seconds
API Keys1 per teamUnlimited
Team Members2Unlimited

Best Practices

1. Use Idempotent Callbacks

Design your callback endpoints to be idempotent. If a task is retried, your endpoint should handle duplicate requests gracefully.

2. Set Appropriate Timeouts

  • Use timeout for the HTTP request timeout (how long to wait for a response)
  • Use maxWaitTime for the total task duration limit

3. Handle Webhook Failures Gracefully

Since onComplete webhooks are fire-and-forget, implement polling as a fallback:

javascript
// Create task
const { task } = await createTask({
callbackUrl: '...',
onCompleteUrl: '...'
});

// Poll for completion as fallback
const result = await pollUntilComplete(task.id, {
maxAttempts: 10,
interval: 5000
});

4. Use Delayed Tasks for Scheduling

Instead of implementing your own cron/scheduler, use delayUntil:

javascript
// Send reminder email in 24 hours
await createTask({
callbackUrl: 'https://api.example.com/send-reminder',
delayUntil: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
});

5. Monitor Task Status

Implement monitoring for failed tasks:

javascript
// Get failed tasks from the last hour
const { tasks } = await listTasks({
status: 'failed',
limit: 100
});

// Alert if there are failures
if (tasks.length > 0) {
alertOps(`${tasks.length} failed tasks in the last hour`);
}