# Async Document Processing API Webhook Patterns

- Canonical: https://schematax.com/blog/async-document-processing-api-webhook-patterns
- Author: Schema Tax (https://schematax.com)
- Published: 2026-06-21T17:08:52.000Z
- Updated: 2026-06-21T17:08:52.000Z

To handle an async document processing API with webhooks, upload the file, store the job ID the API returns, and let the service call your webhook when extraction finishes. Your handler verifies the signature, drops duplicate events, queues the work and answers fast, while a polling job catches any event that never arrives.

## Why does a document processing API use webhooks instead of waiting?

A document processing API uses webhooks because reading a tax form takes longer than a web request should stay open. A ten-page scan has to be straightened, classified page by page and read box by box. Holding the connection open for that whole time invites timeouts, so the API accepts the file and reports back later.

The usual shape has two halves. Your app sends the file and gets an immediate answer that says the job was accepted, along with an ID. Later, when the work is done, the service sends an HTTP request to a URL you registered. That second request is the webhook, and it carries the job ID and the outcome.

HTTP has a status code for the first half. [RFC 9110, the HTTP Semantics standard](https://www.rfc-editor.org/rfc/rfc9110#name-202-accepted), defines 202 (Accepted) as meaning the request "has been accepted for processing, but the processing has not been completed." The same section notes that HTTP has no way to resend a status code from an asynchronous operation. That gap is exactly what a webhook or a status endpoint fills.

File size makes the case stronger. A single W-2 photo may finish quickly, but a client packet with a consolidated brokerage statement can run to dozens of pages. If your code waits on the upload call, one large file can hold a worker, a load balancer slot and a user's spinner for the full run. Splitting submit from result keeps each request short.

Multi-page files also finish unevenly. Some services report per document as each one completes, and others send one event when the whole file is done. Plan your data model for either: a job record, one row per detected form, and a status on each. The post on how to [batch upload tax forms via API and track every page](/blog/batch-upload-tax-forms-via-api) covers the manifest that keeps those rows straight.

How the upload request itself is built, whether multipart form data or a URL to a stored file, is covered in the post on how to [upload a PDF to an API and get JSON back](/blog/upload-pdf-to-api-and-get-json). This post starts once the file is accepted.

## Verifying webhook signatures from a document processing API

Verifying a webhook signature proves the request came from the document processing API and was not changed on the way. The sender computes a keyed hash of the message with a secret you both hold, and your handler computes the same hash and compares. A request that fails the comparison is rejected before any of its data is read.

The keyed hash is usually HMAC. [RFC 2104, which defines HMAC](https://www.rfc-editor.org/rfc/rfc2104), describes it as "a mechanism for message authentication using cryptographic hash functions." The secret never travels with the request, so someone who sees the traffic cannot produce a valid signature for a forged event.

Providers differ in the details, so read whatever your provider documents. The [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md) is a useful reference because it spells out one complete scheme. It sends three headers, `webhook-id`, `webhook-timestamp` and `webhook-signature`, and signs the string `msg_id.timestamp.payload` with HMAC-SHA256, encoded in base64.

Three habits matter more than the exact header names.

### Sign the raw body

Compute the hash over the exact bytes you received. If your framework parses the JSON and you re-serialize it, key order or spacing can change and the hash will not match. Capture the raw body before any parsing step.

### Compare in constant time

The Standard Webhooks specification says to "use a constant time comparison function" when checking the signature, because an ordinary string compare can leak timing information. Most languages ship one in their crypto library.

### Check the timestamp

A valid signature on an old message is still a valid signature. Including the timestamp in the signed string, and rejecting messages whose timestamp is too far from your clock, closes the window for replaying a captured request. The specification asks for an "allowable tolerance" without naming a number, so pick one that covers ordinary clock drift and document it.

Keep the signing secret out of source control, and support two secrets at once during rotation. The Standard Webhooks signature header is a space-delimited list for that reason, so an old and a new signature can both be present while you switch.

## Idempotent file upload API calls and duplicate webhooks

An idempotent file upload API call is one you can safely send twice and still get one job. Retries happen: a mobile connection drops after the server received the file, or your worker restarts mid-request. Without protection, each retry creates a second job, a second bill per page and a second set of results to reconcile.

The common fix is an idempotency key. Your client generates a unique value per logical upload and sends it as a header. If the server has seen that key before, it returns the earlier result instead of starting new work. The IETF Internet-Draft [The Idempotency-Key HTTP Header Field](https://www.ietf.org/archive/id/draft-ietf-httpapi-idempotency-key-header-07.html) describes this pattern. It is an expired draft, not a finished standard.

That draft recommends "a UUID or a similar random identifier" as the key. It also suggests status codes for the awkward cases: 422 when the same key arrives with a different payload, 409 when a retry arrives while the original is still running, and 400 when a required key is missing. Whether a given service follows those codes is up to the service.

Generate the key once, when the user picks the file, and store it with your own record. A key generated on each attempt defeats the purpose. A key derived from a hash of the file bytes is another option, and it also catches a user who uploads the same W-2 twice.

Duplicate webhooks are the mirror image. A sender that retries will sometimes deliver the same event twice, for example when your success response was lost on the way back. The Standard Webhooks specification says to "use the `webhook-id` header as an idempotency key" on the receiving side. Record each event ID you have processed, and skip any ID you have seen.

Store the processed IDs somewhere durable, such as a unique column in your database. An in-memory set forgets everything on restart, and a restart is exactly when duplicates tend to arrive. A unique constraint also handles the race where two copies of one event land at the same moment on two servers.

## What if an async document processing webhook never arrives?

An async document processing webhook can fail to arrive because your endpoint was down, a firewall rule changed or the sender gave up after its retries. Treat webhooks as the fast path and polling as the safety net. A scheduled job that asks the API for the status of old, unfinished jobs catches every event the webhook missed.

Senders usually retry for a while before giving up. The Standard Webhooks specification suggests a schedule that spans multiple days with exponential backoff and jitter. Its example runs from an immediate attempt through retries at 5 seconds, 5 minutes, 30 minutes and then hours apart. A short outage on your side is often covered, but a long one or a misconfigured URL is not.

A reconciliation job closes the gap. Every so often, select jobs in your database that are still marked as processing and are older than you would expect. For each one, call the API's status endpoint, if it has one, and apply the result as if the webhook had arrived. The same handler logic should run in both paths so the outcome is identical.

Set the age cut-off from what you observe, not a guess. Log how long jobs take from submit to webhook, and poll for anything well past the slow end of that range. If jobs never finish at all, mark them failed after a ceiling and show the user a way to resubmit.

Polling alone is a valid design for low volume. A script that uploads a few files and checks every minute is simpler than running a public endpoint. The cost is delay and wasted calls, which is why most production systems use webhooks first and keep polling as the fallback.

## Async document processing webhook mistakes: slow handlers and lost events

The most common async document processing webhook mistake is doing the real work inside the handler. Parsing the result, writing dozens of fields, calling other services and emailing the user can take long enough that the sender times out and retries. The retry then runs the same work again, and duplicates follow.

The fix is to split acknowledge from process. The handler checks the signature, records the event ID, puts the event on a queue and returns a 2xx response. A separate worker reads the queue and does the slow work at its own pace. The Standard Webhooks specification suggests senders allow 15 to 30 seconds per request, and a handler that only enqueues finishes far inside that.

### A webhook handler checklist

- Read the raw request body before any parsing.
- Verify the signature with a constant-time compare, and reject failures with a 4xx response.
- Check the timestamp against your tolerance.
- Insert the event ID into a table with a unique constraint; if it already exists, return 2xx and stop.
- Put the event on a durable queue.
- Return 2xx.
- In the worker, fetch the full result by job ID if the event carries only a summary.
- Log the job ID, event ID and outcome on every step.

### An illustrative handler

The handler below is pseudocode, not code for any real service. Schema Tax has not published API documentation, so the header names, the event fields and the address `https://api.example.com` are placeholders chosen to show the four steps.

```text
on POST /webhooks/extraction:
  raw  = request.raw_body
  id   = header("webhook-id")
  ts   = header("webhook-timestamp")
  sig  = header("webhook-signature")

  # 1. verify
  expected = base64(hmac_sha256(SECRET, id + "." + ts + "." + raw))
  # the header may hold several space-separated "v1,<sig>" entries
  matched = false
  for entry in split(sig, " "):
      if constant_time_equal(expected, strip_prefix(entry, "v1,")):
          matched = true
  if not matched:
      return 401
  if abs(now() - ts) > TOLERANCE:
      return 401

  # 2. dedupe
  if not insert_unique("processed_events", id):
      return 200

  # 3. enqueue
  queue.push({ event_id: id, body: raw })

  # 4. acknowledge
  return 200

worker:
  event  = queue.pop()
  job_id = parse(event.body).job_id
  result = GET https://api.example.com/v1/jobs/{job_id}
  save_fields(job_id, result.forms)
```

Lost events are the other failure. If the handler returns 2xx before the event is safely on the queue, a crash in between loses it. Enqueue first, acknowledge second. If your queue is down, return a 5xx so the sender retries later.

Testing deserves its own pass. Send the same signed event twice and confirm one result. Send one with a changed body and confirm a rejection. Stop your worker, send events, start it again, and confirm nothing was dropped.

For a tax data pipeline, the payoff is that every form lands once, with its fields intact. Schema Tax offers API access by request; it takes a file and returns typed JSON billed per page, and it has published no documentation on whether results arrive by webhook or in the response. The [five steps from upload to export on the homepage](/#how) show where results come from. If you are building the screens around this flow, the post on [tax document upload for fintech apps](/blog/tax-document-upload-for-fintech-apps) walks through status and review from the user's side. Firms that process client packets without writing code can start with the [tax preparers category](/blog/category/tax-preparers).
