Lakebase Postgres is built on object storage, but 99.99999% of reads are served from high-performance local caches
/Realtime/How it works

How it works

View as Markdown

Realtime is a live SQL query and sync engine, with (optional) higher-level reactivity primitives for client-side development.

----------------    ----------------    -------------------    --------------------
|              |    |              |    |                 |    |                  |
|  (1)         |    |  (2)         |    |  (3)            |    |  (4)             |
|  Postgres    |    |  Live SQL    |    |  Lower level    |    |  Higher level    |
|              |---<|  API         |---<|  client SDKs    |---<|  reactive DX     |
|  [ live   ]  |    |              |    |                 |    |                  |
|  [ query  ]  |    |  [ sync   ]  |    |  `seal()`       |    |  `onUpdate`      |
|  [ engine ]  |    |  [ engine ]  |    |  `subscribe()`  |    |  `useLiveQuery`  |
|              |    |              |    |                 |    |                  |
----------------    ----------------    -------------------    --------------------

The layers of the system are composable. You can use the Live SQL API directly, consume it with lower-level client SDKs or code using the higher-level reactivity primitives.

  1. Postgres

    Enabling Realtime installs an incremental live query engine inside Lakebase Postgres.

    This consumes logical replication, matches write operations to live queries and streams the changes to the Live SQL API.

  2. Live SQL API

    The Live SQL API is a WebSocket API. Clients connect via WebSocket and send live SQL queries to subscribe to.

    The API validates the queries and sends them on to the live query engine inside Postgres. It then consumes changes from Postgres (over a single, multiplexed connection) and fans the changes back out to clients over their WebSocket connections.

    Beta: don't use the Live SQL API directly (yet)

    The WebSocket sync protocol is still evolving, so don't develop directly against it yet. Instead, use the clients and reactivity primitives provided, which will track any changes to the protocol for you.

  3. Lower-level client SDKs

    The TypeScript SDK allows you to use the Live SQL API by defining and subscribing to queries.

    Queries are designed to be defined securely in your backend code and subscribed to safely in your frontend. You can define them using raw SQL:

    backend/queries.ts
    import { rawSql } from "@neon/realtime/server"
    
    interface Message {
      id: string;
      body: string;
    }
    
    const query = rawSql<Message>(
      "select id, body from messages where author_id = $1",
      [userId]
    )

    Or using your ORM or query builder, such as Drizzle or Kysely:

    backend/queries.ts
    import { eq } from "drizzle-orm"
    
    const query =
      db.select()
        .from(messages)
        .where(eq(messages.author_id, userId))

    Once you've defined queries, you can then subscribe to them in your backend:

    backend/subscription.ts
    import { createRealtime } from "@neon/realtime/server"
    
    const realtime = createRealtime({
      adapter: drizzleAdapter(),
      secret,
      db: "neondb",
      url: process.env.NEON_REALTIME_URL!
    })
    
    const subscription = await realtime.subscribe(query)
    subscription.onChange(console.log)

    However, the main pattern is to seal the query so that you can safely pass it to an agent or frontend app:

    backend/queries.ts
    import { createRealtime, type SealedLiveQuery } from "@neon/realtime/server"
    import { drizzleAdapter } from "@neon/realtime-drizzle"
    
    const secret = process.env.NEON_REALTIME_SECRET!
    
    const realtime = createRealtime({
      adapter: drizzleAdapter(),
      db: "neondb",
      secret
    })
    
    async function sealQuery(userId: string): Promise<SealedLiveQuery<Message>> {
      const query =
        db.select()
          .from(messages)
          .where(eq(messages.author_id, userId))
    
      // Seal the query
      return realtime.seal({ query })
    }

    Sealing lets a frontend or agent subscribe to a query that your backend defined, without being able to change the query or its parameters, and without ever holding your Realtime secret. All the client holds is the sealed query, an opaque value that it passes to subscribe(). Sealed queries are short-lived, so the client gets a fresh one from your backend to keep its subscription going. That's what the refreshQuery function in the React example below does.

    Expose the query from an API endpoint, so authorization can be enforced and query parameters (like the userId in this example) can be filled in from the request context:

    backend/server.ts
    import { Hono } from "hono"
    
    const app = new Hono().post(
      "/api/v1/messages/live",
      async (c) => {
        const user = await requireUser(c)
        const sealedQuery = await sealQuery(user.id)
    
        return c.json(sealedQuery)
      }
    )
    
    export type AppType = typeof app

    Fetch the sealedQuery and safely subscribe to it in your frontend code:

    frontend/app.ts
    import { hc } from "hono/client"
    import { createRealtimeClient } from "@neon/realtime/client"
    import type { AppType } from "../backend/server"
    
    const server = hc<AppType>(window.location.origin)
    const client = createRealtimeClient({ url })
    
    const response = await server.api.v1.messages.live.$post()
    const sealedQuery = await response.json()
    
    const subscription = client.subscribe(sealedQuery)
    subscription.onChange(console.log)
  4. Higher-level reactive DX

    Rather than subscribing manually and wiring the changes into your application state, most apps will use the higher-level reactivity primitives that handle this for you.

    These bind live query results to component or local application state and allow you to apply optimistic mutations with automatic management of optimistic state.

    For example, with a React app, you can use useLiveQuery to bind a live query to your component state and the native useOptimistic hook to manage optimistic state:

    App.tsx
    import React, { useOptimistic, useTransition } from 'react'
    
    import { useLiveQuery } from "@neon/realtime-react"
    import type { SealedLiveQuery } from "@neon/realtime/client"
    
    interface Props {
      sealedQuery: SealedLiveQuery<Message>;
      refreshQuery: () => Promise<SealedLiveQuery<Message>>;
    }
    
    export function Messages({ sealedQuery, refreshQuery}: Props) {
      const [ isPending, startTransition ] = useTransition()
      const { data, utils } = useLiveQuery(sealedQuery, { refreshQuery })
    
      const [ messages, addOptimisticState ] = useOptimistic(
        data ?? [],
        (synced: readonly Message[], { id, changes }: Write) => {
          return synced.map(msg =>
            msg.id === id ? { ...msg, ...changes } : msg
          )
        }
      )
    
      async function updateMessage(id: string, changes: Partial<Message>) {
        startTransition(async () => {
          addOptimisticState({ id, changes })
    
          const response = await server.api.v1.messages[":id"].$patch({ param: { id }, json: changes })
          const { txid } = await response.json()
    
          await utils.awaitTxId(txid)
        })
      }
    
      return (
        <ul>
          {messages.map((message) => (
            <li key={message.id}>
              <button onClick={ () => updateMessage(message.id, { body: message.body.toUpperCase() }) }>{message.body}</button>
            </li>
          ))}
        </ul>
      )
    }

    See the reactivity and mutations guides and Next.js and TanStack examples for more on SSR and more advanced data loading and client-side data management patterns.

Subscriptions and consistency

A subscription starts with the query's full initial result. After that, changes arrive in batches as transactions commit. Each batch covers one or more committed transactions and is applied all at once, so your rows never show a half-applied write.

A batch carries the IDs of its transactions (txids). awaitTxId() uses them, along with the server's progress between batches, to know that your write has synced. The subscription reports a status that you can show in your UI.

Packages and guides

PackageWhat it gives youGuide
@neon/realtime/servercreateRealtime, rawSql, sealDefining queries
@neon/realtime/clientcreateRealtimeClient, subscribe, awaitTxIdSubscribing, Optimistic mutations
@neon/realtime-drizzledrizzleAdapterQuery builder or ORM, Drizzle example
@neon/realtime-drizzle/clientdrizzleParsersDrizzle example
@neon/realtime-kyselykyselyAdapterQuery builder or ORM, Kysely example
@neon/realtime-reactRealtimeProvider, useLiveQuery, useRealtimeClientReact reactivity, SSR
@neon/realtime-tanstackrealtimeCollectionOptionsTanStack DB reactivity, SSR with TanStack DB

Start with the quickstart, then read the guides in this order: defining queries, subscribing, reactivity, optimistic mutations and server-side rendering.

Need help?

Join our Discord Server to ask questions or see what others are doing with Neon. For paid plan support options, see Support.

Last updated on

Was this page helpful?
Edit on GitHub