elements
Start Docs Blog Demos UI Pricing
Elements Manual
  • Getting Started
  • CLI
  • Build
  • Browser
  • Packages
  • TypeScript
  • Elements HTML
  • Assets
  • RPC
  • Router
  • Session
  • Database
  • Migrations
  • LiveTable
  • Channel
  • Jobs
  • Email
  • Payments
  • JSON
  • Async
  • Style
  • UI
  • JSOC
  • Config
  • Tests
  • Logs
  • Deploy
  • Editors
  • Recipes
    • Todo App
    • Todo App: Markup and Styles
    • Authentication
    • Form Validation
    • Signup with Email Confirmation
    • Signup Wizard
    • Admin Roles
    • File Upload
    • Serving Assets From the Database
    • Live Comments
    • Likes / Votes Toggle
    • Shared Lists
    • Team-Partitioned Table
    • Chat Rooms
    • Typing Indicator
    • Grouped Feed Without Flicker
    • Unread Counts
    • Room Presence
    • Collaborative Canvas
    • Infinite Scroll Feed
    • Bidirectional Partition
    • Search and Filter
    • Admin Table
    • Markdown Blog
    • Public and Admin Views
    • Cron Cache
    • Live Dashboard
    • Live Updates From Any Write
    • Marketing Page
    • Status Indicators
    • Markdown Editor
    • Time Ago
  • Licenses
  • Issues
  • Changelog
Manual / Recipes/ Live Dashboard

Live Dashboard

elements man recipes/live-dashboard

On This Page

  • Migration
  • Services
  • Refresh job
  • Page
  • Routes
  • Notes

A dashboard that updates in real time as a background job recomputes its stats. The job runs on a cron schedule, writes a single cached row, and notifies a dashboard channel. Every browser on the dashboard page listens on that channel; when the notification arrives, the template re-fetches the cached row from the RPC and reassigns the value, and the rendered numbers update without a page reload.

The recipe adds a Channel to the cron cache from elements man recipes cron-cache, with the same single-row stats table and the same kind of job. The job notifies the channel after it writes the row. The notification holds no values: each browser that receives it calls an RPC, and the RPC returns the new row.

Migration

Terminal
elements create migration 'add live stats' -tables=users,orders,stats
app/migrations/<timestamp>-add-live-stats.migration.sql
-- add live stats -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create table users ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), handle text not null unique, lastSeenAt timestamptz ); create trigger usersTouchUpdatedAt before update on users for each row execute function touchUpdatedAt(); create table orders ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), userId uuid not null references users(id) on delete cascade, amountCents integer not null ); create index ordersCreatedAtIdx on orders (createdAt desc); create trigger ordersTouchUpdatedAt before update on orders for each row execute function touchUpdatedAt(); create table stats ( id integer primary key default 1 check (id = 1), computedAt timestamptz not null default now(), totalUsers integer not null default 0, activeNow integer not null default 0, revenueTodayCents integer not null default 0 ); insert into stats ( id ) values ( 1 );

The same single-row stats pattern as cron-cache. The columns are tuned for "live" indicators: activeNow instead of weekly active, revenueTodayCents instead of monthly. The cron entry runs every minute, and the job notifies the channel as soon as it has written the row.

Services

The module is shared because the channel has two callers: the /dashboard page (subscribes via dashboardChannel.listen() and re-fetches on notify) and the RefreshDashboardJob (calls dashboardChannel.notify(...) after each write). The page and the job both import the channel, so it is declared in app/shared/services/. Stats, loadStats and fetchStats read the same row, so they are declared in the same module. Without the job and the channel, only the page would import the module, and it would be app/pages/dashboard/services.ts.

app/shared/services/stats.ts
import { Channel, sql } from "@elements/app"; export interface Stats { computedAt: Date; totalUsers: number; activeNow: number; revenueTodayCents: number; } export const dashboardChannel = new Channel<{ event: "refresh" }>("dashboard"); export function loadStats(): Stats { return sql<Stats>(` select computedAt, totalUsers, activeNow, revenueTodayCents from stats where id = 1 `).firstOrThrow(); } /** @rpc */ export function fetchStats(): Stats { return loadStats(); }

loadStats is a regular function used by the route's first render. fetchStats is the RPC the browser calls on each notification. fetchStats calls loadStats, so both run the same SQL.

dashboardChannel is the broadcast channel. The job below notifies it after every cache write; the page below listens.

Refresh job

Terminal
elements create job RefreshDashboard
app/jobs/refresh-dashboard.ts
import { Job, sql } from "@elements/app"; import { dashboardChannel } from "#app/shared/services/stats"; export class RefreshDashboardJob extends Job { run() { let row = sql<{ totalUsers: number; activeNow: number; revenueTodayCents: number; }>(` select (select count(*)::int from users) as totalUsers, ( select count(*)::int from users where lastSeenAt > now() - interval '5 minutes' ) as activeNow, ( select coalesce(sum(amountCents), 0)::int from orders where createdAt >= date_trunc('day', now()) ) as revenueTodayCents `).firstOrThrow(); sql(` update stats set computedAt = now(), totalUsers = ${row.totalUsers}, activeNow = ${row.activeNow}, revenueTodayCents = ${row.revenueTodayCents} where id = 1 `); dashboardChannel.notify({ event: "refresh" }); } }

The job runs the aggregates, writes the cached row, then notifies the channel. The notify call is the last step, so every browser that receives it reads a row that has already been updated. The event payload is intentionally minimal: the channel only signals that a refresh happened; the new values come from fetchStats, not the payload.

Page

Terminal
elements create page dashboard
app/pages/dashboard/index.ts
import { Request, Response } from "@elements/app"; import dashboard from "./template"; import { dashboardChannel, loadStats } from "#app/shared/services/stats"; export default function route(req: Request, res: Response) { return new dashboard({ initial: loadStats(), listener: dashboardChannel.listen(), }); }

The route returns the current cached stats for the initial server render plus a listener for the dashboard channel. First paint shows numbers immediately; the listener handles every subsequent update.

app/pages/dashboard/template.ehtml
import "./style.css"; import type { Listener } from "@elements/app"; import { Card, CardContent } from "@elements/ui/card"; import { RadialChart } from "@elements/ui/chart-radial"; import type { ChartConfig } from "@elements/ui/chart"; import { Stats, fetchStats } from "#app/shared/services/stats"; const ACTIVE: ChartConfig = { activeNow: { label: "active now", color: "var(--chart-1)" }, }; function onNotify(stats: { value: Stats }) { stats.value = fetchStats(); } <html class="page-dashboard" ( initial: Stats, listener: Listener<{ event: "refresh" }>, private stats: { value: Stats } = { value: initial }, ) oninit={() => listener.on("notify", () => onNotify(stats))}> <main class="page-shell"> <h1>live stats</h1> <div class="stats"> <Card title="total users"> <CardContent><p class="stat">{stats.value.totalUsers.toLocaleString()}</p></CardContent> </Card> <Card title="active now"> <CardContent><p class="stat">{stats.value.activeNow.toLocaleString()}</p></CardContent> </Card> <Card title="revenue today"> <CardContent><p class="stat">${(stats.value.revenueTodayCents / 100).toLocaleString()}</p></CardContent> </Card> </div> <Card title="active share" description="signed-in users seen in the last five minutes"> <CardContent> <RadialChart data={[{ stat: "active", activeNow: stats.value.activeNow }]} config={ACTIVE} value="activeNow" name="stat" max={stats.value.totalUsers} startAngle={90} endAngle={-270} innerRadius="70%" background centerValue={stats.value.activeNow.toLocaleString()} centerLabel={`of ${stats.value.totalUsers.toLocaleString()}`} label="active users" /> </CardContent> </Card> <p class="freshness">last computed {stats.value.computedAt.toLocaleString()}</p> </main> </html>
app/pages/dashboard/style.css
@import "#app/shared/styles/page.css"; .page-dashboard .stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-4); margin-bottom: var(--space-4); } .page-dashboard .stat { margin: 0; font-size: var(--text-3xl); font-weight: var(--weight-semibold); font-variant-numeric: tabular-nums; } .page-dashboard .freshness { color: var(--ink-dim); font-size: var(--text-sm); }

stats is wrapped in { value: Stats } so the onNotify handler can reassign stats.value from a function parameter. The template's oninit registers the handler once; each notify event then calls onNotify, which calls the RPC and reassigns the value. Reading stats.value in the bindings tracks reactively, so every dependent cell updates on each reassignment.

Each number is a Card whose title is the label. The gauge is a RadialChart over one row built from the same stats.value, with max set to the user count, so a notify redraws the arc along with the numbers. The page's stylesheet sets only the grid and the size of the numbers; the cards and the chart are styled by @elements/ui.

Routes

Register the page and the cron entry in index.ts:

index.ts
import dashboard from "#app/pages/dashboard"; import { RefreshDashboardJob } from "#app/jobs/refresh-dashboard"; // ... app.route("/dashboard", dashboard); app.cron("every 1m", "refresh dashboard", () => new RefreshDashboardJob().schedule());

The cron fires every minute. Every app machine tries to take the tick's lease with a single-row update in Postgres, and only one update succeeds, so exactly one machine schedules the job each minute.

Notes

  • Why notify with "refresh" and not the new values. The payload could carry the new Stats directly and skip the RPC round-trip. The "refresh" signal is more flexible: different listeners may want different views of the data (admin or user, per-user or global), and each re-fetch can apply its own auth or filter. For a single fixed view, inlining the payload is the simpler choice; do that by typing the channel as Channel<Stats> and passing the new row to notify.
  • Why not LiveTable. LiveTable broadcasts row-level changes. The stats table has one row that updates in place; the LiveTable's optimistic mutator and auto-fill add nothing here. A channel sends one event per recompute, and the browser has no rows to match by id.
  • Cron cadence. The cron tick is one minute, so every 1m is the shortest schedule. Slow it to every 5m if the data doesn't change that fast; for numbers that must move sooner than a minute, call notify from the code that writes the data, as the next note does. The cost is a Postgres aggregate per tick.
  • Push from anywhere. Any server code can call dashboardChannel.notify(...). An order-fulfillment RPC that updates the revenue in stats can call notify when it commits, without waiting for the next cron tick. Each page still calls fetchStats on the notification, so the page behaves the same whether the job or the RPC sent it.
  • Per-user dashboards. When each user sees their own numbers, the RPC reads where userId = ${session.getOrThrow('userId')} (or similar) and the channel signal can stay global ("something changed; everyone re-fetch their own slice"). For tighter targeting, filter the listener: dashboardChannel.listen({ filter: (e) => e.userId === currentUserId }).
Prev Cron CacheNext Live Updates From Any Write
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026