AJAX - AJAX Circuit Breaker Pattern for Fault-Tolerant Applications

Introduction

The AJAX Circuit Breaker Pattern is a fault-tolerance technique used to prevent a web application from continuously sending AJAX requests to a server or API that is unavailable, overloaded, or repeatedly returning errors.

Normally, when an AJAX request fails, an application may try the request again. If the server continues to be unavailable, repeated requests can increase network traffic, consume browser and server resources, and make the application slower. In some situations, this repeated communication can make an already struggling server experience even more load.

The circuit breaker pattern solves this problem by temporarily stopping requests after a certain number of failures. After waiting for a specified period, the application allows a limited request to determine whether the server has recovered.

Why the Circuit Breaker Pattern Is Needed

Consider an application that retrieves product information from an external API using AJAX.

Under normal conditions, the application sends a request:

Browser → AJAX Request → API Server
Browser ← Response ← API Server

Suppose the API server becomes unavailable. The browser continues making requests whenever users perform an action.

Without a circuit breaker, the process may look like this:

Request → Failure
Request → Failure
Request → Failure
Request → Failure
Request → Failure

If the application automatically retries every failed request, the number of requests can increase significantly.

A circuit breaker changes this behavior:

Request → Failure
Request → Failure
Request → Failure
Circuit Opens
Further Requests → Blocked

After a waiting period, the application tests the server again.

Three States of a Circuit Breaker

A circuit breaker generally operates using three states:

  1. Closed

  2. Open

  3. Half-Open

These states determine whether AJAX requests should be sent to the server.

1. Closed State

The Closed state represents normal operation.

In this state, AJAX requests are allowed to reach the server. The application monitors the results of these requests and records failures.

For example:

Browser
   |
   | AJAX Request
   v
Server
   |
   | Successful Response
   v
Browser

If the server responds successfully, the failure count remains low or can be reset.

For example, an application may define a failure threshold of three:

Failure 1 → Continue
Failure 2 → Continue
Failure 3 → Continue

If the number of consecutive failures reaches the configured threshold, the circuit changes from Closed to Open.

2. Open State

When the circuit is Open, AJAX requests are temporarily prevented from reaching the failing server.

For example:

Browser
   |
   | Request
   v
Circuit Breaker
   |
   | Request blocked
   X
Server

Instead of sending the request, the application can immediately return an appropriate result to the user interface.

For example, the application might display:

Unable to load the latest information.
Please try again later.

The important purpose of this state is to prevent unnecessary communication with an unavailable service.

The circuit remains open for a predefined period, such as 30 seconds.

3. Half-Open State

After the waiting period expires, the circuit changes to the Half-Open state.

In this state, the application allows a limited test request to determine whether the server has recovered.

For example:

Circuit Open
     |
     | Waiting period completed
     v
Circuit Half-Open
     |
     | Test AJAX request
     v
Server

If the test request succeeds, the circuit changes back to Closed:

Half-Open → Successful Request → Closed

Normal AJAX requests can then resume.

If the test request fails, the circuit returns to Open:

Half-Open → Failed Request → Open

The application then waits before attempting another test.

Basic Working Process

The complete process can be understood as follows:

             Request
                |
                v
        Circuit is Closed?
           /          \
         Yes           No
          |             |
          v             v
    Send AJAX       Check State
     Request
          |
          v
      Response
       /    \
   Success  Failure
      |        |
      v        v
 Reset      Increase
 Count      Failure Count
                 |
                 v
        Threshold Reached?
             /       \
           No         Yes
           |           |
           v           v
        Continue     Open

When the circuit is open, the application waits for the recovery period and then moves to the half-open state.

Example Using JavaScript

A simple implementation can be created using JavaScript and AJAX through the Fetch API.

let circuitState = "CLOSED";
let failureCount = 0;

const failureThreshold = 3;
const recoveryTime = 5000;

async function makeAjaxRequest(url) {

    if (circuitState === "OPEN") {
        throw new Error("Circuit is open. Request blocked.");
    }

    try {
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error("Server request failed");
        }

        failureCount = 0;
        circuitState = "CLOSED";

        return await response.json();

    } catch (error) {

        failureCount++;

        if (failureCount >= failureThreshold) {
            circuitState = "OPEN";

            setTimeout(() => {
                circuitState = "HALF_OPEN";
            }, recoveryTime);
        }

        throw error;
    }
}

The example maintains the current circuit state and counts failures. When the failure threshold is reached, further requests are blocked for a specified period.

A production implementation would normally need additional handling for the Half-Open state so that only a controlled test request is permitted.

Example Scenario

Suppose an online shopping website uses AJAX to retrieve delivery information.

Initially:

Circuit: CLOSED
Server: Available

The user requests delivery information, and the request succeeds.

Later, the delivery API becomes unavailable.

The next requests fail:

Request 1 → Failure
Request 2 → Failure
Request 3 → Failure

If the failure threshold is three, the circuit opens.

Now:

Request 4 → Blocked
Request 5 → Blocked
Request 6 → Blocked

The browser does not repeatedly contact the unavailable API.

After the configured recovery period, the circuit enters the Half-Open state.

A test request is sent:

Test Request → Server

If the server responds successfully:

Half-Open → Closed

Normal requests resume.

If the server still fails:

Half-Open → Open

The application continues to block requests until another recovery attempt is appropriate.

Advantages of the Circuit Breaker Pattern

The circuit breaker pattern provides several benefits.

Reduced unnecessary requests

When a server is unavailable, the application does not repeatedly send requests that are likely to fail.

Improved application responsiveness

Blocked requests can fail immediately instead of waiting for network timeouts.

Reduced server load

A failing server does not receive a continuous stream of repeated requests from clients.

Better fault isolation

A failure in one external API does not necessarily cause the entire web application to repeatedly wait for that API.

Controlled recovery

The Half-Open state gives the server an opportunity to recover without immediately receiving a large number of requests.

Circuit Breaker vs Retry

Retry and circuit breaker patterns serve different purposes.

A retry mechanism attempts a failed request again because the failure may be temporary.

For example:

Request
   ↓
Failure
   ↓
Retry
   ↓
Success

A circuit breaker stops requests when failures become persistent.

Request
   ↓
Failure
   ↓
Failure
   ↓
Failure
   ↓
Circuit Opens
   ↓
Requests Blocked

They can also be used together. A limited number of retries can be attempted first, while the circuit breaker prevents excessive retries when the service continues to fail.

Important Configuration Parameters

A practical AJAX circuit breaker usually has several configurable values.

Failure Threshold

The number of failures required before opening the circuit.

Example:

Failure Threshold = 3

This means three qualifying failures can cause the circuit to open.

Recovery Timeout

The amount of time the circuit remains open before testing the service again.

Example:

Recovery Timeout = 30 seconds

Success Threshold

Some implementations require more than one successful request before returning completely to the Closed state.

For example:

Half-Open
   ↓
Success
   ↓
Success
   ↓
Closed

Request Timeout

The application should also define how long an AJAX request can wait before being considered unsuccessful.

Handling Circuit Breaker Errors in the User Interface

When the circuit is open, the application should provide meaningful feedback rather than simply displaying a technical error.

For example:

try {
    const data = await makeAjaxRequest("/api/products");
    displayProducts(data);
} catch (error) {
    displayMessage(
        "Product information is temporarily unavailable. Please try again later."
    );
}

This separates technical failure handling from the user interface.

The user does not need to know whether the circuit is Closed, Open, or Half-Open. Those states are implementation details.

Conclusion

The AJAX Circuit Breaker Pattern provides a structured way to handle repeated server or API failures in web applications. Instead of continuously sending AJAX requests to an unavailable service, the circuit breaker monitors failures, temporarily blocks requests, and later tests whether the service has recovered.

Its three primary states—Closed, Open, and Half-Open—provide a clear mechanism for normal operation, failure protection, and controlled recovery. When combined carefully with request timeouts and limited retries, the pattern can make AJAX-based applications more resilient and responsive when external services experience temporary or prolonged failures.