I am developing a website which, among other things, allows users to chat in real time with one another (similar to Facebook chat). Messages are stored in MySQL table messages
, which contains ID of the message, sender ID, receiver ID and time.
When user A is chatting with user B, I get all their messages by SQL statement SELECT * FROM messages WHERE (senderID='userA' AND receiverID='userB') OR (senderId='userB' AND receiverID='userA')
. This statement retrieves all the messages between user A and user B.
When chat is opened, I send an AJAX request every second (should it be less/more?) to check if there are any new messages between these two users in the database.
My questions are:
- How demanding is it for database to run that kind of SQL statement every X seconds when there are a lot of messages in the database?
- Is my approach good enough if there are thousands of requests made every minute?
- Is there any better/faster way of determining if user A sent a new message to user B and then displaying it in the chat window?