State metrics
Export the state of the job table as OpenTelemetry gauges from a periodic snapshot job.
The observability adapter emits events, so its metrics see transitions and miss state: work that is due and not picked up, job types no live worker takes, how busy the workers are, and jobs that keep failing. A histogram such as queuert.chain.duration records a chain only when it completes, so it never sees chains that have not completed. This guide shows how to take a snapshot of that state as a regular Queuert job and export it as OpenTelemetry gauges.
The snapshot job runs on one worker at a time and exports the gauges itself, under a resource that names no pod. However many pods run workers, the table is scanned once per interval, and each gauge is one series that the pod running the current snapshot updates:
The failing and overdue gauges use the thresholds from your health definitions.
Define the snapshot job type
The snapshot is a plain object the handler builds and exports; the job itself has no output, and each run schedules the next one as a new chain:
src/state-metrics.ts
type StateSnapshot = {
takenAt: number;
jobTypes: Record<
string,
{
blocked: number;
pending: number;
running: number;
due: number;
oldestDueAgeMs: number | null;
liveWorkers: number;
failing: number;
}
>;
chainTypes: Record<string, { running: number; overdue: number | null }>;
workers: { live: number; expired: number; capacity: number; runningJobs: number };
};
const stateSnapshotJobTypes = defineJobTypes<{
/*
* queuert.state-snapshot --(schedules the next run)--> queuert.state-snapshot
*/
"queuert.state-snapshot": {
entry: true;
input: null;
output: null;
};
}>();Take the snapshot
The snapshot counts the state with the client's read methods:
src/state-metrics.ts
const takeStateSnapshot = async (): Promise<StateSnapshot> => {
const now = new Date();
const [jobTypeNames, chainTypeNames] = await Promise.all([
client.getJobTypeNames(),
client.getChainTypeNames(),
]);
const overdueChainTypes = chainTypeNames.filter(
(typeName) => healthDefinitions[typeName].chainOverdueMs !== undefined,
);
const [
blocked,
pending,
running,
due,
oldestPending,
liveWorkersByType,
failingJobs,
runningChains,
overdueChains,
workerCounts,
] = await Promise.all([
client.countJobs({
filters: jobTypeNames.map((typeName) => ({ typeName, status: "blocked" })),
}),
client.countJobs({
filters: jobTypeNames.map((typeName) => ({ typeName, status: "pending" })),
}),
client.countJobs({
filters: jobTypeNames.map((typeName) => ({ typeName, status: "running" })),
}),
client.countJobs({
filters: jobTypeNames.map((typeName) => ({
typeName,
status: "pending",
orderBy: "scheduledAt",
to: now,
})),
}),
Promise.all(
jobTypeNames.map(async (typeName) =>
client.listJobs({
typeName,
status: "pending",
orderBy: "scheduledAt",
to: now,
orderDirection: "asc",
limit: 1,
}),
),
),
client.countWorkers({
filters: jobTypeNames.map((typeName) => ({ typeName, expired: false })),
}),
client.countJobs({
filters: jobTypeNames.map((typeName) => ({
typeName,
minConsecutiveFailures: healthDefinitions[typeName].minConsecutiveFailures,
})),
}),
client.countChains({
filters: chainTypeNames.map((typeName) => ({ typeName, status: "running" })),
}),
client.countChains({
filters: overdueChainTypes.map((typeName) => ({
typeName,
status: "running",
to: new Date(now.getTime() - healthDefinitions[typeName].chainOverdueMs!),
})),
}),
client.countWorkers({ filters: [{ expired: false }, { expired: true }] }),
]);
let capacity = 0;
let runningJobs = 0;
let cursor: string | undefined;
do {
const page = await client.listWorkers({
expired: false,
...(cursor != null ? { cursor } : {}),
});
capacity += page.items.reduce((sum, worker) => sum + worker.concurrency, 0);
const workerJobs = await client.countWorkerJobs({
filters: page.items.map((worker) => ({ workerId: worker.id })),
});
runningJobs += workerJobs.reduce((sum, count) => sum + count.count, 0);
cursor = page.nextCursor ?? undefined;
} while (cursor);
return {
takenAt: now.getTime(),
jobTypes: Object.fromEntries(
jobTypeNames.map((typeName, index) => {
const oldest = oldestPending[index].items[0];
return [
typeName,
{
blocked: blocked[index].count,
pending: pending[index].count,
running: running[index].count,
due: due[index].count,
oldestDueAgeMs:
oldest === undefined ? null : now.getTime() - oldest.scheduledAt.getTime(),
liveWorkers: liveWorkersByType[index].count,
failing: failingJobs[index].count,
},
];
}),
),
chainTypes: Object.fromEntries(
chainTypeNames.map((typeName, index) => {
const overdueIndex = overdueChainTypes.indexOf(typeName);
return [
typeName,
{
running: runningChains[index].count,
overdue: overdueIndex === -1 ? null : overdueChains[overdueIndex].count,
},
];
}),
),
workers: {
live: workerCounts[0].count,
expired: workerCounts[1].count,
capacity,
runningJobs,
},
};
};Key patterns used:
- Batched counts —
countJobs,countChainsandcountWorkerstake one filter per job or chain type and return the counts in input order, one round trip per question - Due work — pending jobs with
orderBy: "scheduledAt"andto: noware due and not picked up; a reschedule movesscheduledAtforward, so a rescheduled job is not waiting - Failing and overdue from the definitions —
healthDefinitions[typeName]returns a type's thresholds with thehealthDefaultfilling the ones it leaves out;minConsecutiveFailureson the job filters, andstatus: "running"withtooncreatedAtfor overdue chains - Capacity —
listWorkers({ expired: false })pages through the live workers, sums theirconcurrency, and counts their running jobs withcountWorkerJobs; utilization divides the two, so jobs still held by an expired worker don't count as load
Counts stop at the state adapter's countCap (10,000 by default), so a snapshot count is a lower bound once it reaches it.
Export the gauges
Each run records the gauges on a meter provider of its own and shuts it down, which exports them once:
src/state-metrics.ts
const exportStateSnapshot = async (snapshot: StateSnapshot): Promise<void> => {
const meterProvider = new MeterProvider({
resource: resourceFromAttributes({ "service.name": "queuert-state" }),
readers: [
new PeriodicExportingMetricReader({
exporter: createMetricExporter(),
exportIntervalMillis: SNAPSHOT_INTERVAL_MS,
}),
],
});
const meter = meterProvider.getMeter("queuert-state");
const takenAt = meter.createGauge("queuert.state.snapshot.taken_at", { unit: "s" });
const jobCount = meter.createGauge("queuert.state.job.count");
const jobDue = meter.createGauge("queuert.state.job.due");
const jobWait = meter.createGauge("queuert.state.job.wait", { unit: "s" });
const jobWorkers = meter.createGauge("queuert.state.job.workers");
const jobFailing = meter.createGauge("queuert.state.job.failing");
const chainCount = meter.createGauge("queuert.state.chain.count");
const chainOverdue = meter.createGauge("queuert.state.chain.overdue");
const workerCount = meter.createGauge("queuert.state.worker.count");
const workerUtilization = meter.createGauge("queuert.state.worker.utilization");
takenAt.record(snapshot.takenAt / 1000);
for (const [typeName, job] of Object.entries(snapshot.jobTypes)) {
const type = { "queuert.job.type": typeName };
for (const status of ["blocked", "pending", "running"] as const) {
jobCount.record(job[status], { ...type, "queuert.job.status": status });
}
jobDue.record(job.due, type);
jobWait.record((job.oldestDueAgeMs ?? 0) / 1000, type);
jobWorkers.record(job.liveWorkers, type);
jobFailing.record(job.failing, type);
}
for (const [typeName, chain] of Object.entries(snapshot.chainTypes)) {
const type = { "queuert.chain.type": typeName };
chainCount.record(chain.running, { ...type, "queuert.chain.status": "running" });
if (chain.overdue !== null) chainOverdue.record(chain.overdue, type);
}
workerCount.record(snapshot.workers.live, { "queuert.worker.state": "live" });
workerCount.record(snapshot.workers.expired, { "queuert.worker.state": "expired" });
workerUtilization.record(
snapshot.workers.capacity === 0 ? 0 : snapshot.workers.runningJobs / snapshot.workers.capacity,
);
await meterProvider.shutdown();
};- A resource without the pod — the provider's resource carries only
service.name, so the series are the same whichever pod runs the snapshot. A pod's own meter provider would tag them with its instance and leave one series per pod - One export per run —
shutdowncollects and exports once; a long-lived provider would keep re-exporting the last values from a pod that no longer runs the snapshot - Exporter per run —
createMetricExporterreturns a new exporter each time, such as anOTLPMetricExporter, since shutting the provider down shuts its exporter down too
A collector that adds pod attributes to everything it receives, such as the Kubernetes attributes processor, splits the series again; leave the queuert-state service out of it.
queuert.state.snapshot.taken_atAttributesWhen the snapshot was taken, in Unix secondsqueuert.state.job.countAttributesqueuert.job.type,queuert.job.statusBlocked, pending and running jobsqueuert.state.job.dueAttributesqueuert.job.typePending jobs that are duequeuert.state.job.waitAttributesqueuert.job.typeSeconds the oldest due job has waitedqueuert.state.job.workersAttributesqueuert.job.typeLive workers that process the typequeuert.state.job.failingAttributesqueuert.job.typeFailing jobsqueuert.state.chain.countAttributesqueuert.chain.type,queuert.chain.statusRunning chainsqueuert.state.chain.overdueAttributesqueuert.chain.typeOverdue chains, for types withchainOverdueMsqueuert.state.worker.countAttributesqueuert.worker.state(live,expired)Workersqueuert.state.worker.utilizationAttributesLive workers' running jobs over their concurrency
Failing is a gauge of its own rather than a status value: a failing job is still pending or running, so summing count over status stays a total.
Alerts follow from the gauges: queuert.state.job.wait growing means workers are missing or too few, queuert.state.job.due above zero with queuert.state.job.workers at zero means no live worker takes the type, and queuert.state.snapshot.taken_at falling a few intervals behind the current time means the snapshot job itself stopped.
Run the snapshot
The processor exports the snapshot, then completes and schedules the next run in one transaction:
src/state-metrics.ts
const stateSnapshotProcessors = createProcessors({
client,
jobTypes: stateSnapshotJobTypes,
processors: {
"queuert.state-snapshot": {
attemptHandler: async ({ applyJobOutcome }) => {
await exportStateSnapshot(await takeStateSnapshot());
await stateAdapter.withTransaction(async (txCtx) => {
await applyJobOutcome({ ...txCtx, output: null });
await client.createChain({
...txCtx,
typeName: "queuert.state-snapshot",
input: null,
schedule: { afterMs: SNAPSHOT_INTERVAL_MS },
deduplication: { key: "queuert.state-snapshot", scope: "running" },
});
});
},
},
},
});- Export before completing — a failed export throws before the transaction, so the attempt is rescheduled and retried instead of completing without exporting
deduplicationwithscope: "running"— ensures only one snapshot chain is active at a time, as in Cleanup; completed snapshot chains are left to Cleanup
Schedule the first run
Schedule the first snapshot at application startup. Deduplication makes this idempotent, and each run schedules the next:
src/state-metrics.ts
const scheduleStateSnapshot = async () =>
stateAdapter.withTransaction(async (txCtx) =>
client.createChain({
...txCtx,
typeName: "queuert.state-snapshot",
input: null,
deduplication: { key: "queuert.state-snapshot", scope: "running" },
}),
);Customization ideas
- Fewer types — leave out job types that never back up, or the snapshot type itself
- Percentiles of waiting — list a page of the oldest due jobs instead of one and report more than the oldest age
- Interval —
SNAPSHOT_INTERVAL_MStrades freshness against one scan per interval
The runnable code is in examples/guides/src/state-metrics.ts. Related: Health for the failing and overdue thresholds, Cleanup for the recurring job pattern, Job, chain and worker queries for the list and count filters, and Feature slices for merging registries.