What's the best way for the client app to immediately react to an update in the database? What's the best way for the client app to immediately react to an update in the database? database database

What's the best way for the client app to immediately react to an update in the database?


You basically have two issues here:

  1. You want a browser to be able to receive asynchronous events from the web application server without polling in a tight loop.

  2. You want the web application to be able to receive asynchronous events from the database without polling in a tight loop.

For Problem #1

See these wikipedia links for the type of techniques I think you are looking for:

EDIT: 19 Mar 2009 - Just came across ReverseHTTP which might be of interest for Problem #1.

For Problem #2

The solution is going to be specific to which database you are using and probably the database driver your server uses too. For instance, with PostgreSQL you would use LISTEN and NOTIFY. (And at the risk of being down-voted, you'd probably use database triggers to call the NOTIFY command upon changes to the table's data.)

Another possible way to do this is if the database has an interface to create stored procedures or triggers that link to a dynamic library (i.e., a DLL or .so file). Then you could write the server signalling code in C or whatever.

On the same theme, some databases allow you to write stored procedures in languages such as Java, Ruby, Python and others. You might be able to use one of these (instead of something that compiles to a machine code DLL like C does) for the signalling mechanism.

Hope that gives you enough ideas to get started.


I figure there must be some way, after all, web application like gmail seem to update my inbox almost immediately after a new email was sent to me. Surely my client isn't continually checking for updates all the time. I think the way they do this is with AJAX, but how AJAX can behave like a remote function call I don't know. I'd be curious to know how gmail does this, but what I'd most like to know is how to do this in the general case with a database.

Take a peek with wireshark sometime... there's some google traffic going on there quite regularly, it appears.

Depending on your DB, triggers might help. An app I wrote relies on triggers but I use a polling mechanism to actually 'know' that something has changed. Unless you can communicate the change out of the DB, some polling mechanism is necessary, I would say.

Just my two cents.


Well, the best way is a database trigger. Depends on the ability of your DBMS, which you haven't specified, to support them.

Re your edit: The way applications like Gmail do it is, in fact, with AJAX polling. Install the Tamper Data Firefox extension to see it in action. The trick there is to keep your polling query blindingly fast in the "no news" case.