@ogygia/devtools · Profiler
Custom spans
Name the waits the profiler can't see on its own. span() and instrument() time a database driver, a queue or a shared renderer, tag() labels a request, and mark() times work in the visitor's browser.
The profiler sees outbound fetch and http calls, timers, file reads and sockets on its own. Two kinds of wait never show up by themselves: a database driver on its own socket pool, and a promise chain (a queue, a cache client, a worker). They appear as grey “nothing recorded” stretches on the timeline. Name them in your code with span():
Outside a recording each of these is one if and then your function: nothing is recorded and nothing is sampled. On the client, and in a universal load running in the browser, they do nothing at all. So you can leave them in.
import { span, tag } from '@ogygia/devtools/profiler';
import { db } from '$lib/server/db';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params, url }) => {
tag('host', url.hostname);
const user = await span('db.user', () =>
db.users.find(params.id)
);
const orders = await span(
'db.orders',
() => db.orders.byUser(user.id),
(rows) => ({
rows: rows.length
})
);
return { user, orders };
};span
span(name, fn, attrs?) runs fn and records it the way the profiler records an outbound call: its start and end on the profiler’s clock, the request it ran in, the caller’s file and line, and the span it sits inside. A synchronous fn stays synchronous and a promise stays a promise. A throw or rejection is recorded on the span and rethrown.
attrs is a record, or a function of the result for what’s only known afterwards. Values are strings, numbers or booleans. The report reads four keys and carries the rest:
| Key | What the report does with it |
|---|---|
cache | 'hit' or 'miss': counted in the Spans table, and a cache that misses on every render gets cache-misses. |
rows | A count, shown and fitted against the span’s time. |
bytes | A size, shown and fitted the same way. |
key | What the call was for, shown on the span. |
For a stream or an event you can’t wrap in a function, open one by hand. span.start(name, attrs?) returns a handle with set(key, value), end(attrs?) and fail(error); ending twice does nothing.
import { span } from '@ogygia/devtools/profiler';
import type { Readable } from 'node:stream';
export function measure_feed(stream: Readable): Readable {
const s = span.start('feed.read');
let bytes = 0;
stream.on('data', (chunk: Buffer) => (bytes += chunk.length));
stream.on('end', () => s.end({ bytes }));
stream.on('error', (error) => s.fail(error));
return stream;
}Spans table
The report’s Spans table lists each span name with its count, time per render, p50, max, cache hits and misses, errors and caller. It carries three totals, like the components table:
- total is the spans’ summed duration.
- self is total minus the child spans nested inside, so a
ds.passof 249 ms with 178 ms of renders and 69 ms of splicing inside has 2 ms of its own. - wall counts overlaps once. Forty-eight renders of 127 ms under a
Promise.alladd up to 6 s of total but 180 ms of wall, and wall is what the render paid. A ∥ marks spans that ran together.
A span whose attribute has a few distinct values gets a by table: ds.render by tag says what each element type cost (count, total, p50), and db.query by table says which table the time went to.
Spans show up in other places too. On the timeline, a gap inside a span reads “in db.user”, and a call inside it names the span. The awaits-in-a-row check treats spans as calls. And five findings read them: span-repeat (once per item, the N+1 shape), span-slow (a fifth of the render or more), cache-misses, span-open and span-errors (Findings).
Values
A span that reports a number (rows, bytes, or any numeric attribute) gets a row per attribute under the Spans table, with the range across the recording (min, median, max and sum) and how the span’s time moved with the value. ms per unit is the slope of a straight line through the spans, and fit is how well that line holds, where 1 means the value alone sets the time.
A steep line with a good fit says the cost depends on the size of the input, which a function’s name can never tell you: the same render is cheap on 3 items and slow on 3,000. The value-driven finding names the first span whose time follows a number with a fit of 0.8 or more over 5 spans or more. A value that barely moved (by less than 5% of its size) gets no fit. In the JSON it’s span_values.
instrument
Some functions (a design system’s renderToString, a database client’s query, an SDK method) are called from so many places that wrapping each call is impractical. instrument wraps the function once, and every call becomes a span. It has two forms:
The attrs function gets the result and then the call’s arguments, so a span can carry the tag it rendered. this is kept. A page that renders three hundred custom elements through one renderToString then shows three hundred ds.render spans with the per-tag split, and span-repeat points it out. When the repeated spans ran together (in a Promise.all), the finding shows their wall time next to the summed work, and the fix is to make each item cheaper rather than to batch.
import { instrument } from '@ogygia/devtools/profiler';
import { renderToString as render_core } from '$lib/server/design-system';
import { db } from '$lib/server/db';
// an ESM import is read-only, so bind the wrapped function
export const renderToString = instrument(
render_core,
'ds.render',
(r, tag) => ({
tag,
bytes: r.html.length
})
);
// a method on an object is patched in place; the return value restores it
export const restore_query = instrument(
db,
'query',
'db.query',
(rows, sql) => ({
rows: rows.length,
key: sql.slice(0, 40)
})
);tag
tag(key, value) stamps the request it runs in, while a recording runs: in a build, during a page profile (any request the process serves meanwhile, not only the profile’s renders) or on a request profiled with x-profile; on the dev server, during any recording window too. Outside a recording it does nothing, like span(), so live traffic carries tags only for the stretch a recording ran. Values are strings, numbers or booleans, cut to 64 characters, and a request keeps at most 16 keys.
The report’s request rows show the tags, and ?by=<key> on the dashboard splits the slowest routes by a tag among the requests that carry one. Since most requests carry none, that split can’t yet tell you “slow for everyone, or for tenant X?” across real traffic (#2304, item 21).
mark
The server profile can’t see the visitor’s browser, where a design system’s components hydrate, a widget boots and a font arrives. mark from @ogygia/devtools/profiler/client is the browser’s counterpart of span:
mark(name, fn, attrs?)times a function or the promise it returns.mark(name, promise, attrs?)times a promise you already hold. A throw or rejection is recorded witherror: trueand rethrown.mark.event(name, type, target?, opts?)times until an event fires ontarget(the document by default), from the call or, with{ from: 'navigation' }, from the page’s start. It returns a promise that settles when the event fires.mark.start(name, attrs?, opts?)opens one by hand (const h = mark.start('search.first-results'));h.end({ hits: 12 })closes it, and ending twice does nothing.
On the server, where there’s no document, every form runs your work and records nothing, so a mark in a component’s script is safe during SSR.
The marks travel with the visit your browser reports, so they cost visitors nothing: the profiler adds its reporting script only to documents served to its own logged-in user, and without it mark runs the work and keeps at most 400 small entries in memory that nothing reads. With it, marks made before the script is ready wait in that same queue and are sent once it starts. The report shows them under Marked in the browser (p50, max, failures and attribute keys), next to the vitals and the server render, and the slowest gets the client-mark note.
<script lang="ts">
import { mark } from '@ogygia/devtools/profiler/client';
import { boot } from '$lib/widget';
// a web-components runtime's "all hydrated" event on the document, timed from the page's start
mark.event('ds.hydrate', 'components-ready', undefined, {
from: 'navigation'
});
async function open() {
await mark('widget.boot', () => boot(), {
version: '3'
});
}
</script>
<button onclick={open}>Open</button>