Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

edits

Copple82134da74126
diff --git a/apps/www/_blog/2022-08-18-supabase-realtime-multiplayer-general-availability.mdx b/apps/www/_blog/2022-08-18-supabase-realtime-multiplayer-general-availability.mdx
index bfd89435396..11a7d383f18 100644
--- a/apps/www/_blog/2022-08-18-supabase-realtime-multiplayer-general-availability.mdx
+++ b/apps/www/_blog/2022-08-18-supabase-realtime-multiplayer-general-availability.mdx
@@ -27,20 +27,21 @@ Here are the key takeaways:
## Background
-Before we discuss the new features, let's review what Supabase Realtime is and its significance to Supabase. Skip ahead if you just want to see the new features!
+Before we discuss the new features, let's review what Realtime is and its significance to Supabase. Skip ahead if you just want to see the new features!
-The first iteration of Supabase Realtime server was written by [@kiwicopple](https://twitter.com/kiwicopple), our CEO. At his previous startup, a chat application he built was facing performance issues while broadcasting database changes from Firestore to individual subscribers.
+The first iteration of Realtime server was written by [@kiwicopple](https://twitter.com/kiwicopple), our CEO. At his previous startup, a chat application he built was facing performance issues while broadcasting database changes from Firestore to individual subscribers.
He turned to Postgres, which has two built-in pieces of functionality for emitting database changes:
- The first, Postgres's LISTEN/NOTIFY, seems like the obvious choice because it conveniently does what its name implies, listen for changes and notify subscribers. However, this approach has a hidden limitation - NOTIFY has a payload limit of 8,000 bytes. The workaround is to send only a unique identifier and then have the client query the database for the specific change. This would have been been too slow for the chat application.
- The second, Postgres's logical replication, doesn't face the same limitations, and Paul used this approach. This required the introduction of a server to listen to a logical replication slot. Paul chose [Elixir](https://elixir-lang.org) and the [Phoenix Framework](https://www.phoenixframework.org) for the server as it scales exceptionally well, especially when dealing with WebSockets. He named this server "[Realtime](https://github.com/supabase/realtime)," leveraging other open source projects, [cainophile](https://github.com/cainophile/cainophile) and [pgoutput_decoder](https://github.com/cainophile/pgoutput_decoder), to listen to the replication stream and decode changes. From there, the changes were serialized into JSON and sent on their merry way to clients.
-Supabase Realtime was the very first open source project of Supabase and played a pivotal role in our founding. Over time, we've improved both the performance and security. During Launch Week 3, we announced [Supabase Realtime RLS](https://supabase.com/blog/realtime-row-level-security-in-postgresql), which allows developers to tap into Postgres's Row Level Security to authorize changes before broadcasting them to clients. This enabled developers to use the same security framework across the entire Supabase stack.
+Realtime was the very first open source project of Supabase and played a pivotal role in our founding. Over time, we've improved both the performance and security.
+During Launch Week 3, we announced [Realtime RLS](https://supabase.com/blog/realtime-row-level-security-in-postgresql), which allows developers to tap into Postgres's Row Level Security to authorize changes before broadcasting them to clients. This enabled developers to use the same security framework across the entire Supabase stack.
## Realtime Channels
-In this Launch Week, we've modified the architecture of Realtime to introduce two core features: Broadcast and Presence.
+We've modified the architecture of Realtime to introduce two core features: Broadcast and Presence.
In this new version, everything is a [Channel](https://phoenixframework.readme.io/docs/channels). Channels are like “Rooms” where participants can join, and leave - very similar to Slack Channels or Discord Channels.
@@ -52,9 +53,10 @@ Broadcast follows the classic Publisher/Subscriber pattern. A client (publisher)
Other clients (subscribers) can “listen” to these messages in real-time, using the unique identifier. If they are listening to the `#random` channel, then they will receive the message.
-This functionality is [baked into the Phoenix framework](https://phoenixframework.readme.io/docs/channels) and we've already been using this to [broadcast Postgres changes](https://supabase.com/docs/reference/javascript/subscribe). We're now exposing the underlying primitives which unlocks a variety of use-cases for developers.
+This functionality is [baked into the Phoenix framework](https://phoenixframework.readme.io/docs/channels) and we've already been using this to [broadcast Postgres changes](https://supabase.com/docs/reference/javascript/subscribe).
+With this release we're exposing the underlying primitives which unlocks a variety of use-cases for developers.
-One common use-case is sharing a user's cursor position with other clients in an online game. Previously, developers were sending all the mouse movements through their Supabase database which added latency and degraded database performance. In contrast, Broadcasts are ephemeral - they bypass the database completely.
+A common use-case is sharing a user's cursor position with other clients in an online game. Previously, developers were sending all the mouse movements through their Postgres database which added latency and degraded database performance. In contrast, Broadcasts are ephemeral - they bypass the database completely.
### Presence
@@ -62,13 +64,14 @@ Presence synchronizes shared state between users. Presence is very similar to Br
Presence utilizes Broadcast as the transport layer, consolidating the state in an eventually-consistent and conflict-free manner. Users are free to come-and-go as they please, and as long as they are all subscribed to the same Channel then they will all have the same Presence state as each other.
-The neat thing about Presence is that if a user is suddenly disconnected (for example, they go offline), then their state will be automatically removed from the shared state. If you've ever tried to re-create an “I'm online” feature which handles unexpected disconnects, you'll appreciate how useful this is.
+The neat thing about Presence is that if a user is suddenly disconnected (for example, they go offline), their state will be automatically removed from the shared state.
+If you've ever tried to build an “I'm online” feature which handles unexpected disconnects, you'll appreciate how useful this is.
## Client Library
-We have introduced the new functionality into the [release candidate](https://supabase.com/blog/supabase-js-v2) version of `supabase-js`. This includes an entirely new client API that deviates from the existing way that developers integrate with Supabase Realtime.
+We've introduced new functionality into the [release candidate](https://supabase.com/blog/supabase-js-v2) version of `supabase-js`.
-Here's just a taste of how you can start using Broadcast and Presence and continue to listen to Postgres changes.
+Here's a taste of how you can start using Broadcast and Presence and continue to listen to Postgres changes.
### Broadcast Example
@@ -90,14 +93,16 @@ channel
// Handle a mouse event.
const receivedCursorPosition({ event, payload }) => {
- console.log('User:', payload.userId)
- console.log('x Position:', payload.x)
- console.log('y Position:', payload.y)
+ console.log(`
+ User: ${payload.userId}
+ x Position: ${payload.x}
+ y Position: ${payload.y}
+ `)
}
// Helper function for sending our own mouse position.
const sendMousePosition(channel, userId, x, y) => {
- channel.send({
+ return channel.send({
type: 'broadcast',
event: MOUSE_EVENT,
payload: { userId, x, y }
@@ -108,39 +113,37 @@ const sendMousePosition(channel, userId, x, y) => {
### Presence Example
-Let's create a contrived example where we could display a “user is typing” indicator. In this case, we'll send the timestamp for the last time that a user hit a key, and then other clients can use this timestamp to display a “typing…” indicator for up to 3 seconds.
+Let's create a contrived example where we could display a “user is typing” indicator.
+In this case, we'll send the timestamp for the last time that a user hit a key.
+Other clients can use this timestamp to display a “typing…” indicator.
```js
const userId = 'user_1234'
const slackRoomId = '#random'
const channel = supabase.channel(slackRoomId, {
- config: { presence: { key: userId } }
+ config: {
+ presence: { key: userId }
+ }
})
-/*
- 'sync' event callback is not called with any
- arguments.
-
- Can use channel.presenceState() to get the
- synced state.
-*/
+// We can subscribe to all Presence changes using the 'presence' -> 'sync' event.
channel
-.on('presence', { event: 'sync' }, () => presenceChanged())
-.subscribe()
+ .on('presence', { event: 'sync' }, () => presenceChanged())
+ .subscribe()
/*
A contrived example where we bind to all keyboard
events and send them over our channel
*/
document.addEventListener('keydown', function(event){
- channel.track({ isTyping: Date.now() })
+ channel.track({ isTyping: Date.now() })
})
// Receive Presence updates
const presenceChanged = () => {
- const newState = channel.presenceState()
- console.log(newState)
+ const newState = channel.presenceState()
+ console.log(newState)
}
// When you no longer wish to track data
@@ -156,57 +159,55 @@ const channelId = '#random'
// Create a filter only for new messages
const databaseFilter = {
- schema: 'public',
- table: 'messages',
- event: 'INSERT'
+ schema: 'public',
+ table: 'messages',
+ filter: `room_id=eq.${channelId}`,
+ event: 'INSERT',
}
-const channel =
- supabase
+const channel = supabase
.channel(channelId)
- .on(
- 'postgres_changes',
- databaseFilter,
- payload => receivedDatabaseEvent(payload))
+ .on('postgres_changes', databaseFilter, (payload) => receivedDatabaseEvent(payload))
.subscribe()
-const receivedDatabaseEvent => (event) {
- const { payload } = event
- console.log(payload)
+const receivedDatabaseEvent = (event) => {
+ const { payload } = event
+ console.log(payload)
}
```
## Future Plans
-This is a big change, but it's just a small step towards the final goal. We have a few exciting plans for the future.
+This is a big change, but it's only a small step towards the final goal. We have a few exciting plans for the future.
### Extensions
-Our `postgres_changes` listener is the first of many [Extensions](https://supabase.com/blog/supabase-realtime-with-multiplayer-features#extensions). We've had requests to extend this interface with a few other integrations beyond Postgres:
+Our `postgres_changes` listener is the first of many [Extensions](https://supabase.com/blog/supabase-realtime-with-multiplayer-features#extensions).
+We've had requests add other integrations beyond Postgres:
-- **Finance:** Listen to stock market events and broadcast them to connected users.
-- **Web3:** Listen to blockchain events and broadcast them to connected users.
-- **Authoritative clocks:** A server clock which broadcasts a timer to every connected client (e.g. auction sites or ticketing systems)
+- **Finance:** Listen to stock market events and broadcast them to connected users
+- **Web3:** Listen to blockchain events and broadcast them to connected users
+- **Authoritative clocks:** A server clock which broadcasts a timer (e.g. auction sites or ticketing systems)
### Peer to Peer
-We've had a lot of users ask about using Realtime for peer to peer applications. We plan to use Realtime as a WebRTC signaling server which will enable developers to build collaborative software with even lower latency. A common example we've seen is collaborative code editors with a CRDT implementation, like Yjs.
+A lot of users ask about using Realtime for peer to peer applications. We plan to use Realtime as a WebRTC signaling server which will enable developers to build collaborative software with even lower latency. A common example we've seen is collaborative code editors with a CRDT implementation, like Yjs.
### Realtime Inspector
-We plan to build a Realtime inspector into the Supabase Dashboard so it'll be easier to debug the messages that are getting passed through your Channels.
+We're building a Realtime inspector into the Supabase Dashboard so it'll be easier to debug the messages that are getting passed through your Channels.
-## Technical Details
+## Technical Overview
-Before this release, every Supabase project had a server that ran Realtime with the other Supabase services like Kong, GoTrue, and PostgREST.
+Before this release, every Supabase project had a server running Realtime with the other Supabase services like Kong, GoTrue, and PostgREST.
-In this latest release we take advantage of Elixir's strengths by running a distributed cluster of servers across the world. Each server communicates directly with the other nodes in the cluster. This improves performance by balancing the load across nodes.
+In this release we take advantage of Elixir's strengths by running a distributed cluster of servers across the world. Each server communicates directly with the other nodes in the cluster. This improves performance by balancing the load across nodes.
Clients connect to the nearest node in the cluster, and we take advantage of the cluster's fast backbone network to improve client connection speeds, stability, and latency. This is especially useful for clients in regions with variable internet quality.
The entire cluster runs on [Fly](https://fly.io/) - we're big fans!
-Much of the new functionality leverages the [Phoenix Framework](https://www.phoenixframework.org/). This made it relatively straightforward to offer Broadcast ([Phoenix PubSub](https://hexdocs.pm/phoenix_pubsub/Phoenix.PubSub.html)) and Presence ([Phoenix Presence](https://hexdocs.pm/phoenix/Phoenix.Presence.html)) in a globally-distributed cluster. Presence is built on top of [Phoenix Tracker](https://hexdocs.pm/phoenix_pubsub/Phoenix.Tracker.html), a delta-based conflict-free replicated data type (CRDT) for eventually consistent and conflict-free synced state.
+Much of the new functionality leverages the [Phoenix Framework](https://www.phoenixframework.org/). This makes it relatively straightforward to offer Broadcast ([Phoenix PubSub](https://hexdocs.pm/phoenix_pubsub/Phoenix.PubSub.html)) and Presence ([Phoenix Presence](https://hexdocs.pm/phoenix/Phoenix.Presence.html)) in a globally-distributed cluster. Presence is built on top of [Phoenix Tracker](https://hexdocs.pm/phoenix_pubsub/Phoenix.Tracker.html), a delta-based conflict-free replicated data type (CRDT) for eventually consistent and conflict-free synced state.
In the future, we'll document the challenges we faced migrating to this new architecture as well as a few challenges we expect to face in the future.
@@ -214,6 +215,6 @@ In the future, we'll document the challenges we faced migrating to this new arch
We have some great news! [Chris McCord](https://twitter.com/chris_mccord), the creator of the Phoenix framework, has agreed to become a Technical Advisor for Supabase.
-Chris works at Fly, and will continue to work there. His role as a technical advisor is mostly for us to express our gratitude for the work he's already done (and we'll probably need his advice in the future for some existing and upcoming challenges). Realtime is made possible by his open source work.
+Chris works at Fly, and will continue to work there. His role as an advisor is mostly to express our gratitude for the work he's already done (admittedly, we'll probably need his advice for some upcoming challenges). Realtime is made possible by his open source work.
-We also want to thank [José](https://twitter.com/josevalim), and everyone in the Elixir ecosystem, for your open source contributions that have made our lives here on the Supabase Realtime team a lot easier.
+We also want to thank [José Valim](https://twitter.com/josevalim), and everyone in the Elixir ecosystem, for your open source contributions that have made our lives here on the Supabase Realtime team a lot easier.