JavaScript
XMLHttpRequest
server optimization
web development
performance enhancement

XMLHttpRequest used to find quicker server

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Using XMLHttpRequest to choose the fastest server is a latency optimization pattern often used in multi-region web applications. The idea is simple: probe several endpoints, measure response time, and route the user to the lowest-latency option. A correct implementation must handle timeouts, caching effects, and noisy network variance.

How Latency Probing Works

A client sends lightweight requests to candidate servers and records elapsed time. You typically probe a health endpoint such as /ping that returns a small payload.

javascript
1function probeServer(url, timeoutMs = 2000) {
2  return new Promise((resolve) => {
3    const xhr = new XMLHttpRequest();
4    const start = performance.now();
5
6    xhr.open("GET", `${url}/ping?ts=${Date.now()}`, true);
7    xhr.timeout = timeoutMs;
8
9    xhr.onreadystatechange = function () {
10      if (xhr.readyState === XMLHttpRequest.DONE) {
11        const elapsed = performance.now() - start;
12        if (xhr.status >= 200 && xhr.status < 400) {
13          resolve({ url, ok: true, elapsed });
14        } else {
15          resolve({ url, ok: false, elapsed: Number.POSITIVE_INFINITY });
16        }
17      }
18    };
19
20    xhr.ontimeout = function () {
21      resolve({ url, ok: false, elapsed: Number.POSITIVE_INFINITY });
22    };
23
24    xhr.onerror = function () {
25      resolve({ url, ok: false, elapsed: Number.POSITIVE_INFINITY });
26    };
27
28    xhr.send();
29  });
30}

The timestamp query parameter reduces caching impact.

Choosing a Winner Robustly

Single probes can be noisy. A stronger strategy runs multiple rounds and uses median latency.

javascript
1async function chooseFastestServer(servers, rounds = 3) {
2  const stats = new Map();
3
4  for (const s of servers) stats.set(s, []);
5
6  for (let i = 0; i < rounds; i += 1) {
7    const results = await Promise.all(servers.map((s) => probeServer(s)));
8    for (const r of results) {
9      if (r.ok) stats.get(r.url).push(r.elapsed);
10    }
11  }
12
13  const summary = servers.map((url) => {
14    const values = stats.get(url).sort((a, b) => a - b);
15    const median = values.length ? values[Math.floor(values.length / 2)] : Number.POSITIVE_INFINITY;
16    return { url, median };
17  });
18
19  summary.sort((a, b) => a.median - b.median);
20  return summary[0];
21}

Median selection is less sensitive to one-time spikes than minimum or average.

Integrating With App Routing

After choosing a server, persist it for a short period to avoid repeated probing on every page load.

javascript
1async function getPreferredServer() {
2  const cacheKey = "preferredServer";
3  const cached = JSON.parse(localStorage.getItem(cacheKey) || "null");
4
5  if (cached && Date.now() - cached.savedAt < 10 * 60 * 1000) {
6    return cached.url;
7  }
8
9  const candidate = await chooseFastestServer([
10    "https://us.example.com",
11    "https://eu.example.com",
12    "https://ap.example.com"
13  ]);
14
15  localStorage.setItem(cacheKey, JSON.stringify({ url: candidate.url, savedAt: Date.now() }));
16  return candidate.url;
17}

A short cache window balances freshness and startup overhead.

Operational Considerations

  • Probe endpoints should be cheap and unauthenticated where possible.
  • Apply rate limits so probing logic cannot amplify traffic during incidents.
  • Keep fallback behavior defined when all probes fail.

Also verify cross-origin policies. If endpoints are on different domains, CORS configuration must allow requests from your frontend origin.

Security and Privacy Notes

Do not probe arbitrary third-party endpoints from browsers. Restrict candidate server list to trusted infrastructure and use HTTPS only. If probe responses include diagnostics, keep payload minimal so latency checks do not leak operational details.

Common Pitfalls

  • Picking a server from one probe and overreacting to transient network jitter.
  • Probing heavy endpoints instead of lightweight health endpoints.
  • Ignoring CORS failures that make servers appear slow or unavailable.
  • Running probes too frequently and creating unnecessary traffic.
  • Failing open to a default region when every probe times out.

Summary

  • XMLHttpRequest probing can improve perceived performance in multi-server deployments.
  • Reliable selection should use multiple rounds and median latency.
  • Cache selected server briefly to reduce repeated startup overhead.
  • Keep probe endpoints lightweight and operationally safe.
  • Always implement deterministic fallback behavior for full probe failure cases.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.