Supabase Realtime broadcasts PostgreSQL INSERT, UPDATE, and DELETE events over WebSockets. UUID v7 primary keys align naturally with Realtime’s subscription model: the same UUID column used for REST cursor pagination doubles as the Realtime FILTER boundary, and chronological ordering is implicit in the lexicographic sort order. See UUID in Databases for the broader storage context.

PostgreSQL schema with UUID v7 default

-- Enable pg_uuidv7 extension (Supabase dashboard or migration)
CREATE EXTENSION IF NOT EXISTS "pg_uuidv7";

CREATE TABLE messages (
    id         UUID        NOT NULL DEFAULT uuid_generate_v7() PRIMARY KEY,
    channel_id UUID        NOT NULL,
    content    TEXT        NOT NULL,
    user_id    UUID        NOT NULL
);

-- Index for cursor pagination — UUID v7 lexicographic = chronological
CREATE INDEX messages_channel_cursor ON messages (channel_id, id);

Supabase client setup (TypeScript)

import { createClient } from '@supabase/supabase-js';
import { v7 as uuidv7 } from 'uuid';

const supabase = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_ANON_KEY!
);

// Insert with client-generated UUID v7
async function sendMessage(channelId: string, content: string, userId: string) {
  const id = uuidv7(); // UUID v7 — encodes send time
  const { data, error } = await supabase
    .from('messages')
    .insert({ id, channel_id: channelId, content, user_id: userId })
    .select()
    .single();
  if (error) throw error;
  return data;
}

Realtime subscription with UUID v7 FILTER

// Subscribe to messages newer than a cursor UUID v7
function subscribeToMessages(
  channelId: string,
  cursor: string, // UUID v7 from last loaded message
  onMessage: (msg: Message) => void
) {
  return supabase
    .channel(`messages:${channelId}`)
    .on(
      'postgres_changes',
      {
        event: 'INSERT',
        schema: 'public',
        table: 'messages',
        filter: `channel_id=eq.${channelId}`,
      },
      (payload) => {
        const msg = payload.new as Message;
        // UUID v7 lexicographic comparison = chronological filter
        if (msg.id > cursor) {
          onMessage(msg);
        }
      }
    )
    .subscribe();
}

React hook — cursor pagination + Realtime

import { useEffect, useRef, useState } from 'react';

interface Message {
  id: string;
  content: string;
  user_id: string;
}

export function useMessages(channelId: string) {
  const [messages, setMessages] = useState<Message[]>([]);
  const cursorRef = useRef<string>('');

  // Initial page load — cursor pagination with UUID v7
  useEffect(() => {
    async function loadInitial() {
      const { data } = await supabase
        .from('messages')
        .select('id, content, user_id')
        .eq('channel_id', channelId)
        .order('id', { ascending: false }) // UUID v7 = newest first
        .limit(50);
      if (data?.length) {
        setMessages(data.reverse());
        cursorRef.current = data.at(-1)!.id; // latest UUID v7 as cursor
      }
    }
    loadInitial();
  }, [channelId]);

  // Realtime — only messages after cursor
  useEffect(() => {
    if (!cursorRef.current) return;
    const channel = subscribeToMessages(channelId, cursorRef.current, (msg) => {
      setMessages((prev) => [...prev, msg]);
      cursorRef.current = msg.id; // advance cursor
    });
    return () => { supabase.removeChannel(channel); };
  }, [channelId, cursorRef.current]);

  return messages;
}

Load more — older messages

async function loadOlderMessages(channelId: string, beforeCursor: string, limit = 20) {
  const { data } = await supabase
    .from('messages')
    .select('id, content, user_id')
    .eq('channel_id', channelId)
    .lt('id', beforeCursor) // UUID v7: lexicographic < = created before
    .order('id', { ascending: false })
    .limit(limit);
  return (data ?? []).reverse();
}

Svelte store — Realtime messages

// stores/messages.ts
import { writable } from 'svelte/store';

export function createMessageStore(channelId: string) {
  const { subscribe, update } = writable<Message[]>([]);
  let cursor = '';

  async function init() {
    const { data } = await supabase
      .from('messages')
      .select('id, content, user_id')
      .eq('channel_id', channelId)
      .order('id', { ascending: true })
      .limit(50);
    if (data?.length) {
      update(() => data);
      cursor = data.at(-1)!.id;
    }
  }

  const channel = supabase
    .channel(`messages:${channelId}`)
    .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages',
        filter: `channel_id=eq.${channelId}` }, (payload) => {
      const msg = payload.new as Message;
      if (msg.id > cursor) {
        update((msgs) => [...msgs, msg]);
        cursor = msg.id;
      }
    })
    .subscribe();

  init();
  return { subscribe, destroy: () => supabase.removeChannel(channel) };
}

Key patterns

PatternUUID v7 approach
Cursor paginationWHERE id > cursor ORDER BY id — no created_at column
Realtime filterUUID v7 string comparison in payload.new.id > cursor
Chronological sortORDER BY id ASC — implicit from UUID v7 timestamp prefix
Subscribe boundaryPass last UUID v7 from REST response as Realtime cursor

Further reading

External references

Frequently asked questions

How do I filter Supabase Realtime events by UUID v7 range?

Use Supabase Realtime's FILTER option with a UUID comparison: .filter('id', 'gte', cursorUuid). Since UUID v7 is lexicographically ordered, this matches all rows created after the cursor. This replaces a separate created_at >= ? filter — the UUID v7 value encodes both identity and time. See UUID v7 in Drizzle + PostgreSQL for the query layer.

Does Supabase support UUID v7 column defaults?

Supabase runs PostgreSQL 15+. You can add a UUID v7 default with the pg_uuidv7 extension or a custom SQL function. In the Supabase dashboard, run: CREATE EXTENSION IF NOT EXISTS "pg_uuidv7"; then set the column default to uuid_generate_v7(). Alternatively, generate UUID v7 on the client with the uuidv7 npm package and insert the value explicitly. See UUID v7 in Prisma + PostgreSQL.

How does UUID v7 improve Supabase cursor pagination with Realtime?

With UUID v4 primary keys, cursor pagination requires a secondary ORDER BY created_at, id sort to ensure stable ordering across concurrent inserts. UUID v7 eliminates this: ORDER BY id is chronological. The cursor from the last REST response can be passed directly to the Realtime FILTER to subscribe only to rows newer than the cursor, with no timestamp column involved. See UUID v7 for Cursor Pagination.