Question: I'm developing a messaging system and I would like to display when a user is typing or not. How I figured I would do it is just have a table in my database called "typing" with the columns for who is typing and who they're typing to and the time. Every time they press a key in the input field I would post to the database (seems like this would slow the site down though). Then I'd run some javascript that checks if the column in the typing field is older than 5 seconds, if not then I display the message, if it is then I remove it.

This seems to be a pretty straight-forward way to do it, but I was wondering if there is a better option. I am uncomfortable with such frequent posts to the database. So does anyone know a better way this can be accomplished? Any help is appreciated, thank you.

Answer: 
Why don't we shift your thinking a little. Put the burden on the client, not the server, for the typing.

After the *first* keypress, send an event to the server, and start a timeout. After 5 seconds, we will say we aren't typing any more. If there is another keypress, we erase the old timeout, and start a new one. This will ensure that anytime a user is typing consistently, it is updated.

If your user reloads or leaves the page is the problem. Then they aren't typing, but the timeout won't trigger. To handle this, I would recommend that you do two things. First, when the user requests a new page, always put their status to `not-typing`. Why? because at the very least, at that second, they are not typing even if they are opening up a new tab. Secondly, if the user leaves the browser and closes before the stopped typing trigger, you'll want to clean those up eventually. You could probably have a cron run every hour and any that are older than 5 minutes yet say they are still typing, set to not typing.
you could offload the typing state to something like memcache or redis as it doesn't matter if you lose the typing state for a user. and as you only need to read the value to tell others if the user was typing in the last 5 seconds.