Nik Drosakis
Nik Drosakis

Reputation: 2348

Ajax polling chat gets duplicates at message receiver front-end on speedy chat

I have developed a javascript chat (php on the backend) using:

1) long-polling to get new messages for the receiver 
2) sessionStorage to store the counter of messages  
3) setInterval to read new messages and if sessionStorageCounter < setIntervalCounter then the last message is shown to receiver.
4) javascript to create,update and write the chat dialogues

The module is working fine, but when users have a speedy chat the receiver' front end gets two or three same messages, (neither the counter fails, nor the query provides double inserts).

The code seems to be correct (that's why I don't provide the code), so the interval delay might be the reason (on reducing interval delay, nothing changes).

Do you think that the above schema is a bad practice and which schema do you think would eliminate the errors?

Upvotes: 4

Views: 282

Answers (2)

falsarella
falsarella

Reputation: 12447

Since it's real time chat, the setInterval interval is probably small enough to ask the server for new messages two or three times simultaneously. Make sure that the server handler is synchronized and it is ignoring duplicated queries from the same user.

Upvotes: 0

S McCrohan
S McCrohan

Reputation: 6693

My approach, if solving it myself (as opposed to using an existing library that already handles this) would be:

  • Have the server assign a unique ID (GUID) to each message as it arrives.
  • On the clients, store the ID of the most recently received message.
  • When polling for new messages, do so with the ID of the last message successfully received. Server then responds by finding that message in its own queue and replaying all of the subsequent messages.
  • To guard against 'dropped' messages, each message can also carry the ID of the immediately-previous message (allowing the client to do consistency-checking)

If repolling does cause duplicates to be delivered from server to client, the presence of unique IDs on each message makes eliminating them trivial. Think of the server-side message queue as an event stream, with each client tracking their last-read position. The client makes no guesses about the appropriate order of messages, how many there are, etc - because its state consists entirely of 'what have I seen', there are few opportunities to get out of sync.

Upvotes: 5

Related Questions