# Common patterns: Background requests

A request you wait for has to finish while the connection is open: 90 seconds on pro. With [detach](https://microlink.io/docs/api/parameters/detach), the API queues the request, answers at once, and runs it in the background with up to 5 minutes. You collect the result by sending the same request again.

## [When to use it](https://microlink.io/docs/guides/common/background-requests#when-to-use-it)

- **Slow pages.** A page that takes long to load or render, a long [pdf](https://microlink.io/docs/api/parameters/pdf), or an [animated screenshot](https://microlink.io/docs/api/parameters/screenshot/animated) of a heavy site.
- **Many URLs at once.** Thousands of requests sent together are queued and run as capacity frees up, instead of all competing for it and timing out. A request the API could not queue answers [EDETACHQUEUE](https://microlink.io/docs/api/basics/error-codes#edetachqueue), and is sent again like a pending one.
- **Jobs, not page views.** A worker that fills a database or warms a cache can wait for a result. A visitor looking at the page usually cannot, so keep those requests synchronous.

It does not give [function](https://microlink.io/docs/api/parameters/function) code more time: the code keeps its own limit. See [time budget](https://microlink.io/docs/api/parameters/detach#time-budget) for every limit that stays the same.

## [The polling loop](https://microlink.io/docs/guides/common/background-requests#the-polling-loop)

Send the request with `detach`. While it is waiting or running, the API answers `202` with `{ "status": "pending" }` and a `Retry-After` header (5 seconds). Send the same request again after that, and stop at the first answer that is final.

The following examples show how to use the Microlink API with CLI, cURL, JavaScript, Python, Ruby, PHP & Golang, targeting 'https://microlink.io' URL with 'screenshot' & 'detach' API parameters:

CLI Microlink API example

```bash
microlink screenshot https://microlink.io --detach
```

cURL Microlink API example

```bash
curl -G "https://api.microlink.io" \
  -d "url=https://microlink.io" \
  -d "screenshot=true" \
  -d "detach=true"
```

JavaScript Microlink API example

```javascript
import createClient from 'microlink.io'

const microlink = createClient()

const data = await microlink.screenshot('https://microlink.io', {
  detach: true
})
```

Python Microlink API example

```python
import requests

url = "https://api.microlink.io/"

querystring = {
    "url": "https://microlink.io",
    "screenshot": "true",
    "detach": "true"
}

response = requests.get(url, params=querystring)

print(response.json())
```

Ruby Microlink API example

```ruby
require 'uri'
require 'net/http'

base_url = "https://api.microlink.io/"

params = {
  url: "https://microlink.io",
  screenshot: "true",
  detach: "true"
}

uri = URI(base_url)
uri.query = URI.encode_www_form(params)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(uri)
response = http.request(request)

puts response.body
```

PHP Microlink API example

```php
<?php

$baseUrl = "https://api.microlink.io/";

$params = [
    "url" => "https://microlink.io",
    "screenshot" => "true",
    "detach" => "true"
];

$query = http_build_query($params);
$url = $baseUrl . '?' . $query;

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET"
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #: " . $err;
} else {
    echo $response;
}
```

Golang Microlink API example

```go
package main

import (
    "fmt"
    "net/http"
    "net/url"
    "io"
)

func main() {
    baseURL := "https://api.microlink.io"

    u, err := url.Parse(baseURL)
    if err != nil {
        panic(err)
    }
    q := u.Query()
    q.Set("url", "https://microlink.io")
    q.Set("screenshot", "true")
    q.Set("detach", "true")
    u.RawQuery = q.Encode()

    req, err := http.NewRequest("GET", u.String(), nil)
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(body))
}
```

```javascript
import createClient from 'microlink.io'

const microlink = createClient()

const data = await microlink.screenshot('https://microlink.io', {
  detach: true
})
```

Click to run the code and see the API response

Every repeat counts as a request, so a good loop does three things:

- it waits longer each time, up to 30 seconds, so a slow request does not cost a request every 5 seconds;
- it repeats on a `503` with the [EDETACHQUEUE](https://microlink.io/docs/api/basics/error-codes#edetachqueue) code too, because that request was not queued yet, and on a `429` with the [ECONCURRENCY](https://microlink.io/docs/api/basics/error-codes#econcurrency) code, because too many requests reached the API in the same second;
- it adds a random part, up to half, to each wait, so requests sent together do not all repeat in the same second;
- it gives up after a deadline of about an hour, because a request that keeps failing can take up to about 45 minutes to reach its final error. Giving up does not cancel it: the same request sent later picks up its answer.

[@microlink/mql](https://github.com/microlinkhq/mql) resolves a pending request with `status: 'pending'`, and throws on an error. Product methods on the [SDK](https://microlink.io/docs/sdk/getting-started/overview) unwrap `data`, and a pending response has none, so this loop calls `mql`:

```
import mql from '@microlink/mql'
import { setTimeout } from 'node:timers/promises'

const MAX_WAIT_MS = 30_000
const DEADLINE_MS = 60 * 60_000

const retryAfterMs = headers => (Number(headers['retry-after']) || 5) * 1000

const sendAgain = error =>
  error.code === 'EDETACHQUEUE' ||
  (error.code === 'ECONCURRENCY' && !error.data?.function)

const detached = async (url, opts) => {
  const deadline = Date.now() + DEADLINE_MS
  let wait = 0
  while (Date.now() < deadline) {
    let headers
    try {
      const result = await mql(url, { ...opts, detach: true })
      if (result.status !== 'pending') return result
      headers = Object.fromEntries(result.response.headers)
    } catch (error) {
      if (!sendAgain(error)) throw error
      headers = error.headers ?? {}
    }
    const grown = Math.max(retryAfterMs(headers), wait * 1.5)
    wait = Math.min(grown * (1 + Math.random() / 2), MAX_WAIT_MS)
    await setTimeout(wait)
  }
  throw new Error(`${url} was still pending after ${DEADLINE_MS / 60_000} minutes`)
}

const { data } = await detached('https://microlink.io', {
  apiKey: process.env.MICROLINK_API_KEY,
  screenshot: true
})

console.log(data.screenshot.url)
```

The same loop in a shell, with `curl`:

```
url='https://pro.microlink.io/?url=https%3A%2F%2Fmicrolink.io&screenshot&detach'
deadline=$(( $(date +%s) + 3600 ))
wait=0

while [ "$(date +%s)" -lt "$deadline" ]; do
  status=$(curl -s -o response.json -D headers.txt -w '%{http_code}' -H "x-api-key: $MICROLINK_API_KEY" "$url")
  case "$status" in
    202) ;;
    503) grep -q '"EDETACHQUEUE"' response.json || break ;;
    429) grep -q '"ECONCURRENCY"' response.json && ! grep -q '"function"' response.json || break ;;
    *) break ;;
  esac
  retry_after=$(awk 'tolower($1) == "retry-after:" { print $2 + 0 }' headers.txt)
  [ "${retry_after:-0}" -gt 0 ] || retry_after=5
  wait=$(( wait * 3 / 2 ))
  [ "$wait" -lt "$retry_after" ] && wait=$retry_after
  wait=$(( wait + RANDOM % (wait / 2 + 1) ))
  [ "$wait" -gt 30 ] && wait=30
  sleep "$wait"
done

case "$status" in
  200) echo "$status" ;;
  *) echo "$status"; exit 1 ;;
esac
```

Keep every repeat identical to the first request: the same parameters, `detach` included, the same [timeout](https://microlink.io/docs/api/parameters/timeout), and the same API key. On the free endpoint the request belongs to your IP address, so send every repeat from the same one. A request without `detach` that is not cached yet runs while you wait.

## [Handle the result](https://microlink.io/docs/guides/common/background-requests#handle-the-result)

The first answer that is not `202`, a `503` `EDETACHQUEUE` or a throttled `429` `ECONCURRENCY` ends the loop:

- `200` is the same response you would get without `detach`.
- A `429` [ERATE](https://microlink.io/docs/api/basics/error-codes#erate), `401` or `403` is about your key or quota, not the request. The request keeps running, and its answer waits for you.
- A `429` [ECONCURRENCY](https://microlink.io/docs/api/basics/error-codes#econcurrency) whose `data` names `function` is not a throttle: it is the error the request ended with, so the loop stops on it.
- Any other status is the error the request ended with, in the usual [error format](https://microlink.io/docs/api/basics/error-codes). `mql` throws, like any other failed request. Some errors carry their own `Retry-After`, such as [EUNREACHABLE](https://microlink.io/docs/api/basics/error-codes#eunreachable); the loop still stops there, because repeating the same request returns the same error.

A request that ends in a `408`, `424`, `429` or `5xx` status is tried up to 3 times in all before its error is kept. The answer, a result or an error, stays the answer to that request for 24 hours. To run it again sooner, change its [timeout](https://microlink.io/docs/api/parameters/timeout) or, on pro, its [cacheKey](https://microlink.io/docs/api/parameters/cacheKey).

`mql` retries some answers twice on its own before it throws (`408`, `413`, `500`, `502`, `503`, `504`, `521`, `522` and `524`), and each retry counts as a request.

## [Process many URLs](https://microlink.io/docs/guides/common/background-requests#process-many-urls)

Run one loop per URL with a concurrency limit, and keep the errors next to the results instead of letting the first one stop the batch. With [p-map](https://github.com/sindresorhus/p-map):

```
import pMap from 'p-map'

const urls = ['https://microlink.io', 'https://github.com', 'https://vercel.com']
const opts = { apiKey: process.env.MICROLINK_API_KEY, screenshot: true }

const results = await pMap(
  urls,
  url => detached(url, opts).then(
    ({ data }) => ({ url, data }),
    error => ({ url, error })
  ),
  { concurrency: 50 }
)
```

Each loop repeats only its own request, so a slow URL does not hold back the others. The limit is for your process and your quota: the API answers a pending request at once, whatever its queue looks like. Requests sent together become pending together, so without the random part of the wait their repeats would all arrive in the same second, and some would answer `429` [ECONCURRENCY](https://microlink.io/docs/api/basics/error-codes#econcurrency). The loop sends those again.

## [Keep the cost down](https://microlink.io/docs/guides/common/background-requests#keep-the-cost-down)

- Back off between repeats, as the loops above do. A request that takes 2 minutes costs about 25 requests when it is repeated every 5 seconds, and about 8 with the backoff.
- Send work you know is fast without `detach`: one request, no repeats.
- Use an [API key](https://microlink.io/docs/api/basics/authentication). On the free endpoint, each repeat takes one of the requests of the day.

A successful result is also [cached](https://microlink.io/docs/api/basics/cache) like any other response, so once a URL is done, the same request with or without `detach` is served from the cache.

## [See also](https://microlink.io/docs/guides/common/background-requests#see-also)

- [detach](https://microlink.io/docs/api/parameters/detach): the parameter reference.
- [Production patterns](https://microlink.io/docs/guides/common/production-patterns): rate limits, endpoints and credentials.
- [Caching patterns](https://microlink.io/docs/guides/common/caching): how long results are kept and served.
