> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getbifrost.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Async Jobs

> Charge an API that runs work in the background once per job, when it finishes, instead of on every status check.

Some APIs do not answer with the result. They start a **job**, hand back its id, and the caller asks for the status until the job is done. AWS Textract works this way: `StartDocumentAnalysis` returns a `JobId`, and `GetDocumentAnalysis` reports the status and, once it is done, the pages.

Priced as ordinary calls, such an API is charged on every status check, and the price of the work (the pages) is only known at the end. An **async job** on a route fixes both:

1. The call that starts the job is charged as usual, with the route's fee.
2. Bifrost reads the job id from the reply and checks the job itself, with the relay's credential, until it reports a final status.
3. When the job succeeds, Bifrost prices that final reply (for example, pages times a price per page) and charges it **once** to the budgets the start call was charged to.
4. The caller's own status checks cost nothing: Bifrost recognizes a call that matches the job's status check and relays it free, whatever route it reaches.

## Set up a job

> [tab] Web UI
>
> 1. Open **Relays**, select the relay and select **Add Async Job** above its routes.
> 2. Under **Start Route (Charged)**, set the call that starts the job: method `POST`, path `/` and the header matcher `X-Amz-Target` = `Textract.StartDocumentAnalysis`. Set **Fee per Start (USD)** to `0.01` and **Job ID Path** to `JobId`.
> 3. Under **Status Check (Free)**, set how Bifrost checks the job: method `POST`, path `/`, the header `X-Amz-Target` = `Textract.GetDocumentAnalysis`, the body `{"JobId":"{{job.id}}","MaxResults":1}` with content type `application/x-amz-json-1.1`, **Status Path** `JobStatus`, **Succeeded Statuses** `SUCCEEDED, PARTIAL_SUCCESS` and **Failed Statuses** `FAILED`.
> 4. Under **Job Pricing**, set **Price per Unit (USD)** to `0.0015`, **Units Read From** to the response, **Measure** to **Number at path** and **Units Path** to `DocumentMetadata.Pages`.
> 5. Select **Add Async Job**.
>
> The job shows in the routes table on its start route. Editing that route opens the async job again.

> [tab] config.json
>
> This Textract relay charges $0.01 to start an analysis and $0.0015 per page when it finishes. Status checks are free.
>
> ```json theme={null}
> {
>   "relays": [
>     {
>       "name": "textract",
>       "base_url": "https://textract.us-east-1.amazonaws.com",
>       "auth": { "type": "aws_sigv4", "aws": { "service": "textract" } },
>       "credential": { "aws": { "region": "us-east-1", "access_key": "env.AWS_ACCESS_KEY_ID", "secret_key": "env.AWS_SECRET_ACCESS_KEY" } },
>       "routes": [
>         {
>           "method": "POST",
>           "path": "/",
>           "headers": { "X-Amz-Target": "Textract.StartDocumentAnalysis" },
>           "usage": { "cost_per_request": 0.01 },
>           "job": {
>             "id_path": "JobId",
>             "poll": {
>               "method": "POST",
>               "path": "/",
>               "headers": { "X-Amz-Target": "Textract.GetDocumentAnalysis" },
>               "body": "{\"JobId\":\"{{job.id}}\",\"MaxResults\":1}",
>               "content_type": "application/x-amz-json-1.1"
>             },
>             "status_path": "JobStatus",
>             "succeeded": ["SUCCEEDED", "PARTIAL_SUCCESS"],
>             "failed": ["FAILED"],
>             "interval_seconds": 30,
>             "timeout_seconds": 21600,
>             "usage": { "units_path": "DocumentMetadata.Pages", "cost_per_unit": 0.0015 }
>           }
>         },
>         {
>           "method": "POST",
>           "path": "/",
>           "headers": { "X-Amz-Target": "Textract.Get*" },
>           "billable": false
>         }
>       ]
>     }
>   ]
> }
> ```

> [tab] Helm
>
> The same relay under `bifrost.relays`:
>
> ```yaml theme={null}
> bifrost:
>   relays:
>     - name: textract
>       base_url: "https://textract.us-east-1.amazonaws.com"
>       auth:
>         type: aws_sigv4
>         aws:
>           service: textract
>       credential:
>         aws:
>           region: us-east-1
>           access_key: "env.AWS_ACCESS_KEY_ID"
>           secret_key: "env.AWS_SECRET_ACCESS_KEY"
>       routes:
>         - method: POST
>           path: /
>           headers:
>             X-Amz-Target: "Textract.StartDocumentAnalysis"
>           usage:
>             cost_per_request: 0.01
>           job:
>             id_path: JobId
>             poll:
>               method: POST
>               path: /
>               headers:
>                 X-Amz-Target: Textract.GetDocumentAnalysis
>               body: '{"JobId":"{{job.id}}","MaxResults":1}'
>               content_type: application/x-amz-json-1.1
>             status_path: JobStatus
>             succeeded: [SUCCEEDED, PARTIAL_SUCCESS]
>             failed: [FAILED]
>             interval_seconds: 30
>             timeout_seconds: 21600
>             usage:
>               units_path: DocumentMetadata.Pages
>               cost_per_unit: 0.0015
>         - method: POST
>           path: /
>           headers:
>             X-Amz-Target: "Textract.Get*"
>           billable: false
> ```

`MaxResults: 1` keeps each check small: Textract still reports `JobStatus` and `DocumentMetadata.Pages`, without the full results.

The start route names one operation because each start has its own status call: `StartDocumentAnalysis` is checked with `GetDocumentAnalysis`, while `StartDocumentTextDetection` needs `GetDocumentTextDetection`. To charge text detection jobs too, add a second start route for `Textract.StartDocumentTextDetection` with its own `job.poll`.

## Fields

| Field | Required | What it does |
| - | - | - |
| `id_path` | Yes | Where the job id is in the start call's reply, such as `JobId`. |
| `poll.method` | No | Method of the status check. Default `POST`. |
| `poll.path` | Yes | Path of the status check below the base URL. `{{job.id}}` is replaced with the job id, as in `/jobs/{{job.id}}`. `{{job.id}}` must appear in the path, a header or the body. A query parameter that carries a credential is refused. |
| `poll.headers` | No | Headers of the status check. Values may contain `{{job.id}}`. Headers that carry a credential are refused: the relay adds its own. |
| `poll.body` | No | Body of the status check. `{{job.id}}` is replaced, escaped for the body's type: JSON, form-encoded or XML. |
| `poll.content_type` | No | Content type of the body. Default `application/json`. |
| `status_path` | Yes | Where the status is in the status check's reply, such as `JobStatus`. |
| `succeeded` | Yes | Statuses that end the job and charge it. Letter case is ignored. |
| `failed` | No | Statuses that end the job without a charge. |
| `interval_seconds` | No | Seconds between checks. Default `30`, and no longer than the timeout. Bifrost looks for due jobs every 10 seconds, and checks less often after many attempts. |
| `timeout_seconds` | No | Stop checking after this long. Default `3600`, at most 7 days. The job is checked once more at the deadline. |
| `reused_id_is_new_job` | No | `true` when the API can hand back an id it already used for new work, such as a job id the caller picks. Then a start that returns the id of a job already charged starts a new job. Default `false`: such a start is a retry and is not charged again. |
| `usage` | No | How the final reply is priced, over the route's and the relay's [pricing](https://docs.getbifrost.ai/relays/pricing.md). Only a `cost_per_request` set here is charged again: the route's fee was charged when the job started. |

A route that starts a job must be billable and is never streamed, because Bifrost reads the job id from its reply.

## What is charged

| The job | Charged |
| - | - |
| Started | The start route's fee, like any call. |
| Reports a `succeeded` status | Its final reply priced with the job's `usage`, once. |
| Reports a `failed` status | Nothing more. |
| Succeeds, but its reply lacks what `usage` reads (units, `cost_path`, or tokens when the job reads neither) | Nothing more. Check the paths in `usage`. Token paths inherited from the relay do not count against a job priced by units or a cost path. |
| Still running at its last check, after `timeout_seconds` | Nothing more. |
| A check fails: unknown to the API (`404`), the credential is refused (`401`, `403`), another `4xx`, throttling or `5xx` | Nothing yet. Bifrost tries again until `timeout_seconds`, since these are often temporary (a job not visible yet, a key being rotated). If the last check still fails, nothing more. |

A caller that retries a start and gets the same job id back (Textract does this for a repeated `ClientRequestToken`) pays the start fee again, but the job is charged only once, also when the retry comes after the job finished. Set `reused_id_is_new_job` only for an API that reuses ids for new work.

> [!NOTE]
>
> If a gateway node charges a budget and then cannot save that it did, another node can count that one job against the budget a second time. The job's row in the Relay Logs is still written once.

The final charge goes to the budgets of the virtual key, team and customer that started the job, even if they changed since. It counts no extra request against rate limits.

## In Relay Logs

The start call is a row like any other, with its job id and the status `started`. When the job ends, a **job** row is added with the final status, the units and the charge. It links to the start call's row and carries that call's model, route and the names of its virtual key, user, team and project. A job Bifrost could not price still gets its row, with the reason and a blank cost, and nothing is charged.

The job row also shows how the job was followed: how many status checks Bifrost sent (a sweep that skips the job because another node is settling it sends nothing, so it does not count), the last job status it read, the HTTP status of the check that ended it, and when it was settled. The replies to those checks are not stored.

A caller's own status check can settle the job too: when its reply shows the job finished, Bifrost charges the job from that reply at once, as it does for a video retrieve, and the job row names that check. Bifrost's own polling stays the backstop, and a job is still charged once whichever check finds it finished first.

> [!NOTE]
>
> Jobs are recorded by request logging. With logging off, the start call is still charged its fee, but no job is followed or charged.

## Job ids Bifrost will not follow

The job id comes from the API's reply and goes into the status check's path. To keep it from reaching another path on the API with the relay's credential, Bifrost only follows an id of printable characters with no spaces, `\`, `?`, `#`, `.` or `..` path segments (also with `;params` after them, as in `..;x`), at most 160 bytes. A reply with any other id is charged as an ordinary call and the job is not followed.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.