---
source_url: https://www.pubnub.com/docs/design-patterns/show-viewer-count-large-room
title: Show a viewer count for a large live event
description: Show the viewer count of one live event channel to every viewer, with heartbeats and a seeded badge, and no server-side roster.
updated_at: 2026-11-20T09:51:54.000Z
---

# Show a viewer count for a large live event

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

This guide shows you how to show the viewer count of one live event channel to every viewer. The count comes from Presence, so you don't need a server-side roster. Read [Large-room presence for live events](https://www.pubnub.com/docs/design-patterns/large-room-presence.md) first to see what the count can and can't tell you at this size.

Before you start:

* Turn on Presence for the event channel in [Presence Management](https://www.pubnub.com/docs/presence/overview.md#turn-on-presence-without-writing-code).
* Keep **Presence Deltas** off for the keyset. A count-only design doesn't use them.
* Note your keyset's **Announce Max** and **Interval** values. The code needs them.

## Set the heartbeat settings

Each viewer must keep sending heartbeats, or PubNub drops it from the count.

1. Check the **Subscribe heartbeats (implicit)** switch. By default, only explicit heartbeats keep a client present. Subscribe requests count as heartbeats only when the keyset's **Subscribe heartbeats (implicit)** setting is on. The **Subscribe heartbeats (implicit)** setting is under **Channel rules** → **⋯** → **Legacy tracking settings** in the keyset's Presence settings, and it's off on new keysets.
2. Keep the switch off unless some viewers can't send explicit heartbeats. Older software development kit (SDK) versions are the usual case. Turning it on without a reason can delay `timeout` events and add transaction costs.
3. Set `presenceTimeout` and `heartbeatInterval` on every viewer, to matching values. Explicit presence heartbeats are off by default in PubNub SDKs, because `heartbeatInterval` defaults to `0`. PubNub SDKs set `presenceTimeout` to 300 seconds by default, which is how long PubNub waits without a heartbeat before marking a client offline. The code below uses 120 and 59 seconds.
4. Keep `heartbeatInterval` a little under half of `presenceTimeout`, so one lost heartbeat doesn't drop the viewer. Each heartbeat is a billable call to the application programming interface (API). For the recommended values, see [API limits](https://www.pubnub.com/docs/architecture/limits.md#presence).

## Write the viewer code

Store the User ID with the viewer's account or in local storage, and reuse it on every reload. A new User ID on each reload counts the viewer twice until the old ID times out.

Use this code for each viewer. Replace the keyset values in the first two lines, and implement `renderWatching` in your user interface (UI).

```javascript
const ANNOUNCE_MAX = 20;     // match your keyset's Announce Max
const INTERVAL_MS = 10_000;  // match your keyset's interval

const pubnub = new PubNub({
  subscribeKey: 'mySubscribeKey',
  userId: storedUserId,      // the same ID on every reconnect and page reload
  presenceTimeout: 120,
  heartbeatInterval: 59,     // explicit heartbeats keep a subscribed viewer counted
});

const eventChannel = 'live.keynote-2026';
const subscription = pubnub.channel(eventChannel).subscription({ receivePresenceEvents: true });

let watching = null;         // the count on screen
let lastTimetoken = 0n;      // newest event rendered
let lastLiveUpdate = 0;      // when an event last changed the badge
let lastBusySignal = 0;      // when we last learned the room is above Announce Max
let recounting = false;      // a Here Now call is in flight

function show(count) {
  watching = count;
  renderWatching(count);
}

// Ask for a snapshot count, to seed the badge or to check it again.
async function recount() {
  if (recounting) return;
  recounting = true;
  try {
    const askedAt = Date.now();
    const result = await pubnub.hereNow({ channels: [eventChannel], includeUUIDs: false });
    if (lastLiveUpdate < askedAt) {
      const count = result.channels[eventChannel]?.occupancy ?? 0;
      if (count > ANNOUNCE_MAX) lastBusySignal = Date.now();
      show(count);
    }
  } catch {
    // Keep the current badge. With no badge yet, try again after one interval,
    // unless an interval event has filled it by then.
    setTimeout(() => { if (watching === null) recount(); }, INTERVAL_MS);
  } finally {
    recounting = false;
  }
}

subscription.onPresence = (event) => {
  if (event.action === 'state-change') return; // carries no occupancy
  if (event.action === 'interval') {
    lastBusySignal = Date.now();
  } else if (watching === null || watching > ANNOUNCE_MAX) {
    // Individual events carry the room's count only in a small room. If
    // interval events have stopped, ask Here Now rather than trust this event.
    if (watching !== null && Date.now() - lastBusySignal > 2 * INTERVAL_MS) recount();
    return;
  }
  const timetoken = BigInt(event.timetoken);
  if (timetoken < lastTimetoken) return; // arrived out of order
  lastTimetoken = timetoken;
  lastLiveUpdate = Date.now();
  show(event.occupancy);
};
subscription.subscribe();

// Seed the badge so a late joiner doesn't wait for the next interval.
await recount();

// Interval events can stop with no individual event to follow. Once a minute,
// check the count if the badge shows a busy room and no interval has arrived.
setInterval(() => {
  if (watching >= ANNOUNCE_MAX && Date.now() - lastBusySignal > 2 * INTERVAL_MS) recount();
}, 60_000);
```

## Seed the badge

The code makes one count-only `Here Now` call at startup, so a late joiner doesn't wait for the next interval. Every viewer makes this call. At 40,000 viewers, that's up to 40,000 calls in the first minute. To skip that call, delete the `await recount()` line. The badge then fills at the next `interval` event.

## Check the count

1. Compare the badge with the `occupancy` in the next `interval` event. The two should match within one interval.
2. If the badge stays busy after the room drains, wait one minute. The code's once-a-minute check fetches a fresh count. That check costs one `Here Now` call per viewer per minute while `interval` events are missing. At 40,000 viewers, that's about 670 calls a second. Don't check more often than once a minute.

## Related tasks

* [Build a roster for a large live event](https://www.pubnub.com/docs/design-patterns/build-roster-large-room.md). Server-side User ID list when the product needs names.
* [Load test a large live event channel](https://www.pubnub.com/docs/design-patterns/load-test-large-room.md). Simulated viewers that check the count and badge.
* [Presence events](https://www.pubnub.com/docs/presence/presence-events.md). Announce and interval modes, deltas, and heartbeat timing.
* [Large-room presence for live events](https://www.pubnub.com/docs/design-patterns/large-room-presence.md). What the count can and can't tell you at this size.

Last updated at: 2026-11-20T09:51:54.000Z
