AJAX - AJAX Request Coordination Using the Web Locks API
1. Introduction
Modern web applications often allow users to open the same website in multiple browser tabs or windows. Each tab may perform background activities such as retrieving information from a server, updating records, synchronizing application data, or processing user requests through AJAX. When multiple tabs attempt to access or modify the same shared resource simultaneously, conflicts can occur. These conflicts may result in duplicate requests, inconsistent data, unnecessary server communication, or unexpected application behaviour.
The Web Locks API is a browser technology that helps coordinate access to shared resources across multiple tabs and workers belonging to the same origin. It allows a web application to request a lock before performing a particular operation. When one tab obtains the lock, other tabs requesting the same lock must wait until it is released. This mechanism helps ensure that only one operation accesses a protected resource at a time.
In AJAX applications, the Web Locks API can be used to coordinate background requests, prevent duplicate data synchronization, and control operations that modify shared information. It provides a structured way to manage concurrent activities without requiring complicated communication mechanisms between browser tabs.
2. What Is the Web Locks API?
The Web Locks API is a browser interface that enables scripts to acquire and manage locks for shared resources. It is particularly useful when multiple browser contexts need to access the same data or perform operations that should not overlap.
A lock acts as a temporary permission to perform a particular task. Before executing a protected operation, a browser tab requests a named lock. If the lock is available, the browser grants access. If another tab already holds the same lock, the new request is placed in a waiting queue until the existing operation finishes.
For example, consider an online shopping application opened in three browser tabs. Each tab may attempt to synchronize the user's shopping cart with the server. If all three tabs send synchronization requests simultaneously, duplicate operations may occur. By using the Web Locks API, the application can allow one tab to perform the synchronization while the other tabs wait for the lock to become available.
The Web Locks API provides the following important capabilities:
-
Exclusive locking: Ensures that only one script holds an exclusive lock with a particular name at a time.
-
Shared locking: Allows multiple scripts to hold shared locks simultaneously when they only need to read a resource.
-
Automatic lock release: Releases a lock when the associated asynchronous operation completes or its callback exits.
-
Cross-tab coordination: Allows browser tabs and workers from the same origin to coordinate access to shared resources.
-
Conflict prevention: Reduces the possibility of simultaneous operations interfering with one another.
3. Why Is Request Coordination Important in AJAX?
AJAX allows web applications to exchange data with servers without reloading the entire webpage. Multiple AJAX requests can run independently, which makes applications more responsive and interactive.
However, when several browser tabs perform the same operation, problems can arise.
For example, imagine a banking dashboard opened in two browser tabs. Both tabs periodically request updated account information from the server. If each tab also attempts to update shared application data, unnecessary requests and conflicting updates may occur.
Request coordination helps address these problems by controlling when specific operations are allowed to execute.
Some important reasons for using request coordination include:
Preventing Duplicate Requests: Multiple tabs may request the same information at approximately the same time. A shared locking mechanism can prevent unnecessary duplicate operations.
Maintaining Data Consistency: When several tabs modify the same shared information, coordinating access helps reduce conflicting updates.
Reducing Server Workload: Preventing repeated background operations can reduce unnecessary requests sent to the server.
Managing Background Synchronization: Applications that periodically synchronize information can use locks to ensure that only one tab performs the synchronization task.
Improving Application Reliability: Coordinated operations reduce unpredictable behaviour caused by multiple scripts attempting to modify the same resource simultaneously.
4. How the Web Locks API Works with AJAX
The Web Locks API works alongside asynchronous JavaScript operations, including AJAX requests made through the Fetch API or XMLHttpRequest.
The process generally follows these steps:
-
A browser tab identifies an operation that requires exclusive access to a shared resource.
-
The application requests a named lock using the
navigator.locks.request()method. -
The browser checks whether the requested lock is available.
-
If the lock is available, the browser grants it to the requesting script.
-
The script performs the required AJAX request or data synchronization operation.
-
After the operation is completed, the lock is automatically released.
-
Another waiting tab can then acquire the lock and perform its operation.
The following example demonstrates how the Web Locks API can coordinate an AJAX request.
async function synchronizeData() {
await navigator.locks.request("data-sync-lock", async () => {
console.log("Lock acquired. Starting synchronization.");
try {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error("Failed to retrieve data");
}
const data = await response.json();
console.log("Data synchronized:", data);
} catch (error) {
console.error("Synchronization error:", error);
}
});
console.log("Lock released.");
}
synchronizeData();
In this example, the application requests a lock named data-sync-lock before starting the AJAX operation.
If another browser tab already holds this lock, the current tab waits until the lock becomes available. Once access is granted, the application retrieves information from the server using the Fetch API.
The lock remains active while the asynchronous operation is running. When the operation finishes, the browser automatically releases the lock.
5. Understanding Exclusive and Shared Locks
The Web Locks API supports two important locking modes: exclusive locks and shared locks.
Exclusive Locks
An exclusive lock allows only one script to access a particular protected resource at a time.
It is useful when an operation modifies shared information or when simultaneous execution could create conflicts.
For example, an application that updates a shared shopping cart can use an exclusive lock to ensure that two browser tabs do not perform the same protected update simultaneously.
The following example demonstrates an exclusive lock:
navigator.locks.request(
"cart-update",
async () => {
console.log("Updating shopping cart");
const response = await fetch("/api/cart/update", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
productId: 101,
quantity: 2
})
});
const result = await response.json();
console.log(result);
}
);
Since the default locking mode is exclusive, another script requesting the same lock must wait until the current operation finishes.
Shared Locks
Shared locks allow multiple scripts to hold the same lock simultaneously. They are useful when multiple tabs need to perform read-only operations on a shared resource.
For example, several browser tabs may need to read shared application information without modifying it.
navigator.locks.request(
"shared-data",
{ mode: "shared" },
async () => {
const response = await fetch("/api/data");
const data = await response.json();
console.log(data);
}
);
Multiple scripts can acquire this shared lock simultaneously, provided there is no conflicting exclusive lock.
The choice between exclusive and shared locking depends on the nature of the operation. Exclusive locks are appropriate for protected modifications, while shared locks are suitable for compatible reading operations.
6. Using Web Locks for Background AJAX Synchronization
Many web applications perform background synchronization to keep information updated without requiring users to refresh the page.
For example, an online project management application may periodically retrieve updated task information from its server. If the application is open in several tabs, every tab might independently perform the same synchronization operation.
This can increase server traffic and waste browser resources.
The Web Locks API can help ensure that only one eligible tab performs the synchronization operation at a time.
Consider the following example:
async function backgroundSync() {
await navigator.locks.request(
"background-sync",
{ ifAvailable: true },
async (lock) => {
if (!lock) {
console.log("Another tab is synchronizing data.");
return;
}
try {
const response = await fetch("/api/synchronize");
const result = await response.json();
console.log("Synchronization completed:", result);
} catch (error) {
console.error("Background sync failed:", error);
}
}
);
}
backgroundSync();
In this example, the ifAvailable option tells the browser not to wait for the lock if another tab already holds it.
If the lock is unavailable, the callback receives null, and the application skips the synchronization operation.
This approach is useful when background synchronization does not need to happen independently in every browser tab.
7. Handling Lock Requests and Timeouts
In real-world AJAX applications, lock requests may need to wait for a long-running operation to finish. Developers should carefully manage these situations to avoid unnecessary delays.
The Web Locks API provides options for controlling how lock requests behave.
Some useful options include:
-
ifAvailable: Allows the application to check whether a lock is immediately available without waiting.
-
steal: Requests a lock by breaking an existing lock's ownership. This option should be used cautiously because it can interrupt another operation.
-
signal: Allows an application to cancel a pending lock request using an AbortSignal.
For example, an application can cancel a pending lock request if the user navigates away or the operation is no longer required.
const controller = new AbortController();
navigator.locks.request(
"ajax-processing",
{ signal: controller.signal },
async () => {
const response = await fetch("/api/process");
const result = await response.json();
console.log(result);
}
).catch(error => {
console.log("Lock request cancelled:", error);
});
The application can cancel the pending request by calling:
controller.abort();
This is particularly useful when an operation becomes unnecessary before the browser grants the requested lock.
The Web Locks API does not provide a built-in timeout option. Developers who need timeout behaviour can implement it using JavaScript cancellation mechanisms.
8. Practical Applications of Web Locks in AJAX Development
The Web Locks API can be applied in several types of web applications where multiple browser tabs need to coordinate background activities.
Online Banking Applications: Banking dashboards can coordinate certain background data retrieval and synchronization operations to reduce unnecessary requests and prevent conflicting client-side updates.
E-Commerce Websites: Shopping websites can coordinate cart synchronization between multiple tabs to reduce duplicate operations and improve consistency.
Content Management Systems: CMS applications can coordinate background publishing, synchronization, or other shared client-side operations.
Online Collaboration Platforms: Collaboration applications can coordinate access to shared browser-side resources when several tabs are open.
Project Management Applications: Project management systems can prevent multiple tabs from performing the same background synchronization task simultaneously.
Offline-First Applications: Applications that store information locally can coordinate certain synchronization activities when connectivity becomes available.
It is important to understand that Web Locks coordinate browser contexts, not independent users or devices. Server-side validation and transaction management are still necessary when protecting important shared data.
9. Advantages and Limitations of the Web Locks API
Advantages
-
Prevents Concurrent Operations: Helps prevent multiple browser tabs from executing conflicting protected operations simultaneously.
-
Reduces Duplicate AJAX Requests: Allows applications to coordinate background requests and avoid unnecessary repeated work.
-
Simplifies Coordination: Provides a built-in browser mechanism instead of requiring developers to implement all locking logic manually.
-
Supports Asynchronous Operations: Works naturally with JavaScript promises and asynchronous Fetch requests.
-
Improves Resource Management: Helps coordinate access to shared browser-side resources.
Limitations
-
Browser Support: The API is not available in every browser environment, so developers should check support before using it.
-
Same-Origin Restriction: Lock coordination is limited to scripts operating within the same origin.
-
No Server-Side Locking: It cannot coordinate requests originating from different devices or independent users.
-
Potential Waiting Delays: A script may need to wait when another operation holds the requested lock.
-
Careful Implementation Required: Long-running operations can prevent other tabs from obtaining the same lock.
-
Not a Replacement for Database Transactions: Important data modifications must still be protected using appropriate server-side mechanisms.
10. Conclusion
The Web Locks API is a useful browser technology for coordinating asynchronous operations in modern AJAX applications. It allows multiple browser tabs and workers to manage access to shared resources through exclusive and shared locks. By controlling when particular operations can execute, developers can reduce duplicate background requests, avoid certain client-side conflicts, and improve the reliability of data synchronization.
When combined with the Fetch API, IndexedDB, and other browser technologies, the Web Locks API can support more efficient multi-tab web applications. However, it should be treated as a client-side coordination mechanism rather than a replacement for server-side security, data validation, or database transaction management. Understanding this API helps developers build AJAX applications that behave more consistently when users interact with the same application across multiple browser tabs.