Realtime Engine: Postgres Changes, Broadcast & Presence

Realtime Engine: Postgres Changes, Broadcast & Presence in Supabase: Modern real-time applications require instant synchronization across clients.

Modern real-time applications require instant synchronization across clients. Supabase Realtime provides three distinct messaging paradigms through a unified WebSocket connection:

  1. Postgres Changes: Synchronizing database mutations (INSERT, UPDATE, DELETE) from the database write-ahead log directly to clients.
  2. Broadcast: Low-latency, client-to-client messaging that bypasses the database completely (cursor tracking, collaborative drawing).
  3. Presence: Stateful synchronization of online user rosters, typing indicators, and room membership.

Paradigm 1: Listening to Database Mutations (Postgres Changes)

To stream changes from a table, you must add the table to the supabase_realtime publication:

-- Enable Realtime publication for the table in SQL
ALTER PUBLICATION supabase_realtime ADD TABLE public.chat_messages;

Then subscribe via the client SDK:

import { supabase } from '@/lib/supabase';

const channel = supabase
  .channel('realtime:chat_messages')
  .on(
    'postgres_changes',
    {
      event: 'INSERT', // 'INSERT' | 'UPDATE' | 'DELETE' | '*'
      schema: 'public',
      table: 'chat_messages',
      filter: 'room_id=eq.lobby_main' // Column-level filter
    },
    (payload) => {
      console.log('New message received in real-time:', payload.new);
      appendMessageToUI(payload.new);
    }
  )
  .subscribe((status) => {
    if (status === 'SUBSCRIBED') {
      console.log('Successfully subscribed to chat changes!');
    }
  });

// Always unsubscribe when component unmounts in React:
// return () => { supabase.removeChannel(channel); };

Paradigm 2: Ephemeral Broadcast (Sub-50ms Latency)

Broadcast does not touch the database or write to disk. It acts as an ultra-fast publish-subscribe bus between clients in a channel:

const collabChannel = supabase.channel('document:450');

collabChannel
  .on('broadcast', { event: 'cursor-movement' }, ({ payload }) => {
    renderCursor(payload.userId, payload.x, payload.y);
  })
  .subscribe();

// Emitting high-frequency cursor coordinates
function onMouseMove(e: MouseEvent) {
  collabChannel.send({
    type: 'broadcast',
    event: 'cursor-movement',
    payload: { userId: currentUserId, x: e.clientX, y: e.clientY }
  });
}

Paradigm 3: Presence (Tracking Online Users)

Presence manages the state of users connected to a channel, handling disconnects automatically:

const presenceChannel = supabase.channel('room:meeting');

presenceChannel
  .on('presence', { event: 'sync' }, () => {
    const newState = presenceChannel.presenceState();
    console.log('Current online users:', newState);
  })
  .on('presence', { event: 'join' }, ({ key, newPresences }) => {
    console.log('User joined room:', key, newPresences);
  })
  .on('presence', { event: 'leave' }, ({ key, leftPresences }) => {
    console.log('User left room:', key, leftPresences);
  })
  .subscribe(async (status) => {
    if (status === 'SUBSCRIBED') {
      await presenceChannel.track({
        user_id: user.id,
        online_at: new Date().toISOString(),
        device: 'desktop'
      });
    }
  });

Exercises

  1. Build a real-time notification listener filtering alerts where recipient_id=eq.<user_id>.
  2. Implement a multi-user typing indicator using Broadcast events with automatic timeout debouncing.
  3. Explain why storing ephemeral mouse coordinates in a PostgreSQL table instead of using Broadcast degrades database performance.