Skip to main content

Polling an async rewrite API from a Python job queue: 202s, statuses and retries

Updated 6 min readMarkdown

Your web app can return a job ID before a rewrite is ready. A background worker then submits the text to the AI humanizer API from AI Checker Humanizer, gets 202 Accepted with a task ID, and polls for the result. The request that started the job has usually finished long before the rewrite does.

Save the API's task ID on the job row, so a restarted worker knows which result to fetch. The same setup works with other APIs that let you poll by task ID.

The shape of the call

POST /api/v1/humanize takes text (up to 3,000 words), an optional mode and strength. A 202 means the API accepted the request. Save the taskId, then poll GET /api/v1/humanize/{taskId} every few seconds while the status is queued or running. The POST response may also include status and creditsReserved.

Two numbers shape the worker:

  • A task that hasn't started within 2 minutes fails with queue_timeout and costs nothing.
  • The result can be fetched until the expiresAt time in the response, about 70 minutes after you submit. After that the same endpoint returns 410 result_expired.

So the worker can't park a task and come back the next morning. It needs to fetch the text and store it in your own database within that window.

Don't poll from the web request

Keep the user's HTTP request short. Save a job row, enqueue it, and return. A background worker does the rest:

import os, time, uuid, requests

API = "https://aicheckerhumanizer.com/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['AICH_API_KEY']}"}

def start_rewrite(job):
    # One idempotency key per job, stored before the first call,
    # so a retry after a timeout points at the same task.
    if not job.idempotency_key:
        job.idempotency_key = f"job-{job.id}-{uuid.uuid4()}"
        job.save()

    r = requests.post(
        f"{API}/humanize",
        headers={**HEADERS, "Idempotency-Key": job.idempotency_key},
        json={"text": job.text, "mode": job.mode},
        timeout=30,
    )
    if r.status_code in (409, 429, 503):
        retry_after = int(r.headers.get("Retry-After") or r.json().get("retryAfter", 10))
        return ("retry", retry_after)
    r.raise_for_status()
    job.task_id = r.json()["taskId"]
    job.save()
    return ("poll", 3)

Save the key before the first POST. If the call times out, resend the same key, text and options within 24 hours. If the API had accepted the request, it returns the original task ID without a second charge. If the first POST was never accepted, retry with the same key. Use a fresh key when you intend to start a separate rewrite.

When to stop polling

After a successful GET, keep polling while the task is queued or running. Everything else is final. If the GET itself returns 429 or 503, wait for Retry-After and poll the same task again.

Status What it means for your worker
queued, running Poll again in about 3 seconds.
completed At least one chunk was rewritten. Save output.
partial Some chunks were rewritten and some failed. Save output and units.
unchanged Nothing was rewritten. No charge.
failed No rewrite. Check reason.
cancelled Stopped before it started. No charge.

With partial, output contains the full text and leaves the failed chunks as you submitted them. For a before-and-after view, use text and output on the units marked succeeded. To highlight a chunk in the original, start and end are UTF-16 offsets with an exclusive end, the same as JavaScript string indexes. In A😀B, B is at index 2 in Python and offset 3 in UTF-16, so convert the offsets before slicing the original string in Python.

def poll(job):
    r = requests.get(f"{API}/humanize/{job.task_id}", headers=HEADERS, timeout=30)
    if r.status_code in (429, 503):
        return ("poll", int(r.headers.get("Retry-After", 10)))
    if r.status_code == 410:
        job.mark_failed("result_expired")   # too late, start over
        return None
    r.raise_for_status()
    task = r.json()
    if task["status"] in ("queued", "running"):
        return ("poll", 3)
    if task["status"] in ("completed", "partial"):
        job.save_output(task["output"], units=task["units"], charged=task["creditsCharged"])
    else:
        job.mark_failed(task.get("reason") or task["status"])
    return None

Failures that need a new key

Once the API has accepted a task, its idempotency key keeps pointing at that task, even if the task fails. Resending with the same key within 24 hours returns that failed task again. Two reasons matter here:

  • queue_timeout: the task never started. Start over with a new key.
  • not_humanized: the API returned no rewrite that its detector rated likely human, and the task costs no credits. The check applies when every paragraph to be rewritten is in English and the text has at least 150 English words, making up at least 80% of it.

Record the reason in the job row. If the same text keeps failing, show that to the user. Don't let the worker retry it forever.

Limits that change how many workers you run

Queued and running rewrites both count toward your account's limit:

  • With trial credits only, you get one slot. After your first credit purchase, you get up to 10.
  • If a new English rewrite needs the detector check and your account already has two or more rewrites queued or running, the POST returns 409 busy.

The API counts queued and running rewrites against your account limit, so limit how many you have submitted at once. If your worker uses a semaphore, hold its slot across polls and release it when you learn the task has finished, not just around the POST. Treat 409 busy as "wait for Retry-After and resubmit", not as an error.

429 comes in two kinds. rate_limited is the hourly limit and has a retryAfter. api_paused means the account hit its daily limit for work that wasn't charged (failed, unchanged or no-verdict requests), and new jobs pause until midnight UTC. A worker that retries failed jobs in a tight loop can trigger the second one, which is another reason to cap retries.

When the worker restarts

  • If the job row has a taskId, resume polling it.
  • If you saved the key but never got a taskId, resend the same POST with that key, text and options within 24 hours.
  • If polling returns 410 result_expired, record the expiry and stop polling. Start a new task with a new key if the user still wants the rewrite.

No comments yet. Be the first to comment.