# Common patterns: Production patterns

## Table of Contents

- [Choose the right endpoint](#choose-the-right-endpoint)
- [Handle rate limits gracefully](#handle-rate-limits-gracefully)
- [Use stale-while-revalidate by default PRO](#use-stale-while-revalidate-by-default-pro)
  - [CLI Microlink API example](#cli-microlink-api-example)
  - [cURL Microlink API example](#curl-microlink-api-example)
  - [JavaScript Microlink API example](#javascript-microlink-api-example)
  - [Python Microlink API example](#python-microlink-api-example)
  - [Ruby Microlink API example](#ruby-microlink-api-example)
  - [PHP Microlink API example](#php-microlink-api-example)
  - [Golang Microlink API example](#golang-microlink-api-example)
- [Protect credentials in client-side code](#protect-credentials-in-client-side-code)
- [Use meta: false when you do not need metadata](#use-meta-false-when-you-do-not-need-metadata)
  - [CLI Microlink API example](#cli-microlink-api-example-1)
  - [cURL Microlink API example](#curl-microlink-api-example-1)
  - [JavaScript Microlink API example](#javascript-microlink-api-example-1)
  - [Python Microlink API example](#python-microlink-api-example-1)
  - [Ruby Microlink API example](#ruby-microlink-api-example-1)
  - [PHP Microlink API example](#php-microlink-api-example-1)
  - [Golang Microlink API example](#golang-microlink-api-example-1)
- [Retry with exponential backoff](#retry-with-exponential-backoff)
  - [CLI Microlink API example](#cli-microlink-api-example-2)
  - [cURL Microlink API example](#curl-microlink-api-example-2)
  - [JavaScript Microlink API example](#javascript-microlink-api-example-2)
  - [Python Microlink API example](#python-microlink-api-example-2)
  - [Ruby Microlink API example](#ruby-microlink-api-example-2)
  - [PHP Microlink API example](#php-microlink-api-example-2)
  - [Golang Microlink API example](#golang-microlink-api-example-2)
- [Monitor response headers](#monitor-response-headers)
- [Compress responses](#compress-responses)
- [See also](#see-also)

---

These patterns apply once you move from prototyping to a production integration. They cover the decisions most teams encounter after the first few hundred requests.

## Choose the right endpoint

| Stage                           | Endpoint           | Auth               |
| ------------------------------- | ------------------ | ------------------ |
| Local development / prototyping | `api.microlink.io` | None needed        |
| Staging / CI                    | `pro.microlink.io` | `x-api-key` header |
| Production                      | `pro.microlink.io` | `x-api-key` header |

The free endpoint has a soft limit of **5 requests per day**. With an API key the quota is your plan's, **25 requests per day** on the free key. Both run up to **2 concurrent requests**: per IP address without a key, per key with one. Sending `x-api-key` to the free endpoint fails with `EPRO`.

See the [endpoint docs](https://microlink.io/docs/api/basics/endpoint) and [authentication docs](https://microlink.io/docs/api/basics/authentication).

## Handle rate limits gracefully

When you hit your quota, Microlink returns **HTTP 429** with error code `ERATE`. Your integration should:

1.  Check `x-rate-limit-remaining` on every response.
2.  When the value approaches zero, slow down or queue requests.
3.  On a 429 response, wait until `x-rate-limit-reset` (UTC epoch seconds) before retrying.
4.  Without a key or on the free key, a 429 with error code `ECONCURRENCY` means you went over 2 concurrent requests: wait a second and retry.

```js
const{status,data,headers}=response

if(status===429){

constthrottled=data.code==='ECONCURRENCY'

constresetAt=Number(headers['x-rate-limit-reset'])*1000

constwaitMs=throttled?1000:Math.max(0,resetAt-Date.now())

awaitnewPromise(resolve=>setTimeout(resolve,waitMs))

}
```

The free endpoint and the free key reset daily. Paid plans reset monthly. See the [rate limit docs](https://microlink.io/docs/api/basics/rate-limit).

## Use stale-while-revalidate by default PRO

For most production workflows, the best cache setup is:

The following examples show how to use the Microlink API with CLI, cURL, JavaScript, Python, Ruby, PHP & Golang, targeting 'https://example.com' URL with 'ttl', 'staleTtl' & 'apiKey' API parameters:

### CLI Microlink API example

```bash
microlink https://example.com&ttl=1d&staleTtl=0 --api-key YOUR_API_TOKEN
```

### cURL Microlink API example

```bash
curl -G "https://pro.microlink.io" \
  -H "x-api-key: YOUR_API_TOKEN" \
  -d "url=https://example.com" \
  -d "ttl=1d" \
  -d "staleTtl=0"
```

### JavaScript Microlink API example

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

const microlink = createClient({ apiKey: "YOUR_API_TOKEN" })

const data = await microlink.metadata('https://example.com', {
  ttl: "1d",
  staleTtl: 0
})
```

### Python Microlink API example

```python
import requests

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

querystring = {
    "url": "https://example.com",
    "ttl": "1d",
    "staleTtl": "0"
}

headers = {
    "x-api-key": "YOUR_API_TOKEN"
}

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

print(response.json())
```

### Ruby Microlink API example

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

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

params = {
  url: "https://example.com",
  ttl: "1d",
  staleTtl: "0"
}

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)
request['x-api-key'] = "YOUR_API_TOKEN"
response = http.request(request)

puts response.body
```

### PHP Microlink API example

```php
<?php

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

$params = [
    "url" => "https://example.com",
    "ttl" => "1d",
    "staleTtl" => "0"
];

$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",
    CURLOPT_HTTPHEADER => [
        "x-api-key: YOUR_API_TOKEN"
    ]
]);

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

curl_close($curl);

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

### Golang Microlink API example

```
package main

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

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

    u, err := url.Parse(baseURL)
    if err != nil {
        panic(err)
    }
    q := u.Query()
    q.Set("url", "https://example.com")
    q.Set("ttl", "1d")
    q.Set("staleTtl", "0")
    u.RawQuery = q.Encode()

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

    req.Header.Set("x-api-key", "YOUR_API_TOKEN")

    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
importcreateClientfrom'microlink.io'

constmicrolink=createClient({apiKey:"YOUR_API_TOKEN"})

constdata=awaitmicrolink.metadata('https://example.com',{

ttl:"1d",

staleTtl:0

})
```

Serve the cached response instantly, refresh in the background. This maximizes cache hits and minimizes user-facing latency.

Adjust `ttl` based on how often the target content changes. See [caching patterns](https://microlink.io/docs/guides/common/caching) for the full strategy.

## Protect credentials in client-side code

If you consume Microlink from a frontend (website, SPA, mobile app):

1.  **Never embed your API key** in client-side code, HTML attributes, or public embed URLs.
2.  **Use a proxy** to keep the key on your server:
    - [@microlink/proxy](https://github.com/microlinkhq/proxy) — self-hosted Node.js proxy.
    - [@microlink/edge-proxy](https://github.com/microlinkhq/edge-proxy) — edge-deployed (Cloudflare Workers, Vercel Edge).
3.  **Restrict allowed domains** in your proxy configuration so only your own sites can consume your quota.

See the [authentication docs](https://microlink.io/docs/api/basics/authentication) and [private pages patterns](https://microlink.io/docs/guides/common/private-pages).

## Use meta: false when you do not need metadata

Many workflows only need one output (a screenshot, a PDF, or custom extracted fields). Adding `meta: false` skips the normalized metadata step, which is usually the single biggest speedup:

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

### CLI Microlink API example

```bash
microlink https://example.com&screenshot
```

### cURL Microlink API example

```bash
curl -G "https://api.microlink.io" \
  -d "url=https://example.com" \
  -d "screenshot=true" \
  -d "meta=false"
```

### JavaScript Microlink API example

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

const microlink = createClient()

const data = await microlink.screenshot('https://example.com')
```

### Python Microlink API example

```python
import requests

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

querystring = {
    "url": "https://example.com",
    "screenshot": "true",
    "meta": "false"
}

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://example.com",
  screenshot: "true",
  meta: "false"
}

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://example.com",
    "screenshot" => "true",
    "meta" => "false"
];

$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

```
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://example.com")
    q.Set("screenshot", "true")
    q.Set("meta", "false")
    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
importcreateClientfrom'microlink.io'

constmicrolink=createClient()

constdata=awaitmicrolink.screenshot('https://example.com')
```

The `x-fetch-mode` response header will show `'skipped'` when metadata detection is bypassed.

## Retry with exponential backoff

Transient errors happen. The API supports a `retry` parameter that performs server-side retries with exponential backoff:

The following examples show how to use the Microlink API with CLI, cURL, JavaScript, Python, Ruby, PHP & Golang, targeting 'https://example.com' URL with 'retry' API parameter:

### CLI Microlink API example

```bash
microlink https://example.com&retry=3
```

### cURL Microlink API example

```bash
curl -G "https://api.microlink.io" \
  -d "url=https://example.com" \
  -d "retry=3"
```

### JavaScript Microlink API example

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

const microlink = createClient()

const data = await microlink.metadata('https://example.com', {
  retry: 3
})
```

### Python Microlink API example

```python
import requests

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

querystring = {
    "url": "https://example.com",
    "retry": "3"
}

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://example.com",
  retry: "3"
}

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://example.com",
    "retry" => "3"
];

$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

```
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://example.com")
    q.Set("retry", "3")
    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
importcreateClientfrom'microlink.io'

constmicrolink=createClient()

constdata=awaitmicrolink.metadata('https://example.com',{

retry:3

})
```

The default value is 2. Increase to 3 for targets that occasionally fail.

For client-side retries, respect the same backoff pattern and avoid retrying on 4xx errors that indicate a configuration problem (like `EINVALURL` or `EAUTH`).

## Monitor response headers

Build observability into your integration by logging these headers:

| Header                   | Why it matters                                                          |
| ------------------------ | ----------------------------------------------------------------------- |
| `x-cache-status`         | Tracks cache hit rate — low hit rates mean wasted work                  |
| `x-response-time`        | Tracks p50/p95 latency — spikes signal a target-site or rendering issue |
| `x-pricing-plan`         | Confirms requests hit the right endpoint                                |
| `x-fetch-mode`           | Shows whether requests used fetch, prerender, or proxy                  |
| `x-rate-limit-remaining` | Enables proactive throttling before you hit the limit                   |

## Compress responses

If you call the API directly (not through the SDK), set the `Accept-Encoding` header to `br` or `gzip`:

```bash
curl-H'Accept-Encoding: br''https://api.microlink.io?url=https://example.com'
```

The SDK enables compression by default. See the [compression docs](https://microlink.io/docs/api/basics/compression).

## See also

- [Screenshots under traffic spikes](https://microlink.io/use-cases/website-screenshot/traffic-spikes) — a production recipe for bursty screenshot workloads.
- [PDFs in bulk](https://microlink.io/use-cases/website-to-pdf/batch-generation) — a production recipe for batch document generation.