tutorial··5 min read·WoWSQL Team

How to Build Typing Indicators and Online Presence

Build typing indicators and online presence over WebSockets: throttled broadcasts, timeouts, multi-tab merging, away status and why presence is a hint.

To build a typing indicator, send a tiny ephemeral "typing" message over a WebSocket channel when the user starts typing, re-send it at most every few seconds while they keep going, send "stopped" when they pause, and let receivers expire it on a timer in case "stopped" never arrives. Online presence works the same way: each connection announces itself on the channel and the server removes it when the socket closes. WoWSQL Realtime gives you both (broadcast and presence on any channel, no database table needed) on every plan from $0, and this guide covers the details that make them feel right: multiple tabs, away status, crashes, spoofing and message cost.

How we tested: presence.ts below type-checks under TypeScript strict mode with @wowsql/sdk 3.10.0, and we ran it on 2 December 2026 against a local stand-in for the WoWSQL Realtime server that we wrote to follow the protocol in WoWSQL's realtime service code (presence keyed by connection, broadcasts echoed to the sender, presence removed when a socket closes). It is our reimplementation, not WoWSQL's service, so test against your own project before you ship.

Key facts

  • Typing is a broadcast, presence is state. Broadcasts are fire-and-forget messages to everyone on the channel; presence is a per-connection record the server keeps and re-sends to anyone who joins.
  • WoWSQL Realtime: wss://<project>.wowsqlconnect.com/realtime/v1/websocket, using the same anon or service key as REST. Broadcast and presence "do not need a Postgres trigger" and payloads are capped at 64 KiB (Realtime docs). Channel names allow letters, digits and _ . : -, up to 128 characters.
  • Presence is per connection. One user with three tabs is three presence entries; merge them by user ID yourself.
  • Presence is self-declared. Anyone holding the anon key can join a channel and track any payload, so check claimed user IDs against data you loaded through Row Level Security.
  • Timings we use: re-announce typing at most every 3 s, send "stopped" after 4 s without a keystroke, expire a remote typer after 6 s with no refresh. In our test, 20 keystrokes in one second produced 1 message on the wire.
  • Plans (pricing): Realtime APIs on Free $0, Pro $25/month and Scale $99/month. Regions: Mumbai, US East and Frankfurt.

The design in one picture

Alice types ─┬─ first keystroke ────────► broadcast {user_id, typing:true}
             ├─ keeps typing 3 s ───────► broadcast {user_id, typing:true}   (refresh)
             └─ 4 s with no keystroke ──► broadcast {user_id, typing:false}

Bob's client: show "Alice is typing…" on true, hide on false,
              and hide anyway 6 s after the last true (crash, lost message)

Each tab:    track({ user_id, status: 'online' | 'away' })   → server keeps it
Socket closes → server drops that connection's presence → everyone gets a leave

Three rules come out of this:

  • Never send a message per keystroke. It multiplies by every listener in the room. A 3-second refresh keeps the indicator alive with a handful of messages a minute.
  • Receivers own the timeout. The sender's "stopped" message is an optimisation; the 6-second expiry is what guarantees a dead indicator disappears.
  • Show names from your database, not the payload. The payload carries only a user ID and a boolean; the display name comes from the room members you loaded through RLS.

Broadcast vs presence: which to use

Use broadcast for Use presence for
Typing, cursor positions, "someone reacted" Who is in the room, online or away, which page they're on
Events that are useless a few seconds later State a newcomer needs to see as soon as they join
Anything that changes several times a second Anything that changes a few times a minute at most

A newcomer doesn't get past broadcasts, but does get the current presence state on joining. That's why "Alice is typing" is a broadcast with a timer, and "Alice is online" is presence.

Step 1: Load the room members through RLS

Presence and typing are only as trustworthy as the list you check them against. Load the room's members with the signed-in user's token so Row Level Security decides who is in the room. If you followed our chat app guide, that is the room_members table joined to profiles; any query that returns { user_id, name } for the room works. Keep it in a Map keyed by user ID and pass it to joinRoom() below.

Step 2: Typing and online status in one module

// presence.ts: typing indicators and an online list for one room (@wowsql/sdk 3.10.0)
import { WowSQLClient } from '@wowsql/sdk'

export type Member = { user_id: string; name: string }
export type Status = 'online' | 'away'
export type OnlineUser = Member & { status: Status; tabs: number }

const TYPING_REFRESH_MS = 3000 // while typing, re-announce at most every 3 s
const TYPING_IDLE_MS = 4000    // no keystroke for 4 s: send "stopped"
const TYPING_EXPIRE_MS = 6000  // receiver gives up if no refresh arrives (sender crashed, lost packet)

export function joinRoom(opts: {
  db: WowSQLClient
  roomId: string
  me: Member
  members: Map<string, Member> // the room's real members, loaded through RLS
  status?: Status
  onTyping: (names: string[]) => void
  onOnline: (users: OnlineUser[]) => void
}) {
  const { db, me, members } = opts
  const channel = db.realtime.channel(`room:${opts.roomId}`)

  // ---------- who is typing (incoming) ----------
  const typers = new Map<string, ReturnType<typeof setTimeout>>()
  const publishTyping = () => opts.onTyping([...typers.keys()].map((id) => members.get(id)!.name))
  const clearTyper = (id: string) => {
    const timer = typers.get(id)
    if (timer === undefined) return
    clearTimeout(timer)
    typers.delete(id)
    publishTyping()
  }

  // ---------- who is online ----------
  const publishOnline = () => {
    const byUser = new Map<string, OnlineUser>()
    // presenceState() has one entry per connection, so a user with 3 tabs appears 3 times
    for (const p of Object.values(channel.presenceState()) as Array<{ user_id?: string; status?: Status }>) {
      const member = p?.user_id ? members.get(p.user_id) : undefined
      if (!member) continue // not in this room: ignore whatever they claim
      const prev = byUser.get(member.user_id)
      const status: Status = prev?.status === 'online' || p.status === 'online' ? 'online' : 'away'
      byUser.set(member.user_id, { ...member, status, tabs: (prev?.tabs ?? 0) + 1 })
    }
    for (const id of [...typers.keys()]) if (!byUser.has(id)) clearTyper(id) // gone: stop "typing…"
    opts.onOnline([...byUser.values()])
  }

  channel
    .on('broadcast', { event: 'typing' }, ({ payload }) => {
      const { user_id, typing } = payload as { user_id?: string; typing?: boolean }
      // Skip our own echo (other tabs of the same user included) and non-members
      if (!user_id || user_id === me.user_id || !members.has(user_id)) return
      if (!typing) return clearTyper(user_id)
      clearTimeout(typers.get(user_id))
      typers.set(user_id, setTimeout(() => clearTyper(user_id), TYPING_EXPIRE_MS))
      publishTyping()
    })
    .on('presence', { event: '*' }, publishOnline)
    .subscribe(async () => {
      await channel.track({ user_id: me.user_id, status: opts.status ?? 'online' })
    })

  // ---------- my typing (outgoing) ----------
  let typing = false
  let lastSent = 0
  let idle: ReturnType<typeof setTimeout> | undefined
  const sendTyping = (value: boolean) =>
    void channel.send({ type: 'broadcast', event: 'typing', payload: { user_id: me.user_id, typing: value } })

  function stopped() {
    clearTimeout(idle)
    if (!typing) return
    typing = false
    sendTyping(false)
  }

  return {
    /** Call on every input event. Sends at most one message per 3 s. */
    keystroke() {
      const now = Date.now()
      if (!typing || now - lastSent >= TYPING_REFRESH_MS) {
        sendTyping(true)
        typing = true
        lastSent = now
      }
      clearTimeout(idle)
      idle = setTimeout(stopped, TYPING_IDLE_MS)
    },
    /** Call when the message is sent, the input is cleared or loses focus. */
    stopped,
    /** 'away' when the tab is hidden, 'online' when it's visible again. */
    setStatus(status: Status) {
      void channel.track({ user_id: me.user_id, status })
    },
    async leave() {
      stopped()
      for (const id of [...typers.keys()]) clearTyper(id)
      await channel.untrack()
      await channel.unsubscribe()
    },
  }
}

What the module does:

  • Typing out: keystroke() sends typing: true on the first keystroke and then at most once every 3 seconds, and schedules stopped() 4 seconds after the last keystroke. Call stopped() yourself when the message is sent or the input loses focus.
  • Typing in: each remote typer gets a 6-second timer that a refresh resets. Messages from your own user ID are skipped, which also hides the echo from your other tabs (WoWSQL echoes broadcasts back to the sender).
  • Online list: presenceState() returns one entry per connection. The module ignores entries whose user_id isn't a room member, merges tabs by user ID, counts them, and shows a user as online if any tab is visible.
  • Cleanup: when someone disappears from presence, their typing indicator is cleared immediately rather than waiting for the timer.

Step 3: Wire it to the page

// browser.ts: wiring it to a page (illustrative; renderTyping/renderOnline are yours)
import { WowSQLClient } from '@wowsql/sdk'
import { joinRoom, type Member, type OnlineUser } from './presence.ts'

declare const me: Member, roomId: string, members: Map<string, Member>
declare const input: HTMLInputElement, form: HTMLFormElement
declare function renderTyping(text: string): void
declare function renderOnline(users: OnlineUser[]): void

const db = new WowSQLClient({ projectUrl: 'https://myproject.wowsqlconnect.com', apiKey: 'wowsql_anon_your_key_here' })

const room = joinRoom({
  db, roomId, me, members,
  status: document.hidden ? 'away' : 'online',
  onTyping: (names) =>
    renderTyping(names.length === 0 ? '' : names.length === 1 ? `${names[0]} is typing…` : `${names.length} people are typing…`),
  onOnline: renderOnline,
})

input.addEventListener('input', () => (input.value ? room.keystroke() : room.stopped()))
input.addEventListener('blur', () => room.stopped())
form.addEventListener('submit', () => room.stopped())
document.addEventListener('visibilitychange', () => room.setStatus(document.hidden ? 'away' : 'online'))
window.addEventListener('pagehide', () => void room.leave())

visibilitychange flips the tab between online and away, and pagehide leaves cleanly when the tab closes. If the browser is killed instead, the WebSocket closes and the server drops that connection's presence for you.

What our test run showed

Scenario Bob's view
Alice opens two tabs Alice: online, 2 tabs (one row, not two)
A non-member joins and tracks u-eve Ignored
Alice types 20 keystrokes in 1 second "Alice is typing…"; 1 typing message on the wire
Alice stops for 4 seconds Indicator cleared; 2 messages in total (start and stop)
Alice hides one tab Still online (the other tab is visible)
Alice hides both tabs Alice: away, 2 tabs
Alice's typing tab is closed mid-sentence Alice: away, 1 tab; the indicator stays until the 6-second expiry because Alice is still present in her other tab
Alice's last tab leaves Alice removed from the list, indicator cleared
Another client tracks user_id: 'u-bob' Bob: online, 2 tabs

The last row is the important caveat: presence payloads are self-declared, so membership checks stop strangers but can't stop one signed-in member pretending to be another. Treat presence as a hint for the UI. For anything that matters, such as "who read this message", write to a table with RLS instead.

Reconnects, crashes and scale

  • Reconnects: the SDK reconnects with exponential backoff (1 second, doubling up to 30 seconds) and, in the 3.10.0 source, re-joins channels and re-sends your last tracked presence. It does not rerun your subscribe callback, so don't put essential setup there beyond the first track().
  • Server side: in WoWSQL's realtime service code a connection's presence is removed when its socket closes, the server sends a heartbeat every 30 seconds and refreshes the connection's presence, and multi-replica deployments share presence through Redis with a TTL (90 seconds by default). We haven't measured how quickly a silently dropped mobile connection disappears on the hosted service, so don't promise users second-accurate "last seen" from presence alone.
  • Message cost: every broadcast is delivered to every connection on the channel. As an illustration, someone typing for 30 seconds in a room with 50 open connections sends about 11 messages with this module (about 550 deliveries); sending one per keystroke at five keys a second would be 150 messages and 7,500 deliveries.
  • Privacy: channel names aren't secret and channels aren't authorised per room in WoWSQL today, so keep payloads to IDs and booleans. Never put message text or email addresses in a typing or presence payload.

Presence options compared

Checked 2 December 2026. Sources: WoWSQL Realtime docs, Supabase Presence, Supabase Realtime limits, Supabase Realtime authorization, Ably presence, Pusher presence channels.

WoWSQL Realtime Supabase Realtime Ably Pusher Channels
Who can join a presence channel Anyone with the project's anon or service key Can be restricted with RLS policies on realtime.messages Clients with a token or key; identity is the clientId Only users your auth endpoint authorises
Identity in presence Whatever the client tracks Whatever the client tracks (key is configurable) clientId, tied to the token User ID and info set by your server
Same user, several tabs One entry per connection One key per client by default (a server-generated UUID); you can supply your own key Present once per connection (same clientId, different connectionId) member_added on the first tab only, member_removed after the last
Abrupt disconnect Removed when the socket closes Leave event when a client disconnects or untracks Treated as a leave after 15 s without resuming Removed when the last connection closes
Size limits Payload up to 64 KiB 10 presence keys per object; Free plan 20 presence messages/s and 200 concurrent connections 200 members by default, up to 20,000 with server-side batching depending on package 100 members, 1 KB user object
High-frequency updates Use broadcast Docs say presence "is not designed for high-frequency updates"; use broadcast Batching recommended for busy channels Client events between subscribers
Bundled with a Postgres backend Yes Yes No No

Where others are better: Supabase can authorise who joins a channel with RLS policies, and Pusher and Ably tie presence to a server-issued identity, so a member can't impersonate another member there. WoWSQL Realtime has neither today, which is why the module above checks membership itself and treats presence as a UI hint. Ably also handles very large presence sets with batching. WoWSQL's advantage is that typing and presence sit in the same project as your Postgres database, auth and REST API, starting on the free plan.

Related guides

FAQ

How do I build a "user is typing" indicator?

Broadcast a small { user_id, typing: true } message on the conversation's channel when the user starts typing, refresh it every few seconds while they type, send typing: false after a short pause, and have receivers hide the indicator a few seconds after the last refresh.

How often should a typing indicator send updates?

Not on every keystroke. Sending at most once every 2 to 3 seconds while typing, plus one "stopped" message, keeps the indicator responsive and the message count low. Receivers should expire it after about twice the refresh interval.

How do I show who is online in my app?

Have each connection track a presence record on a channel, then group the presence state by user ID to merge tabs and devices. Show a user as online if any of their connections is active and away if all are hidden.

Should I store typing status or presence in the database?

No. Both change every few seconds and are useless a minute later, so send them over a realtime channel and keep nothing. Store things you need later, such as last-read message IDs, in a table with RLS.

How do I stop users faking their presence?

Ignore presence entries whose user ID isn't a member you loaded through RLS. On services that tie presence to a server-issued identity (Ably, Pusher, Supabase with channel authorization) you can go further; on WoWSQL today, treat presence as a UI hint.

What is the best realtime service for typing indicators and presence?

If you already need a Postgres backend, use the realtime layer that comes with it (WoWSQL or Supabase) so auth and data stay in one place. For huge presence sets or strict server-side identity, a dedicated service like Ably or Pusher is stronger.

Create a free WoWSQL project · Realtime docs · TypeScript SDK docs