Chrysolites Tech Academy

Short-Video App with React Native and Supabase · Course book

Chapter 16: Real-Time Chat

Pairs with Lesson 16: Real-Time Chat with Supabase

Chat is where a social app feels most alive. A message should appear on the other person's screen the instant it is sent, without anyone pulling to refresh, and conversations should be private to the two people in them. This chapter builds real-time chat for the short-video app with Supabase: deciding who may chat, identifying a private conversation with a stable key worked out by hand, storing messages, subscribing to new messages so they arrive instantly, comparing that with polling using a graph of delays, reusing the comment list component for messages, and securing conversations so only their members can read them.

Who can chat, and how conversations are identified

In this app, only friends, people who follow each other, can message one another. That rule keeps unsolicited messages out of people's inboxes and reuses the friendship logic from the follow chapter: the inbox lists the user's friends, and tapping one opens the conversation with them. If one person unfollows the other, they are no longer friends and the chat option disappears, though their earlier messages can remain, readable but closed to new replies.

Each private conversation needs an identifier that both participants can compute independently, so that whoever opens the chat first, they find the same messages. A simple and robust choice is a chat key made from the two user ids in a fixed order: sort them, then join them with a separator.

Worked example. Ana's id begins 7c1e… and Ben's begins 2a9f…. Sorting the two ids as text puts Ben's first, because "2" comes before "7", so the key is 2a9f…_7c1e…. When Ben opens the chat, he sorts the same two ids and gets exactly the same key; without sorting, Ana would compute "Ana_Ben" and Ben "Ben_Ana", and they would never see each other's messages. With n users there are n(n − 1) / 2 possible pairs, 4,950 for 100 users, each with its own unique key.

The alternative is a separate conversations table with a row per conversation and a members table linking users to it, which is the better design for group chats. For one-to-one chat between friends, a computed key avoids an extra table and an extra lookup, and every message row simply stores the key.

The friends list for the inbox comes from the same intersection of following and followers computed in the follow chapter. Each entry can show the friend's picture and name, and, once messages exist, the latest message in the conversation with its relative time, found with a query for the newest row with that chat key. Sorting the inbox by the time of each conversation's latest message, newest first, puts active conversations at the top, which is what people expect.

Storing and sending messages

Messages live in the Chat table: the message text, the sender's user id, the chat key and the creation time. Sending a message is an insert; loading a conversation is a query for rows with that chat key, ordered by time, together with each sender's username and picture.

// send
await supabase.from("Chat").insert({ text, user_id: me, chat_id: chatKey });

// load the most recent 50, newest first
const { data } = await supabase
  .from("Chat")
  .select("*, User(username, profile_photo)")
  .eq("chat_id", chatKey)
  .order("created_at", { ascending: false })
  .limit(50);

An index on chat_id makes loading a conversation fast however many messages the table holds across all users. Loading the newest messages first and displaying the list inverted, so that the newest message sits at the bottom next to the input box, matches how chat apps look, and FlatList's inverted property handles the flipping. Scrolling up then loads older pages. Messages should be trimmed of surrounding spaces and limited in length before sending, and empty messages ignored, so the conversation stays tidy and the table is protected from accidental or deliberate abuse.

Real-time subscriptions

Loading the conversation shows what was already there; new messages need to arrive by themselves. Supabase Realtime lets the app subscribe to changes in a table. The app opens a channel and listens for inserts on the Chat table filtered to this chat key; Supabase pushes each new row to every subscribed app over a persistent WebSocket connection.

useEffect(() => {
  const channel = supabase
    .channel(`chat-${chatKey}`)
    .on("postgres_changes",
        { event: "INSERT", schema: "public", table: "Chat", filter: `chat_id=eq.${chatKey}` },
        (payload) => addMessage(payload.new))
    .subscribe();
  return () => { supabase.removeChannel(channel); };
}, [chatKey]);

The effect subscribes when the chat screen opens and the clean-up function removes the channel when it closes, so the app does not keep listening to conversations nobody is viewing. The table must have real-time updates enabled in the Supabase dashboard, and row level security applies to real-time events too: a user receives only rows they are allowed to read.

The sender's own message arrives through the subscription as well. To avoid showing it twice, the app either relies solely on the subscription to add messages, or adds the message immediately as an optimistic entry and, when the matching row arrives, replaces the temporary entry rather than adding a second copy.

Why push beats polling

Without subscriptions, the app could poll: ask the server for new messages every few seconds. Polling works, but it trades delay against waste. If the app polls every T seconds, a message sent at a random moment waits on average T / 2 seconds before the next poll fetches it, and up to T seconds at worst; meanwhile every poll costs a request, even when nothing has changed.

2.75 s5 s polling: average T / 2 push: about 0.1 s 02.55 15.510 polling interval T (seconds)average delay (seconds)
Figure 16.1 — Average delay before a new message appears. Polling's delay grows with its interval; a push subscription delivers in roughly a network round trip.

The waste adds up too. Polling every 2 seconds sends 30 requests a minute, 1,800 an hour, per open chat, almost all returning nothing; and its average delay is still a full second. A subscription keeps one connection open and sends data only when a message exists, delivering it in roughly the time of a network round trip, often around a tenth of a second. For chat, push is clearly the right design.

ApproachAverage delayRequests per hour per open chatBest for
Polling every 10 s5 s360Rarely updated data
Polling every 2 s1 s1,800Short-lived screens when push is unavailable
Push subscriptionAbout one round tripOne connection, plus one message per eventChat, live counts, presence

Push has costs of its own. Each open connection uses a little server capacity, and connections drop when phones change networks or go to sleep. The client library reconnects automatically, but messages sent while a phone was disconnected arrive through no subscription at all, so when the chat screen returns to the foreground, or the connection is re-established, the app should refetch the latest messages to fill any gap. Combining a subscription for live updates with a fetch on reconnect gives both speed and completeness.

A reusable message component and security

The chat screen looks a lot like the comment section: a list of messages, each with a picture, a name, text and a time, and an input bar at the bottom inside a keyboard-avoiding view. Building one reusable message list component, used by both comments and chat, means fixes and improvements to one benefit the other. Props can switch the small differences: chat aligns the user's own messages to the right in a coloured bubble and other people's to the left, while comments align everything to the left.

Privacy is enforced by the database. A row level security policy on the Chat table should allow a user to read or insert a message only if the chat key contains their own id, and for inserts, only if the sender id is their own. A stricter version also checks that the two users are friends, by looking up the Follower table in the policy, so that the "friends only" rule cannot be bypassed by a modified app, however the requests are crafted. Because Realtime respects the same policies, nobody can subscribe to someone else's conversation either.

Finishing touches make chat feel polished: the inbox shows each conversation's latest message and time; unread messages show a dot until the conversation is opened; the input disables its send button when empty; and a long press on a message could offer to copy or delete it. Each builds on the same table and subscription, so they can be added one at a time. Realtime channels can also carry presence, which tracks who is currently connected, and broadcast messages that are not stored, which suit a "typing…" indicator: a short-lived signal that would be wasteful to save as a row in the database.

Practice tasks

  1. Compute the chat key for users with ids beginning b4 and 9e, using text order. Which comes first, and why?
  2. How many distinct one-to-one conversations are possible among 250 users?
  3. With polling every 4 seconds, what are the average and worst-case delays, and how many requests are made per hour per chat?
  4. Explain why the subscription must be removed when the chat screen closes.
  5. Describe how the app avoids showing the sender's own message twice.
  6. Write in words the policy that lets only the two participants read a conversation.

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.