Cron Cache
elements man recipes/cron-cacheStats that would be expensive to compute on every request, cached in a
single-row table. A cron job recomputes the row every five minutes; pages read
the cached row with one cheap select. The aggregate queries run in the job, not in
the page's route, so a page request takes the same time however many users and
orders the app has.
The recipe shows a "site stats" panel: total user count, active-this-week count,
revenue this month. The aggregates run inside a RefreshStatsJob triggered by
app.cron, which writes the latest values into a single stats row keyed by a
fixed id. The dashboard route reads that one row.
Migration
Terminalelements create migration 'add stats' -tables=users,orders,stats
app/migrations/<timestamp>-add-stats.migration.sql-- add 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, activeThisWeek integer not null default 0, revenueThisMonthCents integer not null default 0 ); insert into stats ( id ) values ( 1 );
The stats table holds exactly one row. The check (id = 1) constraint plus
default 1 ensures every insert and every update operates on the same row. The
seed insert in the migration creates that row, so the first page load doesn't
have to handle an empty cache. The cron job below upserts the same row by id.
Stats job
Terminalelements create job RefreshStats
app/jobs/refresh-stats.tsimport { Job, sql } from "@elements/app"; export class RefreshStatsJob extends Job { run() { let row = sql<{ totalUsers: number; activeThisWeek: number; revenueThisMonthCents: number; }>(` select (select count(*)::int from users) as totalUsers, ( select count(*)::int from users where lastSeenAt > now() - interval '7 days' ) as activeThisWeek, ( select coalesce(sum(amountCents), 0)::int from orders where createdAt >= date_trunc('month', now()) ) as revenueThisMonthCents `).firstOrThrow(); sql(` update stats set computedAt = now(), totalUsers = ${row.totalUsers}, activeThisWeek = ${row.activeThisWeek}, revenueThisMonthCents = ${row.revenueThisMonthCents} where id = 1 `); } }
The job runs three aggregates in one SQL round-trip and then a single update
against the cached row. Each aggregate has its own where clause, so Postgres
can use a different index for each one. The job is
fieldless (extends Job with no <Fields> type parameter) because the cron
tick is the only trigger; no payload to pass.
Dashboard page
Terminalelements create page dashboard
app/pages/dashboard/index.tsimport { Request, Response, sql } from "@elements/app"; import dashboard, { Stats } from "./template"; export default function route(req: Request, res: Response) { let stats = sql<Stats>(` select computedAt, totalUsers, activeThisWeek, revenueThisMonthCents from stats where id = 1 `).firstOrThrow(); return new dashboard({ stats }); }
The route does one select against a single-row table. The query is
constant-time regardless of how many users or orders the app has accumulated.
The page renders with the values as of the last cron tick.
app/pages/dashboard/template.ehtmlimport "./style.css"; import { Card, CardContent } from "@elements/ui/card"; export interface Stats { computedAt: Date; totalUsers: number; activeThisWeek: number; revenueThisMonthCents: number; } <html class="page-dashboard" (stats: Stats)> <main class="page-shell"> <h1>site stats</h1> <div class="stats"> <Card title="total users" size="sm"> <CardContent> <p class="text-2xl font-semibold">{stats.totalUsers.toLocaleString()}</p> </CardContent> </Card> <Card title="active this week" size="sm"> <CardContent> <p class="text-2xl font-semibold">{stats.activeThisWeek.toLocaleString()}</p> </CardContent> </Card> <Card title="revenue this month" size="sm"> <CardContent> <p class="text-2xl font-semibold">${(stats.revenueThisMonthCents / 100).toLocaleString()}</p> </CardContent> </Card> </div> <p class="hint">last computed {stats.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(auto-fit, minmax(14rem, 1fr)); gap: var(--space-4); }
Each stat is a Card (opens in a new tab) from @elements/ui, which every
new app has (elements man ui): the label is the card's title, a heading,
and the value is a <p> inside CardContent, sized with the text-2xl and
font-semibold utility classes. The
page's own CSS only lays the cards out, as a grid that wraps to one column on
a phone. The .hint line renders the computedAt timestamp so the reader
knows how stale the snapshot is.
Routes
Register the page and the cron entry in index.ts:
index.tsimport dashboard from "#app/pages/dashboard"; import { RefreshStatsJob } from "#app/jobs/refresh-stats"; // ... app.route("/dashboard", dashboard); app.cron("every 5m", "refresh site stats", () => new RefreshStatsJob().schedule());
The cron entry fires every five minutes; the callback schedules a
RefreshStatsJob. 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 runs each tick. The job runs on a worker process, which retries it if
run() throws and stops it at its timeout.
Notes
- Why one row, not one row per snapshot. Storing every snapshot would grow
the
statstable without bound and force the route to find the latest row on every read. The single-row pattern bounds storage and makes the read a constant-id lookup. If history matters, write to a separatestatsHistorytable from the job in addition to updatingstats. - Why a job, not raw SQL in the cron callback. The cron callback only
schedules a job. The aggregation runs as a job, so it gets the job system's
retries and timeout and runs in the worker pool. If
RefreshStatsJob.run()errors, the job system retries with exponential backoff; an error inside the cron callback itself would not retry. - Picking the cron cadence. Five minutes is a balance: fresh enough for a
dashboard, infrequent enough that the aggregates stay cheap. For per-second
freshness, see
elements man recipes live-dashboard, which adds a channel and reactive re-fetch to this same pattern. For nightly summaries, useevery day at 2am. - Initial value. The migration inserts the seed row so the first page load
works before the cron has ever fired. Without the seed, the route would throw
NotFoundErroruntil the job first runs. Every environment needs that row, so the migration is untagged; demo rows for local work go in a separate@migration env=developmentmigration (seeelements man database/seeds). - Per-tenant stats. Replace the
check (id = 1)constraint with atenantId uuid primary keyforeign key. The job loops over tenants and writes one row per tenant. Pages read bywhere tenantId = ${session.get('tenantId')}.