You can create a trigger in the table (creates / updates / deletes) that triggers a notification on the βchannelβ, and you can listen to the specified channel for events. I use socketcluster, listen from workers and pass them to consumers (browsers and mobile applications).
First you create a trigger:
CREATE FUNCTION deletes_notify_trigger() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE BEGIN PERFORM pg_notify('deletes_channel', ('DELETED' || ';;' || OLD.id )::text ); RETURN new; END; $$;
and
CREATE TRIGGER deletes_trigger AFTER DELETE ON events FOR EACH ROW EXECUTE PROCEDURE deletes_notify_trigger();
In the transmitted data packets you can add whatever you want, in my case I only need the identifier of the record. To create and update, you can send the full row or only some selected columns. You can also send it as JSON in PG 9.2 (I think) and above. I use 9.1, so I agree with ;; separators.
Make sure that your code takes no more than 10% of the time between your requests, otherwise if you perform complex joins or updates or other operations, you will notice a significant decrease in performance. You want it to be as simple and fast as possible, save it to the basic operations and do any heavy lifting at the application level.
Then the observer and translation for consumers (in my case node, socketcluster and pg gem, in your case you can use JS, Python, Ruby, whatever you like)
var global_deletes = socket.subscribe('deletes_channel'); pg.connect(connectionString, function(err, client) { client.on('notification', function(dbmsg) { console.log(dbmsg.payload); var payload = dbmsg.payload.split(";;"); // you can use JSON instead if (payload[0] == "DELETED") { // when a DELETE is received... global_deletes.publish(dbmsg.payload); var tchannel = socket.subscribe('events-'+ payload[1]); // join the channel we want to broadcast setTimeout( () => tchannel.publish(dbmsg.payload), 50); // send the update to all consumers setTimeout( () => tchannel.unsubscribe(), 100); } ); var query = client.query("LISTEN deletes_channel"); // turn on notifications from the server });