Duplicate messages are appearing at the message receiver front-end in the speedy chat due to Ajax polling

After developing a unique javascript chat system with php on the backend, the following techniques were utilized:

1) Implementing long-polling to retrieve new messages for the receiver 
2) Utilizing sessionStorage to maintain the message counter 
3) Utilizing setInterval to check for new messages and displaying the latest message if sessionStorageCounter < setIntervalCounter
4) Using javascript for creating, updating, and displaying chat dialogues

While the module functions properly, it seems that during fast-paced chatting sessions, the receiver's front end sometimes receives duplicate messages (counter and query checks out fine).

Despite the correctness of the code (omitted for brevity), the issue could potentially lie in the interval delay, which remains unresolved even after reducing it.

Considering the scenario described above, do you believe the current system architecture is suboptimal? If so, what alternative schema would you propose to rectify these errors?

Answer №1

One strategy I would use to solve this problem on my own, without relying on an existing library, is as follows:

  • Assign a unique ID (GUID) to each message as it arrives on the server.
  • Store the ID of the most recently received message on the clients.
  • When checking for new messages, use the ID of the last successfully received message. The server will then find that message in its queue and replay all subsequent messages.
  • To prevent 'dropped' messages, each message can also include the ID of the immediate previous message for consistency-checking by the client.

If repolling results in duplicates being sent from the server to the client, removing them is easy thanks to the presence of unique IDs on each message. Visualize the server-side message queue as an event stream, with each client monitoring their last-read position. The client does not need to guess the correct message order or quantity since its state is solely based on 'what have I seen', minimizing chances of falling out of sync.

Answer №2

Given the nature of live chat, the interval set for setInterval is likely short enough to enable the server to handle multiple requests for new messages from the user at the same time. It's important for the server handler to be synchronized and to properly handle and discard duplicate queries from the same user.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing my file input to duplicate and send the image twice?

I am facing an issue with my Ajax script that displays images sent by the admin to clients. The problem is, every time the admin uploads a new image, the script duplicates and sends the image twice. For example, if the admin uploads the first image, it sho ...

Once the label with the text "DYNAMIC" is filled dynamically, it becomes challenging to retrieve the same text

I'm currently populating the Label4.text dynamically with the hope of being able to retrieve it for updating in the database. <asp:Label ID="Label4" runat="server" Font-Bold="True" BackColor="#E3EAEB" Height="25px" Width="300px"><%=Applic ...

Utilizing Redux dispatch to uncheck checkboxes within renderOption with Material UI Autocomplete

In the Autocomplete component, I have a checkbox that is rendered in the renderOptions prop. By using the onChange function event: object, value: T | T[], reason: string), I can retrieve the list of selected options. The value parameter will provide me w ...

Comparing throwing exceptions in Node.js and Gevent

During a recent tech gathering, I heard an interesting claim about the behavior of callbacks and exceptions in Node.js and Gevent. The person mentioned that if a callback throws an exception in Node.js, it can crash the entire process, whereas in Gevent, a ...

Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties. Criteria Must start with "url" Followed by brackets Optional quotes inside brackets The location can include path information Must ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

Asynchronously retrieve the result from a previous NodeJS chain and forward it to a nested function for processing

When uploading an image from the client as Base64 to the server, I need to: Save the file to disk Get the result of the save (first chain) and pass it to the next chain Check the result in the next function using that(), if it's true, update the dat ...

It's not possible to add additional options to the select input in a react

Hi there! I'm currently facing an issue while trying to retrieve a list of options from the backend, map them to another list of options, and add them to a main list. Unfortunately, my attempts have not been successful. Could anyone offer some advice ...

Issue with JSON or Jquery: Uncaught error message: Cannot access property 'error' as it is null

I am attempting to initiate an ajax call using the jQuery code provided below. However, when I try this in Chrome, I encounter an error that says 'uncaught typeerror cannot read property 'error' of null'. This prevents the preloader fr ...

Filtering GridView Results with Live Search on ASP.net Textbox

I am currently working on implementing a live search feature for my ASP.net project. The goal is to have a description textbox where users can enter their search term, and the GridView below will dynamically filter the results as the user types. While I ...

Develop an API within a Vue/Quasar server-side rendering (SSR) project

I am looking to develop an API that can be accessed by the app itself (via "ajax" or server-rendered) as well as other clients like a mobile app. Most of the resources I have come across while searching for "Quasar REST API" focus on utilizing external API ...

I am having issues with the drag and drop directives in AngularJS - they work fine on my computer's navigator, but they

I have successfully implemented drag and drop directives in angularJS, and they are functioning properly on my computer's web browser. However, when I tried to use the directives on my touch devices, they did not work. Should I make adjustments to my ...

Utilizing a variable twice within the Express module, while only using it once in another module

Below is a basic example of how to use a Node.js module: let os = require('os'); console.log("This is the user info - " , os.userInfo()); In this case, we can see that by using dot notation, we were able to access the existing functio ...

Utilizing Ajax to Invoke Wordpress Functions from a Client's Browser

Currently working on setting up a WordPress website integrated with WooCommerce, while also developing an HTML5 app for my small online store. I am looking to utilize Ajax to call WordPress functions like search directly from my HTML5 app and receive the r ...

javascriptif the number is a whole number and evenly divisible

I am currently developing a script that tracks the distance traveled by some dogs in meters. It is basically just a gif running in a loop. What I want to achieve now is to display an image every 50 meters for a duration of 3 seconds. Here's my attempt ...

Understanding the specific purpose and functionality of the "next()" parameter in express.js

As a newcomer to express.js, I have been diving into the documentation to understand its nuances. One particular aspect that caught my attention is the next parameter in express middleware, which supposedly triggers the following middleware function for th ...

A guide on implementing reverse routes using react-router

Is there a best practice for constructing URLs for links in my react-router based app? In the Zend Framework world of php, I would use a url helper that utilizes reverse routes. By providing the route name and parameters to a route configuration, it would ...

Searching through a json object using typescript

While attempting to retrieve JSON data from a URL, I encountered a particular issue. The problem lies in the fact that each row in the Datarows array contains 5 rows, each row consisting of 47 cells. Out of these 47 cells in each row, I am specifically in ...

Dropdown selection values were not set appropriately

I've been encountering an issue with setting the selected value in a drop-down list using the code below. The values are being split from a comma-separated string, but it's not functioning as intended. When I use string='text1,text2,text3,t ...