Presence enables you to track the online and offline status of users and devices in realtime, as well as store custom state information. Some examples of custom state information include user information (username, location, avatar, etc.), inventory stock of a product, latest bid price for an auction, position of cursors in a collaborative document, location of a package being delivered, sensor readings from a phone’s gyroscope, or the temperature of a thermostat.
PubNub automatically creates a ‘presence channel’ for each channel. This ‘sister’ presence channel is the name of the original channel with ‘-pnpres’ appended to the the name. For example, the presence channel for the channel ‘myChatRoom’ is ‘myChatRoom-pnpres’. Presence exists for channel groups as well; if the channel group is ‘myChannelGroup’, the presence channel group becomes ‘myChannelGroup-pnpres’. Subscribing to a presence channel group (e.g. ‘myChannelGroup-pnpres’) will return the presence events for every channel in the original channel group.
Subscribing to a presence channel or presence channel group will only return presence events, never the original published messages (for that you must subscribe to the original channel or channel group directly).
There are numerous presence events we monitor: join, leave, timeout, state-change, and channel active/inactive.
All presence events are published to the presence channel as soon as the event occurs. However, if a channel has reached the Presence Announce Max number subscribers, then join, leave, and timeout events will no longer be fired. Instead, an occupancy count is sent every 10 seconds by default. Both the occupancy count interval and Presence Announce Max are configurable properties in your account dashboard. The upper limit for Presence Announce Max is 100; please contact support if you wish to raise this limit – do keep in mind, however, larger limits are quick to incur a heavy message count.
Webhooks are available for every presence event, and are especially useful in decreasing subscribe message usage, as well as in certain design patterns. For instance, webhooks can be utilized for easily persisting messages to your own backend database, depending on the use case:
Alternatively, you could create an after publish block that directly stores each message in your database, saving you from making history calls. Keep in mind that webhooks are also subject to the Presence Announce Max limit.
Presence also includes additional functions for ad-hoc presence information:
History can be called on presence channels for auditing purposes, to see who was online a month ago, which users were active, custom state information at a particular time, etc.
For further learning, please see: