Dstar Demo

Explained An inbox grows up

Simple and reactive Phoenix pages

Rico Trevisan · October 2026

Dstar renders Phoenix pages over Datastar: the browser sends signals, the server answers with HTML patches over SSE, and there's no client-side app.

Phoenix gives every page a choice. A controller renders HTML and forgets the tab. It's cheap and simple, but every click reloads the page. A LiveView makes the page interactive, and to do that it keeps a socket and a process open for as long as the tab is.

Dstar is a third option, and it aims to be the simple one. A click is an ordinary request: it goes through your router, runs a handler, and comes back as HTML patches for whatever changed, wherever it is on the page. Nothing stays open between clicks. When a page needs to hear about changes it didn't make, you add one attribute, and it opens a stream.

To see what that's worth, this post builds the same inbox both ways, with LiveView written the way Phoenix 1.8 recommends, and follows the arrows as it grows: a login, a badge in the layout, other tabs, a second page, a deploy. Both can build it. The question is what staying connected costs along the way, and whether you pay it on every page or only where you need it.

Following the arrows

Scroll, and the diagram follows along. Solid arrows are HTTP requests. Animated ones are long-lived connections. Dashed outlines are processes that live as long as the tab.

01

A page with buttons

LiveView: live "/inbox", InboxLive. The GET renders through your router. Then the browser opens a WebSocket, and an InboxLive process mounts again and serves the tab for as long as it's open. Clicks ride that socket. The connection is what makes the page interactive, and everything below builds on it.

Dstar: dstar "/inbox", InboxPage. The GET renders through your router, and so does every click, as a POST to /inbox/_event/… that answers with HTML patches. Between clicks, nothing is open and nothing is held. The page is interactive, and it isn't connected.

The code at this step

LiveView +8 lines in 2 files · 8 so far

router.ex
live "/inbox", InboxLive
inbox_live.ex
def mount(_params, _session, socket) do  {:ok, stream(socket, :messages, Inbox.list(socket.assigns.current_scope))}enddef handle_event("read", %{"id" => id}, socket) do  message = Inbox.mark_read!(socket.assigns.current_scope, id)  {:noreply, stream_insert(socket, :messages, message)}end

Dstar +8 lines in 2 files · 8 so far

router.ex
dstar "/inbox", InboxPage
inbox_page.ex
def mount(conn, _params) do  assign(conn, :messages, Inbox.list(conn.assigns.current_scope))enddef handle_event(conn, "read:" <> id, _signals) do  message = Inbox.mark_read!(conn.assigns.current_scope, id)  conn  |> patch(&message_row/1, message: message)

02

Your plugs, twice

LiveView: phx.gen.auth writes the login check twice: pipe_through :require_authenticated_user for the HTTP render, and an on_mount hook on the live_session for the socket, which never runs the router pipeline. That's the documented pattern, and it's sound. It's also what pays for cheap navigation, as stage 5 shows: the socket is a second way in on purpose.

Then you add a plug of your own, say the reader's language from Accept-Language. It sets the Gettext locale for the HTTP render. But the LiveView is a new process, Gettext keeps the locale per process, and the socket can't read that header at all. So the plug also hands its answer over in the session, and an on_mount sets it again. Every plug that feeds the page gets that second half. Forget it and nothing fails: the page renders in the reader's language, then switches to the default as soon as the socket connects.

Good teams keep each rule in one module that the plug and the hook both call, so the logic is written once. What's left is two places to wire every new plug, and remembering that the second one exists.

Dstar: the same plug, once. The GET, every click and every stream are requests through it, each in its own process, so the locale holds for whatever that request renders.

Both: any client can send any event, so "is this my message?" gets checked on every event either way. In Dstar that check can live in authorize/2; in LiveView it lives in handle_event/3. That part is parity.

The code at this step

LiveView +21 lines in 2 files · 29 so far

router.ex
pipeline :browser do  # ...  plug MyAppWeb.Localeendscope "/", MyAppWeb do  pipe_through [:browser, :require_authenticated_user]  live_session :require_authenticated_user,    on_mount: [      {MyAppWeb.UserAuth, :require_authenticated},      MyAppWeb.Locale    ] do    live "/inbox", InboxLive  endend
locale.ex
def call(conn, _opts) do  locale = locale_from(get_req_header(conn, "accept-language"))  Gettext.put_locale(MyAppWeb.Gettext, locale)  # The socket can't read this header, so hand the answer over in the session.  put_session(conn, :locale, locale)end# The LiveView process is a new process: set the locale again in it.def on_mount(:default, _params, session, socket) do  Gettext.put_locale(MyAppWeb.Gettext, session["locale"] || "en")  {:cont, socket}end

Dstar +9 lines in 2 files · 17 so far

router.ex
pipeline :browser do  # ...  plug MyAppWeb.Localeendscope "/", MyAppWeb do  pipe_through [:browser, :require_authenticated_user]    dstar "/inbox", InboxPageend
locale.ex
def call(conn, _opts) do  locale = locale_from(get_req_header(conn, "accept-language"))  Gettext.put_locale(MyAppWeb.Gettext, locale)  connend

03

The sidebar wants to know

Design wants an unread badge in the sidebar, which is part of the layout on every page.

LiveView: in Phoenix 1.8 the layout is a function component, <Layouts.app>, rendered inside the LiveView, so the badge is just an assign. An on_mount hook on the live_session assigns @unread, and attach_hook/4 keeps it fresh. Still one process per tab, no nested LiveView. The cost is wiring: the badge lives in each page's assigns, so every LiveView passes unread={@unread} to its layout, and only that page's process can change it.

Dstar: the badge is an element with an id. A plug assigns the count for the first render. After that, any handler can patch #sidebar in the response it's already sending, and nothing owns it. The flip side: nothing keeps it fresh for you either. Whatever changes the count has to patch it.

The code at this step

LiveView +19 lines in 4 files · 48 so far

router.ex
      MyAppWeb.Locale      MyAppWeb.Locale,      MyAppWeb.Unread    ] do
unread.ex
def on_mount(:default, _params, _session, socket) do  scope = socket.assigns.current_scope  if connected?(socket), do: Inbox.subscribe(scope)  {:cont,   socket   |> assign(:unread, Inbox.unread_count(scope))   |> attach_hook(:unread, :handle_info, &handle_info/2)}enddefp handle_info({:inbox_changed, _message}, socket) do  {:cont, assign(socket, :unread, Inbox.unread_count(socket.assigns.current_scope))}enddefp handle_info(_message, socket), do: {:cont, socket}
layouts.ex
attr :unread, :integer, default: 0def app(assigns) do  ~H"""  <aside>    <.link navigate={~p"/inbox"}>Inbox <span>{@unread}</span></.link>  </aside>  <main>{render_slot(@inner_block)}</main>
inbox_live.ex
<Layouts.app flash={@flash} current_scope={@current_scope}><Layouts.app flash={@flash} current_scope={@current_scope} unread={@unread}>

Dstar +14 lines in 4 files · 31 so far

router.ex
pipeline :unread do  plug MyAppWeb.Unreadendscope "/", MyAppWeb do  pipe_through [:browser, :require_authenticated_user]  pipe_through [:browser, :require_authenticated_user, :unread]
unread.ex
def call(conn, _opts) do  assign(conn, :unread, Inbox.unread_count(conn.assigns.current_scope))end
layouts.ex
attr :unread, :integer, default: 0def app(assigns) do  ~H"""  <aside><.unread_badge unread={@unread} /></aside>  <main>{render_slot(@inner_block)}</main>
inbox_page.ex
<Layouts.app flash={@flash} current_scope={@current_scope}><Layouts.app flash={@flash} current_scope={@current_scope} unread={@unread}># ...  conn  |> patch(&message_row/1, message: message)  |> patch_unread()enddefp patch_unread(conn) do  patch(conn, &Layouts.unread_badge/1, unread: Inbox.unread_count(conn.assigns.current_scope))end

04

Other tabs want to know

Open the inbox in two tabs. Mark one read. The other should follow.

LiveView: nothing new to open. The socket was already there, and the hook subscribed to PubSub when it connected. handle_info/2 updates the rows.

Dstar: this is the first time the inbox needs a connection, and it's one attribute: data-init={connect()}. That POST goes through the same plugs, handle_connect/2 subscribes, and handle_info/2 patches the rows and the badge. The handlers you already wrote don't change.

From here it's parity, and so is the bill. A held-open stream costs about what a socket does: 24 KB per tab against LiveView's 24 KB in the benchmark. The difference is that you opened it here, for this page, because it needed one.

The code at this step

LiveView +3 lines in 1 file · 51 so far

inbox_live.ex
def handle_info({:inbox_changed, message}, socket) do  {:noreply, stream_insert(socket, :messages, message)}end

Dstar +10 lines in 1 file · 41 so far

inbox_page.ex
<ul id="messages"><ul id="messages" data-init={connect()}># ...def handle_connect(conn, _params) do  Inbox.subscribe(conn.assigns.current_scope)  connenddef handle_info({:inbox_changed, message}, conn) do  conn  |> patch(&message_row/1, message: message)  |> patch_unread()end

05

A second page

Real apps are many pages. Click a message to open it.

LiveView: <.link navigate={…}>. Inside the live_session, navigation stays on the open socket: no HTTP request, no plug pipeline, no layout to download. MessageLive mounts in a new process, and the on_mount hooks run (auth, the locale, the badge). This is what the second way in from stage 2 buys, and it's a real win: moving around the app skips the pipeline.

Dstar: a plain <a href={…}>. The browser does a full GET: the router, every plug, mount/2 and the whole page, layout included. Assets come from the cache, and cross-document View Transitions can make the swap smooth, but the server does the full render on every hop. If the old page had a stream, it closes, and the new page opens its own only if it needs one.

We haven't benchmarked navigation yet, so there's no number here. Per hop, LiveView does less work.

The code at this step

LiveView +12 lines in 3 files · 63 so far

router.ex
    live "/inbox", InboxLive    live "/inbox/:id", MessageLive
inbox_live.ex
<li id={@id}>  {@message.subject}  <.link navigate={~p"/inbox/#{@message.id}"}>{@message.subject}</.link>
message_live.ex
def mount(%{"id" => id}, _session, socket) do  {:ok, assign(socket, :message, Inbox.get!(socket.assigns.current_scope, id))}enddef render(assigns) do  ~H"""  <Layouts.app flash={@flash} current_scope={@current_scope} unread={@unread}>    <article>{@message.body}</article>  </Layouts.app>  """end

Dstar +12 lines in 3 files · 53 so far

router.ex
  dstar "/inbox", InboxPage  dstar "/inbox/:id", MessagePage
inbox_page.ex
<li id={"message-#{@message.id}"}>  {@message.subject}  <a href={~p"/inbox/#{@message.id}"}>{@message.subject}</a>
message_page.ex
def mount(conn, %{"id" => id}) do  assign(conn, :message, Inbox.get!(conn.assigns.current_scope, id))enddef render(assigns) do  ~H"""  <Layouts.app flash={@flash} current_scope={@current_scope} unread={@unread}>    <article>{@message.body}</article>  </Layouts.app>  """end

06

Then you deploy

LiveView: every socket drops. Each tab rejoins, runs its on_mount hooks (auth and the badge) and mount/3 again to rebuild its assigns, all at the same moment.

Dstar: each stream re-POSTs connect() through the plugs, and handle_connect/2 re-reads what it shows. mount/2 doesn't run. And a click was never connected in the first place: one that lands mid-deploy is just a request, and Datastar retries it until a server answers.

The lab's six tabs, open in both apps.

LiveView

mount runs
12
auth checks
12
open connections
6

Dstar

mount runs
6
auth checks
12
open connections
6

Last: Six tabs opened the inbox. Open the full lab

The code at this step

LiveView no code changes · 63 lines so far

A deploy needs no code in either model. What differs is what runs when it happens: press Deploy and watch the counters.

Dstar no code changes · 53 lines so far

A deploy needs no code in either model. What differs is what runs when it happens: press Deploy and watch the counters.

Stage 1 / 6 One page

LiveView

ways in: 2 processes per tab: 2 navigation: over the socket memory per tab: 24 KB

Browser router plugs HTTP only WebSocket 1 process / tab InboxLive mount/3 ×2

Dstar

ways in: 1 processes per tab: 0 navigation: full GET memory per tab: ≈ 0 KB

Browser #list router plugs GET · events · streams POST InboxPage handle_event/3 SSE: #list

Processes and memory per open tab: measured medians from the benchmark, 1000 tabs. A Dstar page without a stream holds neither, like the message page at stage 5. Navigation isn't benchmarked yet.

The finished inbox, as code

All six stages stacked: login, the locale plug, a layout badge, live tabs and a second page, written both ways. These are illustrative excerpts on top of phx.gen.auth, which generates the same user_auth.ex for both apps, so it isn't counted. Neither is the Inbox context, which is the same in both.

router.ex
pipeline :browser do
  # ...
  plug MyAppWeb.Locale
end

scope "/", MyAppWeb do
  pipe_through [:browser, :require_authenticated_user]

  live_session :require_authenticated_user,
    on_mount: [
      {MyAppWeb.UserAuth, :require_authenticated},
      MyAppWeb.Locale,
      MyAppWeb.Unread
    ] do
    live "/inbox", InboxLive
    live "/inbox/:id", MessageLive
    # ...every page with the sidebar lives in this live_session
  end
end
locale.ex
defmodule MyAppWeb.Locale do
  @moduledoc "Picks the reader's language: once for HTTP, again for the socket."
  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    locale = locale_from(get_req_header(conn, "accept-language"))
    Gettext.put_locale(MyAppWeb.Gettext, locale)
    # The socket can't read this header, so hand the answer over in the session.
    put_session(conn, :locale, locale)
  end

  # The LiveView process is a new process: set the locale again in it.
  def on_mount(:default, _params, session, socket) do
    Gettext.put_locale(MyAppWeb.Gettext, session["locale"] || "en")
    {:cont, socket}
  end

  defp locale_from(header), do: MyApp.Locales.best_match(header)
end
unread.ex
defmodule MyAppWeb.Unread do
  @moduledoc "Keeps the layout's unread badge fresh on every LiveView in the live_session."
  import Phoenix.Component, only: [assign: 3]
  import Phoenix.LiveView, only: [attach_hook: 4, connected?: 1]

  alias MyApp.Inbox

  def on_mount(:default, _params, _session, socket) do
    scope = socket.assigns.current_scope
    if connected?(socket), do: Inbox.subscribe(scope)

    {:cont,
     socket
     |> assign(:unread, Inbox.unread_count(scope))
     |> attach_hook(:unread, :handle_info, &handle_info/2)}
  end

  # :cont hands the message on, so the page can update its own rows.
  # Every LiveView in the live_session receives inbox messages.
  defp handle_info({:inbox_changed, _message}, socket) do
    {:cont, assign(socket, :unread, Inbox.unread_count(socket.assigns.current_scope))}
  end

  defp handle_info(_message, socket), do: {:cont, socket}
end
layouts.ex
attr :flash, :map, required: true
attr :current_scope, :map, default: nil
attr :unread, :integer, default: 0
slot :inner_block, required: true

def app(assigns) do
  ~H"""
  <aside>
    <.link navigate={~p"/inbox"}>Inbox <span>{@unread}</span></.link>
  </aside>
  <main>{render_slot(@inner_block)}</main>
  <.flash_group flash={@flash} />
  """
end
inbox_live.ex
def mount(_params, _session, socket) do
  {:ok, stream(socket, :messages, Inbox.list(socket.assigns.current_scope))}
end

# Every LiveView hands its layout the badge it was given by the hook.
def render(assigns) do
  ~H"""
  <Layouts.app flash={@flash} current_scope={@current_scope} unread={@unread}>
    <ul id="messages" phx-update="stream">
      <.message_row :for={{id, message} <- @streams.messages} id={id} message={message} />
    </ul>
  </Layouts.app>
  """
end

# Inbox.mark_read!/2 broadcasts. The hook hears it and updates @unread.
def handle_event("read", %{"id" => id}, socket) do
  message = Inbox.mark_read!(socket.assigns.current_scope, id)
  {:noreply, stream_insert(socket, :messages, message)}
end

def handle_info({:inbox_changed, message}, socket) do
  {:noreply, stream_insert(socket, :messages, message)}
end

defp message_row(assigns) do
  ~H"""
  <li id={@id}>
    <.link navigate={~p"/inbox/#{@message.id}"}>{@message.subject}</.link>
    <button phx-click="read" phx-value-id={@message.id}>Mark read</button>
  </li>
  """
end
message_live.ex
def mount(%{"id" => id}, _session, socket) do
  {:ok, assign(socket, :message, Inbox.get!(socket.assigns.current_scope, id))}
end

def render(assigns) do
  ~H"""
  <Layouts.app flash={@flash} current_scope={@current_scope} unread={@unread}>
    <article>{@message.body}</article>
  </Layouts.app>
  """
end

What the process buys

The diagram counts LiveView's process as a cost, and it is one: memory and a socket for every open tab. But it also pays for several of the arrows, and some of them Dstar doesn't have. Here's what you get for it, and Dstar's answer to each.

LiveView's process Dstar
Navigation

Over the open socket. Inside a live_session, a new LiveView mounts with no HTTP request and no plug pipeline. Its on_mount hooks still run.

A full GET. Router, plugs, mount/2 and the whole page. Assets are cached, and View Transitions can make it smooth, but the server renders every hop.

Event order

One at a time, in order. A tab's events queue in its process, so a double click is two events, handled one after the other.

No ordering. Each click is its own request and process. Datastar cancels the previous response from the same element, but the server may already have run it, and retries make delivery at-least-once.

State between events

In the process, out of the client's reach. Assigns hold anything you like, trusted, until the tab closes.

In the database or the session. Signals come from the browser, so they're input, not state. A multi-step form needs somewhere to keep its draft.

Updates

Diffs. Only the changed dynamic parts go over the socket. Compression is off unless you set compress: true on the socket.

HTML patches. The changed element, whole. Bandit compresses responses and streams by default. We haven't benchmarked compressed bytes yet.

Form recovery

Automatic. After a reconnect, forms with phx-change are replayed into the new process.

Mostly not needed. A deploy doesn't reload the page, so inputs stay in the DOM. But nothing on the server knows about a half-filled form.

Cost

A process and a socket per open tab, about the same memory as one Dstar stream.

Nothing per tab, until a page opens a stream.

Event order is the one to read twice. A Dstar handler can run twice, or alongside another one, so it should be safe to repeat: "mark read" is, "add one" isn't. You can watch the difference in the lab: press "Ada double-clicks".

Where it pays off, and where it doesn't

Say that a year from now, someone wants the unread count in the header too, and a toast when new mail arrives. Inbox.deliver/2 now broadcasts {:new_message, message}, which is the same change in both apps. Here's the rest of that pull request, both ways:

Header badge and a new-mail toast

3 files changed. The toast shows on every LiveView in the live_session.

lib/my_app_web/unread.ex the hook
  import Phoenix.Component, only: [assign: 3]  import Phoenix.LiveView, only: [attach_hook: 4, connected?: 1]  import Phoenix.LiveView, only: [attach_hook: 4, connected?: 1, put_flash: 3]  # ...  defp handle_info({:inbox_changed, _message}, socket) do    {:cont, assign(socket, :unread, Inbox.unread_count(socket.assigns.current_scope))}  end  defp handle_info({:new_message, message}, socket) do    {:cont,     socket     |> assign(:unread, Inbox.unread_count(socket.assigns.current_scope))     |> put_flash(:info, "New mail from #{message.from}: #{message.subject}")}  end  defp handle_info(_message, socket), do: {:cont, socket}
lib/my_app_web/components/layouts.ex the layout
  def app(assigns) do    ~H"""    <header>      <.link navigate={~p"/inbox"}>Inbox <span>{@unread}</span></.link>    </header>    <aside>      <.link navigate={~p"/inbox"}>Inbox <span>{@unread}</span></.link>    </aside>    <main>{render_slot(@inner_block)}</main>    <.flash_group flash={@flash} />    """  end
lib/my_app_web/live/inbox_live.ex the page
  def handle_info({:inbox_changed, message}, socket) do    {:noreply, stream_insert(socket, :messages, message)}  end  def handle_info({:new_message, message}, socket) do    {:noreply, stream_insert(socket, :messages, message, at: 0)}  end

With a hook, the change is split by owner. The hook owns the badge and the toast, the page owns its rows, and the layout shows what it's handed. In return, the toast reaches every LiveView in the live_session for free, because every page there is already a process subscribed to the inbox. (Put the toast in InboxLive instead, and it's two files with the same reach as Dstar's.)

With a patch, the whole change lives in the handler that heard about the mail. It patches the row, both badges and the toast by id, and the layout only gives the toast somewhere to land. The catch is reach. Only a page with an open stream hears about new mail. A page without one shows the right count on its next request and costs nothing in between. To toast on every page, every page opens a stream, and pays what a socket costs.

Which brings back the question from the top. If every page should be live, you're paying for the connection anyway, and LiveView's hook makes good use of it. If most pages are clicks and a few spots are live, Dstar lets the same module start as requests and add a stream where it's needed, and the cost stays there.

The inbox, for real

This one is live and shared by everyone reading this page. The messages are held on the server, which is the source of truth. Every button is a POST, and every open tab follows along through one stream. Open this page in a second tab and click in one of them.

layout

Inbox 2

This badge sits outside the page's main content and is patched by id.

page

  • Signals are out — have a look?

    Zach

  • Deploy went out, nobody noticed. Good sign.

    Ada

  • Can the sidebar badge update by itself?

    Ben

    read
  • Lunch on Friday?

    Dee

    read
lib/dstar_demo_web/pages/home_page.ex
def handle_event(conn, "read:" <> id, _signals) do
  with {id, ""} <- Integer.parse(id), do: Inbox.mark_read(id)
  patch_inbox(conn)
end
# ...
def handle_connect(conn, _params) do
  :ok = Inbox.subscribe()
  :ok = Server.subscribe()
  patch_inbox(conn)
end
# ...
def handle_info(:inbox_changed, conn), do: patch_inbox(conn)
# ...
defp patch_inbox(conn) do
  conn
  |> patch(&inbox_sidebar/1, unread: Inbox.unread_count())
  |> patch(&inbox_list/1, messages: Inbox.list())
end

Where each one wins

LiveView wins when…

  • Every page should be live. One hook on the live_session reaches every LiveView. There's no stream to open page by page.

  • Users move around a lot. Navigation inside a live_session stays on the socket: no HTTP render and no plug pipeline per hop.

  • Order matters. One process handles a tab's events one at a time, in order. Dstar's handlers can overlap and must be safe to repeat.

  • Updates are tiny and constant. A diff on an open socket is smaller and faster than an HTTP round trip that returns HTML.

  • The state really belongs to the connection. Presence, uploads and long wizards fit a process that lives as long as the tab.

  • You want the mature path. LiveViewTest, JS commands, streams and years of answers on the forum.

Dstar wins when…

  • You want one way in. The router pipeline guards the page, every event and every stream.

  • Most pages are requests, and a few are live. A page without a stream holds no process and no memory. You pay for live updates where you open one.

  • A change should live with the code that caused it. Any handler patches any element by id, whether it's the layout, a toast or another list.

  • Interactive shouldn't mean connected. Clicks are requests, so they're retried through a deploy or a flaky network, and nothing has to rejoin.

Both live happily in one Phoenix app, so you can choose per route.

Try it

If the arrows on the right look like your app, Dstar is worth an afternoon. If the ones on the left do, LiveView's hook is already the right tool, and nothing here should change your mind.

Dstar is a Hex package. Add it next to Phoenix, and a page is one module and one router line:

mix.exs
{:dstar, "~> 0.3.0"}

Reading isn't proof. Now go break them

Built by . Tell me where it breaks.