# Automatic retries

> Let VirginProxy try a request again when the target answers with a temporary error or the connection fails. Only the answer you receive is charged.

Source: https://docs.virginproxy.com/retries/

Websites sometimes answer with a temporary error: a 429 or 503, a timeout, or a connection that breaks off. With `retry` we try again before we answer you and you get the first good answer.

## Example

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://www.example.com/",
    "retry": {
      "times": 2,
      "on": [
        403,
        429,
        503,
        "timeout"
      ],
      "fresh_ip": true
    }
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://www.example.com/",
        "retry": {"times": 2, "on": [403, 429, 503, "timeout"], "fresh_ip": True},
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["status"], data["attempts"], data["cost"]["credits"])
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://www.example.com/",
    retry: { times: 2, on: [403, 429, 503, "timeout"], fresh_ip: true },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
console.log(data.status, data.attempts, data.cost.credits);
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://www.example.com/",
    "retry": {"times": 2, "on": [403, 429, 503, "timeout"], "fresh_ip": True},
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://www.example.com/",
  retry: { times: 2, on: [403, 429, 503, "timeout"], fresh_ip: true },
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://www.example.com/",
        "retry" => [
            "times" => 2,
            "on" => [403, 429, 503, "timeout"],
            "fresh_ip" => true,
        ],
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo $data["status"], " ", $data["attempts"], " ", $data["cost"]["credits"], PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://www.example.com/",
  "retry": {
    "times": 2,
    "on": [
      403,
      429,
      503,
      "timeout"
    ],
    "fresh_ip": true
  }
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["status"], data["attempts"], data["cost"].(map[string]any)["credits"])
}
```

POST`/v1/requests`[≈ 1+ credits](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL3d3dy5leGFtcGxlLmNvbS8iLCJyZXRyeSI6eyJ0aW1lcyI6Miwib24iOls0MDMsNDI5LDUwMywidGltZW91dCJdLCJmcmVzaF9pcCI6dHJ1ZX19)

`attempts` in the response tells you how many tries it took.

## Fields

| Field | Type | Meaning |
| --- | --- | --- |
| `times` | integer | How many more attempts at most: 0 to 3. Default 1. |
| `on` | list | When to try again: target statuses from 300 to 599 (as numbers or strings), the errors `timeout`, `connection_failed`, `target_unreachable` and `tls_error`, and `text_match` and `selector_missing` (see [Retry by content](#content)). At most 20 entries. Default `[403, 429, 503, "timeout", "connection_failed"]`. |
| `fresh_ip` | boolean | `true` gets a new IP before each further attempt. Default `false`: the next attempt uses the same IP. |

`"retry": {}` uses all defaults: one more attempt on the same IP.

## Retry by content

Some temporary errors arrive as a normal 200: an empty result list or a "please try again" text. Two more fields catch them:

| Field | Type | Meaning |
| --- | --- | --- |
| `if_text` | list | Up to 10 texts of up to 200 characters. If the body contains one of them (case does not matter), the attempt counts as refused. |
| `if_missing` | string | A CSS selector. If an HTML answer contains no matching element, the attempt counts as refused – for example when the product price is missing. |

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://shop.example/product/42",
    "retry": {
      "times": 3,
      "fresh_ip": true,
      "if_text": [
        "please try again",
        "temporarily unavailable"
      ],
      "if_missing": ".price"
    }
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://shop.example/product/42",
        "retry": {
            "times": 3,
            "fresh_ip": True,
            "if_text": ["please try again", "temporarily unavailable"],
            "if_missing": ".price",
        },
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["status"], data["attempts"], data["cost"]["credits"])
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://shop.example/product/42",
    retry: {
      times: 3,
      fresh_ip: true,
      if_text: ["please try again", "temporarily unavailable"],
      if_missing: ".price",
    },
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
console.log(data.status, data.attempts, data.cost.credits);
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://shop.example/product/42",
    "retry": {
        "times": 3,
        "fresh_ip": True,
        "if_text": ["please try again", "temporarily unavailable"],
        "if_missing": ".price",
    },
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://shop.example/product/42",
  retry: {
    times: 3,
    fresh_ip: true,
    if_text: ["please try again", "temporarily unavailable"],
    if_missing: ".price",
  },
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://shop.example/product/42",
        "retry" => [
            "times" => 3,
            "fresh_ip" => true,
            "if_text" => ["please try again", "temporarily unavailable"],
            "if_missing" => ".price",
        ],
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo $data["status"], " ", $data["attempts"], " ", $data["cost"]["credits"], PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://shop.example/product/42",
  "retry": {
    "times": 3,
    "fresh_ip": true,
    "if_text": [
      "please try again",
      "temporarily unavailable"
    ],
    "if_missing": ".price"
  }
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["status"], data["attempts"], data["cost"].(map[string]any)["credits"])
}
```

POST`/v1/requests`[≈ 1+ credits](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL3Nob3AuZXhhbXBsZS9wcm9kdWN0LzQyIiwicmV0cnkiOnsidGltZXMiOjMsImZyZXNoX2lwIjp0cnVlLCJpZl90ZXh0IjpbInBsZWFzZSB0cnkgYWdhaW4iLCJ0ZW1wb3JhcmlseSB1bmF2YWlsYWJsZSJdLCJpZl9taXNzaW5nIjoiLnByaWNlIn19)

Internally these count as the codes `text_match` and `selector_missing`: they are added to `on` automatically, and you may also list them there yourself. If the last attempt still matches, that answer comes back normally and is charged like any answered request – check it before you use it.

## What it costs

- Only the answer you receive is charged, by its size, as usual. Earlier attempts are on us.
- Each new IP adds 5 credits, as with `fresh_ip`.
- If every attempt fails with an error (timeout, broken connection), nothing is charged.
- If the last attempt still gets a refusal, for example a 403, that answer is charged like any answer.

Example: the first attempt gets a 429, the second, from a new IP, gets a 200 with 300 kB. You pay 1 + 5 = 6 credits.

## Same IP or a new one?

- For `timeout` and `connection_failed` the same IP is usually fine: the path to the target had a hiccup.
- For 429 and 503, wait or slow down: these are the target's own limits. Respect them and the site's terms.
- A `session` keeps its IP, so `retry.fresh_ip` cannot be combined with `session`. Retries on the same IP can.

## Time

Each attempt may take the full `timeout_ms`, and a new IP takes up to about 20 seconds more. Set your client's timeout to cover all attempts: timeout × (1 + `times`), plus the wait for a free slot (see [Load and priority](https://docs.virginproxy.com/priority/)), plus 30 seconds per new IP.

## What retry does not cover

`retry` is about the target. Our own answers, such as `rate_limited`, `concurrency_limited` or `busy`, come back to you at once and are not charged; handle them in your client as described in [Limits and retries](https://docs.virginproxy.com/limits/).

> **Warning:** Think twice before retrying a `POST`. A request that timed out may still have been carried out by the target.
