Skip to main content

Overview

Polling provides a pull-based mechanism for retrieving automation task results. After submitting a task via the Remote Dispatch API, you can periodically check for completion using the Get Task Status endpoint.

Simple Setup

No webhook endpoints or server infrastructure required to get started

Firewall Friendly

Works in restricted network environments without opening inbound ports

No Server Required

Perfect for scripts, CLI tools, and applications without a web server

Full Control

You decide when and how often to check for results

How Polling Works

When you submit an automation task, you receive a requestId that you can use to poll for the task status until it completes.
1

Submit Task

Send a request to the Remote Dispatch API and receive a requestId
2

Wait

Wait for an appropriate interval before checking status
3

Check Status

Call the Get Task Status endpoint with your requestId
4

Handle Response

If status is pending, go back to step 2. Otherwise, process the result.
Polling is ideal for simple integrations, scripts, and environments where setting up webhook endpoints isn’t feasible.

Basic Implementation

Here’s how to implement basic polling in different languages:
# Submit the task
REQUEST_ID=$(curl -s -X POST 'https://api.narada.ai/fast/v2/remote-dispatch' \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
    "prompt": "/Operator search for software engineering jobs",
    "browserWindowId": "your-browser-window-id"
  }' | jq -r '.requestId')

echo "Task submitted: $REQUEST_ID"

# Poll for completion
while true; do
  RESPONSE=$(curl -s -X GET "https://api.narada.ai/fast/v2/remote-dispatch/responses/$REQUEST_ID" \
    -H 'x-api-key: YOUR_API_KEY')

  STATUS=$(echo $RESPONSE | jq -r '.status')

  if [ "$STATUS" != "pending" ]; then
    echo "Task completed with status: $STATUS"
    echo $RESPONSE | jq '.response'
    break
  fi

  echo "Task still pending, waiting 5 seconds..."
  sleep 5
done

Polling with Timeout

Here’s a complete example with timeout handling:
import requests
import time
import os

def poll_for_result(request_id: str, timeout: int = 300, poll_interval: int = 5) -> dict:
    """Poll for task completion with timeout."""
    api_key = os.environ['NARADA_API_KEY']
    deadline = time.time() + timeout

    while True:
        remaining = deadline - time.time()
        if remaining <= 0:
            raise TimeoutError(f"Task did not complete within {timeout}s")

        # Check status
        response = requests.get(
            f'https://api.narada.ai/fast/v2/remote-dispatch/responses/{request_id}',
            headers={'x-api-key': api_key}
        )
        result = response.json()

        if result['status'] != 'pending':
            return result

        time.sleep(min(poll_interval, remaining))

# Usage
try:
    result = poll_for_result('req_abc123def456', timeout=120)

    if result['status'] == 'success':
        print(f"Success: {result['response']['text']}")
    elif result['status'] == 'error':
        print(f"Error: {result['response']['text']}")
    elif result['status'] == 'input-required':
        print(f"Input required: {result['response']['text']}")

except TimeoutError as e:
    print(f"Timeout: {e}")

Response Handling

The Get Task Status endpoint returns different statuses that you should handle appropriately:
{
  "status": "pending",
  "response": null,
  "createdAt": "2024-12-19T00:00:00.000000+00:00",
  "completedAt": null
}
The task is still running. Continue polling after waiting.

Best Practices

Use Reasonable Intervals

Poll every 5-10 seconds to balance responsiveness with API efficiency

Set Timeouts

Always implement maximum timeouts to prevent infinite polling loops

Handle All Statuses

Implement handlers for success, error, input-required, and timeout scenarios

Log Progress

Log polling attempts for debugging and monitoring purposes

Handle Network Errors

Wrap API calls in try-except to handle transient network failures gracefully

Consider Webhooks

For production apps with many concurrent tasks, webhooks may be more efficient

Comparison: Polling vs Webhooks

FeaturePollingWebhooks
Setup ComplexityLowMedium
InfrastructureNone requiredWeb server needed
Real-time UpdatesNo (delayed by interval)Yes
Resource UsageHigher (active requests)Lower
Firewall FriendlyYesRequires open ports
ScalabilityLimitedExcellent
Best ForScripts, simple appsProduction systems
Start with polling for development and simple use cases. Migrate to webhooks when you need real-time notifications or are handling high volumes of tasks.

Common Issues

Problem: Making too many requests and hitting rate limits.Solution: Use a reasonable polling interval of 5-10 seconds. This balances responsiveness with API efficiency.
POLL_INTERVAL = 5  # seconds - good balance for most use cases
time.sleep(POLL_INTERVAL)
Problem: Script runs forever if a task never completes.Solution: Always set a maximum timeout for your polling loop.
start = time.time()
while time.time() - start < MAX_TIMEOUT:
    # poll...
raise TimeoutError("Task did not complete in time")
Problem: Code breaks when receiving unexpected status values.Solution: Handle all possible statuses: pending, success, error, and input-required.
if result['status'] == 'success':
    handle_success(result)
elif result['status'] == 'error':
    handle_error(result)
elif result['status'] == 'input-required':
    handle_input_required(result)
Problem: Network errors crash the polling loop.Solution: Wrap API calls in try-except and implement retry logic.
try:
    response = requests.get(url, headers=headers, timeout=10)
    response.raise_for_status()
except requests.RequestException as e:
    logger.warning(f"API request failed: {e}, retrying...")
    time.sleep(interval)
    continue

Next Steps

Production Checklist: Before deploying, ensure you have reasonable polling intervals, maximum timeouts, comprehensive error handling, and logging implemented.