elements
Blog Demos UI Docs 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
Manual / Recipes/ Live Dashboard

Live Dashboard

elements man recipes/live-dashboard

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 pattern layers two ideas: the cron-driven aggregate cache from elements man recipes cron-cache (same single-row stats table, same job shape) plus a Channel push so connected browsers learn about new values as soon as the job commits. The channel carries a "something changed" signal; the actual value comes from an RPC the browser re-runs on each notification.

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 fires every minute and the channel pushes the change immediately.

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). A job is not a page, so the consumer count by the page-vs-shared rule is one page plus one job. The channel is the bridge between them, so its declaration plus the helpers that operate on the same row (Stats, loadStats, fetchStats) cluster together in app/shared/services/. If the page never had a server-driven refresh path (no job, no channel), the entire module would move to 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. They run the same SQL but with different call paths.

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 wires the listener once; every subsequent notify event fires onNotify, which re-runs 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 stylesheet is the grid and the figure size; the cards and the chart bring their own.

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. Postgres arbitrates the leader across the deployment so exactly one machine schedules each tick.

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. The channel matches what's happening: one event per recompute, no row identity to track.
  • 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, notify from the write path, as the next note does. The cost is a Postgres aggregate per tick.
  • Push from anywhere. Anything on the server can call dashboardChannel.notify(...). An order-fulfillment RPC that wants to bump the revenue counter immediately on commit can notify itself, bypassing the cron cadence. Pages still re-fetch through the same path, so the UX is identical regardless of who triggered the update.
  • 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