Skip to content

How to Handle Retry and Timeout When Using a Proxy

Proxied requests have more places to fail. Learn how to set layered timeouts, choose which errors deserve a retry, add backoff and keep retries polite.

9 min readUpdated Nov 13, 2026By XPASS Editorial Team

How to Handle Retry and Timeout When Using a Proxy

Every network call can fail, and a call that travels through a proxy has one more hop where things can go wrong. A timeout that looks fine for a direct request may be too tight once a proxy is in the path, and a retry loop that is harmless against a quiet internal service can become a problem when it multiplies traffic against someone else's API. This guide explains how to think about timeouts in layers, how to decide which failures deserve a retry, how to space attempts out, and how to keep the whole thing polite and observable. The advice applies to any language; the examples use JavaScript. Use proxies only for lawful work, follow the terms of the services you call, and treat rate limits as rules rather than obstacles.

Where a proxied request can fail

Picture the journey of one HTTPS request through a proxy and mark each stage where a delay or error can appear.

  1. Connecting to the proxy. DNS lookup of the proxy name, TCP connection to its port.
  2. Authenticating to the proxy. The proxy may answer with HTTP 407 when credentials are missing or wrong.
  3. Opening the tunnel. The client sends CONNECT to the target host and port, and the proxy tries to reach it. Failures here often appear as 502, 503 or 504 from the proxy itself. The MDN guide to proxy servers and tunneling describes this step.
  4. TLS handshake with the target. Slow or failed handshakes show up as timeouts or certificate errors.
  5. Sending the request and waiting for the first byte. The target may be slow or overloaded.
  6. Reading the response body. A connection can stall halfway through a large download.

A single total timeout for all of this hides which stage is slow. Layered limits make failures easier to understand and let you react differently to each one.

Choosing layered timeouts

Most HTTP libraries expose some mix of the following. Names differ, but the ideas are shared.

Timeout What it limits Practical thought
Connect Time to reach the proxy and open the TCP connection Keep it short; a proxy that cannot be reached in a few seconds is unlikely to recover during the wait
TLS or tunnel Time to finish CONNECT and the handshake Slightly longer than connect, since the proxy has to reach the target
Response headers or first byte Time until the target starts to answer Depends on the API; slow endpoints need a larger value
Idle or read Time between chunks of data Protects against stalled transfers
Total deadline Overall time for the operation, including retries The cap that keeps a job from running forever

There is no universal set of numbers. Start modestly, measure the real distribution of response times for your own traffic, and set limits just above what healthy requests need. Proxied calls add a hop, so base your values on measurements taken through the proxy, not on a direct test from your laptop.

In modern JavaScript, AbortController with a timer is a convenient way to enforce a total deadline on fetch, and libraries such as Axios offer a timeout option. When you need finer control, set connect and socket timeouts on the underlying agent. The article on setting up a proxy in Node.js fetch shows where those hooks sit, and configuring Axios for API work covers the same topic for Axios.

Deciding what to retry

Retrying everything is as bad as retrying nothing. Classify the failure first.

Usually worth retrying

  • Connection reset, connection refused for a moment, DNS lookup failure and similar transport errors.
  • Timeouts, within your total deadline.
  • HTTP 502, 503 and 504, which often signal a temporary problem along the path.
  • HTTP 429 or 503 together with a Retry-After header, when you wait at least as long as the server asks.
  • HTTP 408, which means the server timed out waiting for the request.

Usually not worth retrying

  • HTTP 400, 404 and 422. The request itself is wrong, and repeating it will not fix it.
  • HTTP 401 and 403. Check your credentials and permissions instead of repeating.
  • HTTP 407 from the proxy. Fix the proxy credentials; a loop will only generate noise.
  • Any response that says the request was understood and refused for policy reasons.

Be especially careful with 403 and 429 from a target site. They are signals about your behaviour. Respond by slowing down, reducing concurrency or contacting the API owner, not by trying to dodge the control. RFC 9110 defines the meaning of these status codes and of the Retry-After header, and it is worth reading the short sections on them once.

Idempotency: when a retry can do harm

HTTP defines some methods as idempotent, meaning that repeating the same request has the same intended effect as making it once. GET, HEAD, PUT and DELETE are idempotent by definition, while POST is not. In practice, an API can break the definition, so read its documentation.

The danger is the lost response. You send a POST that creates an order. The order is created, but the connection drops before the answer reaches you. If you retry blindly, you might create a second order. Safer patterns include:

  • Sending an idempotency key, if the API supports one, so repeated attempts are recognised as the same operation.
  • Checking the state first, for example by querying for the order before creating it again.
  • Limiting automatic retries to read requests and sending anything that changes data to a manual or queued process.

Backoff, jitter and budgets

A retry should wait. Waiting gives a struggling service time to recover, and it keeps you from hammering an endpoint.

  • Exponential backoff. Double the delay after each failure: for example 1 second, then 2, then 4.
  • Jitter. Add a random amount to each delay. Without it, many workers that failed together retry together, creating synchronised bursts.
  • Maximum attempts. Two or three retries are plenty for most jobs.
  • Total deadline. Stop when the overall time budget is spent, whatever the attempt count says.
  • Retry budget. Limit the share of your traffic that may be retries, so a bad hour cannot double your load.

A compact example in JavaScript:

async function fetchWithRetry(doRequest, { retries = 3, baseMs = 1000, deadlineMs = 30000 } = {}) {
  const started = Date.now();
  for (let attempt = 0; ; attempt++) {
    try {
      const res = await doRequest();
      if (![429, 502, 503, 504].includes(res.status)) return res;
      if (attempt >= retries) return res;
      const wait = retryAfterMs(res) ?? backoff(attempt, baseMs);
      if (Date.now() - started + wait > deadlineMs) return res;
      await sleep(wait);
    } catch (err) {
      if (attempt >= retries || !isTransient(err)) throw err;
      const wait = backoff(attempt, baseMs);
      if (Date.now() - started + wait > deadlineMs) throw err;
      await sleep(wait);
    }
  }
}

const backoff = (n, base) => base * 2 ** n + Math.floor(Math.random() * base);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

The helper functions retryAfterMs and isTransient are small: the first reads the Retry-After header as seconds or as a date, and the second checks error codes such as ECONNRESET and ETIMEDOUT.

Here is a small illustration with made-up numbers, only to show the arithmetic. Suppose healthy requests finish within 3 seconds, you allow 3 retries, the response timeout is 6 seconds and the backoff waits are about 1, 2 and 4 seconds. One failing item can then consume roughly 4 times 6 seconds of waiting plus 7 seconds of pauses, which is about 31 seconds. If the job handles 1,000 items and the target is down, that is hours of wasted work. This is why a total deadline per item and a circuit breaker matter: they turn a long outage into a short, quiet pause instead of a pile of doomed attempts.

A plain worked example

A nightly job collects order data from a partner API through a proxy. It fails sometimes with a timeout. Here is a sensible way to harden it.

  1. Measure a week of successful calls and note the 95th percentile of response time. Suppose it is a few seconds.
  2. Set the connect timeout to a few seconds, the response timeout to a comfortable margin above the measured percentile, and a total deadline per job item.
  3. Retry only read requests and only on the transient classes listed above, with exponential backoff and jitter, up to three attempts.
  4. Honour Retry-After when present.
  5. If five consecutive items fail, pause the whole job for a few minutes rather than pushing on. This is a simple circuit breaker.
  6. Record each failure with the stage, status code or error code, attempt number and elapsed time.
  7. Review the log after a few runs and adjust the numbers.

Notice that nothing here tries to defeat the API. The aim is a job that recovers from brief glitches and backs off when the other side asks it to.

A quick decision rule helps when you are unsure. Ask three questions in order. Is the failure likely to be temporary? If not, stop and report it. Is the request safe to repeat? If not, check the state or use an idempotency key first. Has the server told me how long to wait? If so, wait at least that long. Only when all three answers allow it should the code try again. Writing this rule next to the retry function in a comment keeps later edits from quietly turning a careful policy into an endless loop.

Limits and what to watch for

  • Retries multiply load. Three attempts on every item means up to four times the traffic during an outage. Combine retries with concurrency limits, as discussed in managing connection pools across several proxy IPs.
  • Retry storms. If many workers share one cause of failure, they all retry. Jitter and a circuit breaker reduce the effect.
  • Proxy versus target errors. A 502 or 504 may come from the proxy or from the target. Check headers and your proxy's documentation to tell them apart before you decide the target is down.
  • Switching proxies. Moving to another proxy between attempts can help when the problem is the path, but keep it bounded, and never use it to sidestep a rate limit, a block or a site's terms.
  • Plan limits. Failed attempts can still count toward connection or traffic limits of your plan. Check the plan page for what is included.
  • Hidden timeouts. Load balancers, firewalls and the target may close idle connections on their own schedule. Keep-alive settings should be shorter than the shortest idle limit in the path.
  • Logging secrets. Do not log proxy credentials or full URLs that contain tokens.

Summary

Treat a proxied request as a chain of stages and give each a sensible, measured timeout, plus a total deadline. Retry only failures that are likely to be temporary, such as transport errors, 502, 503, 504 and a polite 429, and avoid blind retries of requests that change data unless you have an idempotency key. Use exponential backoff with jitter, a small attempt limit, a retry budget and a circuit breaker, and honour what the server tells you. Log the stage and reason for every failure so you can tune the numbers with evidence. If you are choosing a proxy for this kind of work, the options are described on the XPASS proxy page.

Frequently asked questions

Which errors are worth retrying through a proxy?

Network resets, connection timeouts and server-side errors such as 502, 503 and 504 are the usual candidates, as is 429 when you wait for the period the server asks for. Client errors such as 400, 401, 403 and 404 normally will not change on a repeat and should not be retried.

Is it safe to retry a POST request?

Not by default. A POST may have been processed even though you never saw the response. Retry it only when the API supports an idempotency key or when you can check the outcome first.

How many retries should I allow?

Keep the number small, often two or three, and add a delay that grows between attempts with some random jitter. Also cap the total time a single job may spend retrying.

Should I change the proxy between retries?

Sometimes, if the failure points at the proxy path rather than the target. Do it deliberately, keep the rotation bounded and never use it to get around a rate limit or a block that a site has put in place.

About the author

Bob Kanokphon Thongdee, founder of XPASS VPN

Bob Kanokphon Thongdee

  • Founder of XPASS VPN
  • Co-founder of eSIMonline.asia
  • More than 7 years in online marketing
  • Founder of Cojourney Visa and Cojourney Travel

Need a proxy for this?

XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.

See proxy plans

Keep reading

Proxy Guides

How to Set Up an Axios Proxy for API Work

A practical guide to routing Axios requests through a proxy in Node.js, from the built-in proxy option to agents, environment variables, timeouts and testing.

9 min read

Proxy Guides

How to Manage a Connection Pool When Using Multiple Proxy IPs

When your code uses several proxy IPs, connection handling matters. See how to keep one pool per endpoint, cap concurrency, retire bad endpoints and avoid leaks.

10 min read

Proxy Guides

How to Set Up a Proxy in Node.js fetch

The built-in fetch in Node.js ignores proxy environment variables by default. This guide shows how to route it through a proxy with an undici dispatcher and test the result.

9 min read