As I work on building a website that includes a feature for real-time chatting between users (similar to Facebook chat), I have implemented a system where messages are stored in a MySQL table called messages
. This table contains the message ID, sender ID, receiver ID, and timestamp.
For retrieving messages between two users, user A and user B, I use the SQL statement:
SELECT * FROM messages WHERE (senderID='userA' AND receiverID='userB') OR (senderId='userB' AND receiverID='userA')
. This query fetches all the messages exchanged between the two users.
When the chat window is open, an AJAX request is sent every second to check for any new messages between the users in the database. However, I am unsure if this frequency of requests is optimal given a large number of messages in the database.
I have the following questions:
- How resource-intensive is it for the database to execute this SQL statement at regular intervals when there is a high volume of data?
- Is my current approach adequate for handling thousands of requests per minute?
- Are there any more efficient methods for determining if a new message has been sent from user A to user B and displaying it instantly in the chat window?