Storage adapters
Persist Telescope entries in your own database (MikroORM — MySQL/SQLite; Drizzle — PostgreSQL), share one store across replicas (Redis), tier hot entries into Parquet on S3, or run on ClickHouse. Same StorageProvider contract everywhere.
The default store is per-process SQLite. Swap it by passing a storage provider to forRoot. See Storage for the SPI and Scaling storage for which adapter fits which volume; this page is the wiring for each adapter. Every adapter here passes the same conformance suite.
MikroORM (PostgreSQL / MySQL / SQLite) — @dudousxd/nestjs-telescope-mikro-orm
Persists entries to your application's own database through MikroORM — so you can use your existing MySQL (or SQLite) for Telescope instead of standing up Redis. No migration, no manual table setup. Hand it your existing MikroORM:
import { TelescopeModule } from '@dudousxd/nestjs-telescope';
import { MikroOrmStorageProvider } from '@dudousxd/nestjs-telescope-mikro-orm';
import { MikroORM } from '@mikro-orm/core';
@Module({
imports: [
// your normal MikroOrmModule.forRoot({ ... }) — nothing to add there
TelescopeModule.forRootAsync({
inject: [MikroORM],
useFactory: (orm: MikroORM) => ({
// borrows the host's connection config; opens its OWN scoped connection
storage: new MikroOrmStorageProvider(orm),
}),
}),
],
})
export class AppModule {}For high write volume, put Telescope on a separate database by passing explicit connection options instead of the host MikroORM:
import { MySqlDriver } from '@mikro-orm/mysql';
new MikroOrmStorageProvider({
driver: MySqlDriver,
clientUrl: process.env.TELESCOPE_DATABASE_URL,
// ensureSchema: false, // opt out of boot-time schema sync (you manage it via migration)
});Its own schema
To keep Telescope's tables out of your application's schema, pass schema:
new MikroOrmStorageProvider(orm, { schema: 'telescope' });
// or with explicit connection options:
new MikroOrmStorageProvider({ driver: PostgreSqlDriver, clientUrl }, { schema: 'telescope' });- PostgreSQL: every table (
telescope_entries,telescope_rollups,telescope_leases,telescope_schema_meta) lives in that schema, and every statement names it ("telescope"."telescope_entries"). Telescope never setssearch_path, which would leak to other clients behind a pooler such as PgBouncer in transaction mode. At boot, withensureSchemaon, the schema is created when it does not exist. A role that may not create schemas works as long as the schema exists and the role may create tables in it. - MySQL / MariaDB: the schema is a database on the same server. Telescope's own connection opens it (creating it at boot when
ensureSchemais on), so your application's connections are not affected. - SQLite has no schemas:
init()fails with a clear error whenschemais set.
schema wins over a schema in the connection options or in the host ORM's config. Without it, nothing changes.
How it works:
-
Dedicated, scoped connection. The provider opens its own MikroORM that knows only
TelescopeEntry. The schema diff can therefore only ever touchtelescope_entries(it can't alter your other tables), and it avoids a self-capture loop where everyINSERT INTO telescope_entrieswould be recorded as a query. -
Self-healing schema at boot.
init()runsensureDatabase()and theschema.update({ safe: true })diff: creates the table if missing, adds missing columns, widens changed column types, and never drops anything. MikroORM's diff would drop the indexes the entities do not declare; those statements are taken out, so an index you added totelescope_entries(or the Overview indexes) survives every upgrade.ensureSchema: falsedisables it. -
Millisecond timestamps.
created_atisdatetime(3)on MySQL/MariaDB, so the trace waterfall can order and nest entries within a second. Existing tables are altered on the next boot. WithensureSchema: false, run it yourself (on a large table this rebuilds it, so pick a quiet moment):ALTER TABLE telescope_entries MODIFY created_at DATETIME(3) NOT NULL; -
Lifecycle.
init()is awaited byTelescopeModuleat startup;close()closes the owned connection at shutdown. You call neither. -
Keyset pagination is newest-first; the cursor encodes a
(createdAt, id)position, so paging resumes even after older entries are pruned. -
Flushes are plain multi-row
INSERTs. A flush is written withem.insertMany, not through the unit of work: no managed entities, no change sets. Each statement holds at most the ORM'sbatchSizerows (MikroORM's default is 300), which keeps a largerecorder.flushBatchSizeunder PostgreSQL's 65,535 bound-parameter limit and SQLite's variable limit. A flush that needs several statements runs them in one transaction, so it is stored whole or not at all and the recorder's retry never meets rows from the failed attempt. -
Rollups merge in the database.
telescope_rollupsis written with one native upsert per 100 buckets (ON DUPLICATE KEY UPDATEon MySQL/MariaDB,ON CONFLICT … DO UPDATEon PostgreSQL and SQLite/libSQL). Count and sum add, max keeps the larger value, and the histogram adds cell by cell against the row as stored at write time, so pods writing the same minute never lose or reject each other's increments. Buckets are written in key order, so concurrent writers lock rows in the same order. Other drivers use a transactional read-modify-write, which is only safe with a single writer.
Indexes for the Overview
The console's Overview and Pulse read a whole window (counts per type and per minute, the slowest entries, per-family durations, N+1 groups). The boot schema has no index those reads can answer from, so on a large table each one reads every row of the window. Opt-in indexes fix that. They are not created at boot: building an index on a table that already holds millions of entries is a one-off job, so you run it once, from a migration or a script:
// a one-off script, or the up() of a migration
await storage.createOverviewIndexes(); // returns the names it created; a rerun that creates none changes nothingor with the statements, in your own migration tool:
import { overviewIndexStatements } from '@dudousxd/nestjs-telescope-mikro-orm';
overviewIndexStatements('postgres', { schema: 'telescope' }); // run each one outside a transaction| Dialect | Indexes |
|---|---|
| PostgreSQL | (duration_ms) WHERE duration_ms IS NOT NULL, (created_at, type), (type, created_at) INCLUDE (family_hash, batch_id, duration_ms), all CREATE INDEX CONCURRENTLY IF NOT EXISTS (writes go on while they build). It also lowers the table's autovacuum thresholds (autovacuum_vacuum_scale_factor / autovacuum_vacuum_insert_scale_factor = 0.02), so recent rows are read from the index too. |
| MySQL / MariaDB | (duration_ms), (created_at, type), as online ALTER TABLE … ALGORITHM=INPLACE, LOCK=NONE. |
| SQLite | (duration_ms) WHERE duration_ms IS NOT NULL, (created_at, type) (writes wait while they build). |
On a 2.4M-row PostgreSQL 16 table they built in about 6 s and added about half to the size of the table's indexes (442 MB → 666 MB). A 24-hour Overview went from about 1.4 s to about 1.05 s; the N+1 grouping (every query entry of the window by batch) is what is left. On PostgreSQL 14 and later the per-minute counts use date_bin.
This same package ships the MikroORM query watcher and N+1 detector — see Watchers.
Drizzle (PostgreSQL) — @dudousxd/nestjs-telescope-drizzle
Persists entries to your PostgreSQL through Drizzle ORM (drizzle-orm/node-postgres). No migration, no manual table setup. Hand it your Drizzle database:
import { TelescopeModule } from '@dudousxd/nestjs-telescope';
import { DrizzleStorageProvider } from '@dudousxd/nestjs-telescope-drizzle';
import { drizzle } from 'drizzle-orm/node-postgres';
const db = drizzle({ client: pool });
TelescopeModule.forRoot({ storage: new DrizzleStorageProvider(db) });It also takes a pg Pool, or Pool options for a database of its own:
new DrizzleStorageProvider({ connectionString: process.env.TELESCOPE_DATABASE_URL });Settings, the second argument:
| Setting | Default | What it does |
|---|---|---|
schema | none | A PostgreSQL schema for every Telescope table, written into each statement and created at boot when missing. Telescope never sets search_path. |
ensureSchema | true | Create and heal the tables at boot. Turn it off when your drizzle-kit migrations create them. |
dedicatedPool | false | true (or { max }) opens a pool of the provider's own with your pool's connection settings, closed at shutdown. |
batchSize | 500 | Rows per INSERT. |
How it works:
- Your pool, its own Drizzle instance. The provider borrows your pool and wraps it in a Drizzle instance of its own, built without a logger. Drizzle keeps the logger on the instance, not the pool, so your Telescope query logger never records Telescope's writes and there is no capture loop. The borrowed pool is never closed. When your instance wraps a single
pg.Client, which cannot run Telescope's transactions next to yours, the provider opens a pool of its own with that client's settings. - Tables at boot, behind a fingerprint.
init()runs additive, idempotent DDL (CREATE TABLE IF NOT EXISTS,ADD COLUMN IF NOT EXISTSfor the nullable columns,CREATE INDEX IF NOT EXISTS) under an advisory lock, then stores its sha256 intelescope_schema_meta. Every later boot reads that one row and runs nothing else, becauseALTER TABLEtakes the table's exclusive lock even when the column exists. Nothing is ever dropped. - The same tables as the MikroORM package. Column types, lengths and index names match what
@dudousxd/nestjs-telescope-mikro-ormcreates on PostgreSQL, so either package runs on a database the other created. - Flushes, rollups, pruning and aggregation work as in the MikroORM adapter: multi-row
INSERTs in one transaction when a flush needs several, rollups merged byON CONFLICT DO UPDATE, bounded oldest-first prune batches under a lease taken with one atomic upsert, and Pulse and the timeseries as SQLGROUP BYs (date_binon PostgreSQL 14+).
Managing the tables with drizzle-kit
The pgTable definitions are exported. Re-export them from your schema file and drizzle-kit creates them with your migrations; then pass ensureSchema: false:
// db/schema.ts
export {
telescopeEntries,
telescopeRollups,
telescopeLeases,
telescopeSchemaMeta,
} from '@dudousxd/nestjs-telescope-drizzle';
// or in a schema of their own (export `namespace` too, so drizzle-kit creates the schema):
import { telescopeTables } from '@dudousxd/nestjs-telescope-drizzle';
export const { entries, rollups, leases, schemaMeta, namespace } = telescopeTables('telescope');The package's tests check that what drizzle-kit generates from these definitions and what the boot DDL creates are identical. If you leave the tables to the provider, keep them out of your migrations:
// drizzle.config.ts
import { telescopeManagedTables } from '@dudousxd/nestjs-telescope-drizzle';
export default defineConfig({
// ...
tablesFilter: ['*', ...telescopeManagedTables().map((name) => `!${name}`)],
});The opt-in Overview indexes are the PostgreSQL ones above, under the same names: await storage.createOverviewIndexes(), or overviewIndexStatements({ schema }) in your own migration.
The same package ships the Drizzle query logger. See Watchers.
Redis (shared, multi-instance) — @dudousxd/nestjs-telescope-redis
The store to pick when you run multiple replicas: all replicas pointed at the same Redis share one store, so the dashboard aggregates entries across the whole deployment instead of one process. Requires Redis 6+ and ioredis v5+.
pnpm add @dudousxd/nestjs-telescope-redis ioredisimport Redis from 'ioredis';
import { RedisStorageProvider } from '@dudousxd/nestjs-telescope-redis';
import { TelescopeModule } from '@dudousxd/nestjs-telescope';
const storage = new RedisStorageProvider(new Redis(process.env.REDIS_URL));
TelescopeModule.forRoot({ storage });Notes:
-
The host owns the connection. The provider never closes the
ioredisclient it was given (close()is a no-op). Manage the connection's lifecycle andquit()yourself. -
Pruning is explicit. There's no per-key TTL — old entries are removed by the core pruner via the
pruneconfig (e.g.prune: { after: '24h' }). -
Two copies per entry. Each entry is stored in full under
e:<id>and without its content underm:<id>, written in the sameMULTI. Reads that skip content (stats and pulse scans, batched id reads, prune bookkeeping) fetch only them:copies, at the cost of storing each entry's metadata twice. Entries without anm:copy are read frome:<id>. Asearchstill reads full entries, because it matches on content. -
Index choice. A query with a
familyHashpages the family index, the narrowest one. Rollup reads take two pipelined round trips (bucket indexes, then bucket hashes) whatever the window. -
keyPrefix. Every key is namespaced; the default prefix istelescope:. Override it to share one Redis across apps:new RedisStorageProvider(redis, { keyPrefix: 'myapp:telescope:' });
Tiered: hot store + Parquet cold tier — @dudousxd/nestjs-telescope-parquet
Keeps the store you already have as a minutes-deep hot tier and moves older entries into Parquet files on S3 or a directory instead of deleting them. Reads merge both tiers on the same newest-first cursor. Pure JavaScript by default (hyparquet): nothing native, nothing downloaded at runtime.
pnpm add @dudousxd/nestjs-telescope-parquet
# S3 location: you already have @aws-sdk/client-s3; Telescope uses your clientimport { S3Client } from '@aws-sdk/client-s3';
import { TelescopeModule } from '@dudousxd/nestjs-telescope';
import { MikroOrmStorageProvider } from '@dudousxd/nestjs-telescope-mikro-orm';
import { MikroORM } from '@mikro-orm/core';
import { parquetColdStore, tieredStorage } from '@dudousxd/nestjs-telescope-parquet';
const cold = parquetColdStore({
location: { s3: { bucket: 'observability', prefix: 'telescope/v1', client: new S3Client({}) } },
// or: location: { dir: '/var/lib/telescope' },
compaction: { every: '15m', targetFileMb: 128 },
});
TelescopeModule.forRootAsync({
inject: [MikroORM],
useFactory: (orm: MikroORM) => ({
storage: tieredStorage({ hot: new MikroOrmStorageProvider(orm), cold }),
prune: { after: '5m', intervalMs: 15_000 }, // how long entries stay hot
archive: cold.archive({ types: ['request', 'query', 'exception', 'job'] }), // what moves cold
}),
});Notes:
- Any hot store.
hotis anyStorageProvider— MikroORM, Redis, SQLite. The tiered store has exactly the hot store's optional capabilities (prune lease, bounded deletes, rollups, shared new-exception dedup). - Layout.
<prefix>/type=<type>/dt=<yyyy-mm-dd>/hour=<hh>/<instanceId>-<uuid>.parquet, each file sorted by(created_at, id)in 10,000-row groups, with statistics and bloom filters onid,batch_idandtrace_id. Every pod writes its own files. cold.archive({ types, batchSize?, maxBatchesPerCycle? })returns thearchiveconfig with the cold store as sink, defaulting to 5,000 × 20 per type per cycle. Types not listed are pruned without archiving.- Retention. A bucket lifecycle rule per
type=<type>/prefix, orretention: { default?, perType? }onparquetColdStore(hour granularity), which the prune cycle applies. - Compaction merges closed hours (older than
closedAfter, default2h) into files of abouttargetFileMb, at mostmaxHoursPerRun(24) per run, under the prune lease.compaction: falseturns it off. clear()clears both tiers, including every cold file.- DuckDB engine (optional).
engine: { duckdb: { memoryLimit, threads, localCacheMb } }with@duckdb/node-apiinstalled. It never loadshttpfs: S3 objects are fetched through your client into a bounded local cache. Boot fails if it is configured but not installed. See Scaling storage before enabling it in a hardened image.
ClickHouse — @dudousxd/nestjs-telescope-clickhouse
One columnar store for high volume and long retention. Retention is the table's TTL, so there is no pruner to run.
pnpm add @dudousxd/nestjs-telescope-clickhouse @clickhouse/clientimport { ClickHouseStorageProvider } from '@dudousxd/nestjs-telescope-clickhouse';
TelescopeModule.forRoot({
storage: new ClickHouseStorageProvider({
url: process.env.CLICKHOUSE_URL, // HTTP interface, self-hosted or ClickHouse Cloud
username: process.env.CLICKHOUSE_USER,
password: process.env.CLICKHOUSE_PASSWORD,
database: 'observability',
retention: { default: '24h', perType: { exception: '90d', durable: '30d' } },
}),
// no `prune`: retention is the table's TTL
});Notes:
- Schema at boot.
init()createstelescope_entries(ReplacingMergeTree, partitioned by day, ordered by(type, created_at, id)) andtelescope_rollups(SummingMergeTree) if missing. Rename them withtable/rollupTable. - Retention changes apply at boot. The TTL's fingerprint is kept in the table comment; when
retentionchanges,init()runsALTER TABLE … MODIFY TTL, otherwise it leaves the table alone. prune*are no-ops that report 0, and there is no prune lease. If you do configureprune, it does nothing.- Writes use
async_insert=1, wait_for_async_insert=1(asyncInsert: falseto opt out). - Bring your own client. Pass
client(a@clickhouse/clientinstance) instead ofurl; the provider then never closes it.clientOptionspasses TLS, compression and other settings through when the provider creates the client. - New-exception dedup across pods (
markFamilySeen) uses aKeeperMaptable (telescope_seen_families, rename withseenFamiliesTable), written inkeeper_map_strict_modeso exactly one replica pages for a new exception family per window. It works in two modes:- With ClickHouse Keeper or ZooKeeper configured on the server, plus
<keeper_map_path_prefix>in its config (ClickHouse Cloud has both),init()creates the table and the alert pages once per deployment. - Without them, creating the table fails; the provider logs one warning saying how to enable it and leaves
markFamilySeenout, so the alert falls back to deduplicating per pod — exactly as on any store without it.
- With ClickHouse Keeper or ZooKeeper configured on the server, plus
Watchers
Query watchers (MikroORM, TypeORM, Prisma, Drizzle) and behavioral watchers (mail, cache, schedule, events, logs, redis, model) — each a small package you add to the watchers array.
Queue managers
Horizon-style live queue consoles — BullMQ (browse + retry/remove/promote/retry-all) and SQS (depth + DLQ inspection + redrive), all behind a default-deny mutation gate.