Automatic 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 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
}
}'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"])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);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)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
$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;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"])
}require "json"
require "net/http"
uri = URI("https://api.virginproxy.com/v1/requests")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer " + ENV.fetch("VP_KEY")
req["Content-Type"] = "application/json"
req.body = JSON.generate({
"url" => "https://www.example.com/",
"retry" => {
"times" => 2,
"on" => [403, 429, 503, "timeout"],
"fresh_ip" => true,
},
})
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 180) { |http| http.request(req) }
data = JSON.parse(res.body)
abort(data["error"]["code"] + ": " + data["error"]["message"]) unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(data)import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
String payload = """
{
"url": "https://www.example.com/",
"retry": {
"times": 2,
"on": [
403,
429,
503,
"timeout"
],
"fresh_ip": true
}
}
""";
HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.virginproxy.com/v1/requests"))
.header("Authorization", "Bearer " + System.getenv("VP_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(180))
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() >= 300) {
System.err.println(res.statusCode() + " " + res.body()); // the error object: code, message
System.exit(1);
}
System.out.println(res.body()); // JSON: read it with the JSON library of your choice
}
}using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(180) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VP_KEY"));
var payload = """
{
"url": "https://www.example.com/",
"retry": {
"times": 2,
"on": [
403,
429,
503,
"timeout"
],
"fresh_ip": true
}
}
""";
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.virginproxy.com/v1/requests");
req.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var res = await http.SendAsync(req);
using var data = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
if (!res.IsSuccessStatusCode)
{
var e = data.RootElement.GetProperty("error");
Console.Error.WriteLine(e.GetProperty("code") + ": " + e.GetProperty("message"));
Environment.Exit(1);
}
Console.WriteLine(data.RootElement);/v1/requests≈ 1+ creditsOpen in Playgroundattempts 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). 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 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"
}
}'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"])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);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)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
$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;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"])
}require "json"
require "net/http"
uri = URI("https://api.virginproxy.com/v1/requests")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer " + ENV.fetch("VP_KEY")
req["Content-Type"] = "application/json"
req.body = JSON.generate({
"url" => "https://shop.example/product/42",
"retry" => {
"times" => 3,
"fresh_ip" => true,
"if_text" => ["please try again", "temporarily unavailable"],
"if_missing" => ".price",
},
})
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 180) { |http| http.request(req) }
data = JSON.parse(res.body)
abort(data["error"]["code"] + ": " + data["error"]["message"]) unless res.is_a?(Net::HTTPSuccess)
puts [data["status"], data["attempts"], data["cost"]["credits"]].join(" ")import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
String payload = """
{
"url": "https://shop.example/product/42",
"retry": {
"times": 3,
"fresh_ip": true,
"if_text": [
"please try again",
"temporarily unavailable"
],
"if_missing": ".price"
}
}
""";
HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.virginproxy.com/v1/requests"))
.header("Authorization", "Bearer " + System.getenv("VP_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(180))
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() >= 300) {
System.err.println(res.statusCode() + " " + res.body()); // the error object: code, message
System.exit(1);
}
System.out.println(res.body()); // JSON: read it with the JSON library of your choice
}
}using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(180) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VP_KEY"));
var payload = """
{
"url": "https://shop.example/product/42",
"retry": {
"times": 3,
"fresh_ip": true,
"if_text": [
"please try again",
"temporarily unavailable"
],
"if_missing": ".price"
}
}
""";
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.virginproxy.com/v1/requests");
req.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var res = await http.SendAsync(req);
using var data = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
if (!res.IsSuccessStatusCode)
{
var e = data.RootElement.GetProperty("error");
Console.Error.WriteLine(e.GetProperty("code") + ": " + e.GetProperty("message"));
Environment.Exit(1);
}
Console.WriteLine(data.RootElement.GetProperty("status") + " " + data.RootElement.GetProperty("attempts") + " " + data.RootElement.GetProperty("cost").GetProperty("credits"));/v1/requests≈ 1+ creditsOpen in PlaygroundInternally 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
timeoutandconnection_failedthe 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
sessionkeeps its IP, soretry.fresh_ipcannot be combined withsession. 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), 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.
Warning
Think twice before retrying a POST. A request that timed out may still have been carried out by the target.
Was this page helpful?
Last updated