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/ Cron Cache

Cron Cache

elements man recipes/cron-cache

Stats 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 pattern decouples the expensive aggregate work from the request path, so user-facing latency stays predictable even as the underlying data grows.

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

Terminal
elements 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

Terminal
elements create job RefreshStats
app/jobs/refresh-stats.ts
import { 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, which keeps the query readable and gives Postgres independent indexes to use. 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

Terminal
elements create page dashboard
app/pages/dashboard/index.ts
import { 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.ehtml
import "./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 sits in CardContent in the design system's type utilities. 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.ts
import 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. Postgres arbitrates the cron leader so exactly one machine fires each tick across the whole deployment. The job itself runs through the standard worker pool, with retries and timeouts handled by the job system.

Notes

  • Why one row, not one row per snapshot. Storing every snapshot would grow the stats table 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 separate statsHistory table from the job in addition to updating stats.
  • Why a job, not raw SQL in the cron callback. The cron callback is supposed to be a one-liner that schedules a job. Job retries, timeouts, and worker-pool scaling all kick in for the actual aggregation. 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 on top of this same pattern. For nightly summaries, drop to every 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 NotFoundError until the first tick lands. Every environment needs that row, so the migration is untagged; demo rows for local work go in a separate @migration env=development migration (see elements man database/seeds).
  • Per-tenant stats. Replace the check (id = 1) constraint with a tenantId uuid primary key foreign key. The job loops over tenants and writes one row per tenant. Pages read by where tenantId = ${session.get('tenantId')}.
Prev Public and Admin ViewsNext Live Dashboard
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026