Aviary
Packages

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 sets search_path, which would leak to other clients behind a pooler such as PgBouncer in transaction mode. At boot, with ensureSchema on, 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 ensureSchema is on), so your application's connections are not affected.
  • SQLite has no schemas: init() fails with a clear error when schema is 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 touch telescope_entries (it can't alter your other tables), and it avoids a self-capture loop where every INSERT INTO telescope_entries would be recorded as a query.

  • Self-healing schema at boot. init() runs ensureDatabase() and the schema.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 to telescope_entries (or the Overview indexes) survives every upgrade. ensureSchema: false disables it.

  • Millisecond timestamps. created_at is datetime(3) on MySQL/MariaDB, so the trace waterfall can order and nest entries within a second. Existing tables are altered on the next boot. With ensureSchema: 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 by TelescopeModule at 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 with em.insertMany, not through the unit of work: no managed entities, no change sets. Each statement holds at most the ORM's batchSize rows (MikroORM's default is 300), which keeps a large recorder.flushBatchSize under 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_rollups is written with one native upsert per 100 buckets (ON DUPLICATE KEY UPDATE on MySQL/MariaDB, ON CONFLICT … DO UPDATE on 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 nothing

or 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
DialectIndexes
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:

SettingDefaultWhat it does
schemanoneA PostgreSQL schema for every Telescope table, written into each statement and created at boot when missing. Telescope never sets search_path.
ensureSchematrueCreate and heal the tables at boot. Turn it off when your drizzle-kit migrations create them.
dedicatedPoolfalsetrue (or { max }) opens a pool of the provider's own with your pool's connection settings, closed at shutdown.
batchSize500Rows 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 EXISTS for the nullable columns, CREATE INDEX IF NOT EXISTS) under an advisory lock, then stores its sha256 in telescope_schema_meta. Every later boot reads that one row and runs nothing else, because ALTER TABLE takes 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-orm creates 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 by ON CONFLICT DO UPDATE, bounded oldest-first prune batches under a lease taken with one atomic upsert, and Pulse and the timeseries as SQL GROUP BYs (date_bin on 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 ioredis
import 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 ioredis client it was given (close() is a no-op). Manage the connection's lifecycle and quit() yourself.

  • Pruning is explicit. There's no per-key TTL — old entries are removed by the core pruner via the prune config (e.g. prune: { after: '24h' }).

  • Two copies per entry. Each entry is stored in full under e:<id> and without its content under m:<id>, written in the same MULTI. Reads that skip content (stats and pulse scans, batched id reads, prune bookkeeping) fetch only the m: copies, at the cost of storing each entry's metadata twice. Entries without an m: copy are read from e:<id>. A search still reads full entries, because it matches on content.

  • Index choice. A query with a familyHash pages 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 is telescope:. 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 client
import { 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. hot is any StorageProvider — 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 on id, batch_id and trace_id. Every pod writes its own files.
  • cold.archive({ types, batchSize?, maxBatchesPerCycle? }) returns the archive config 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, or retention: { default?, perType? } on parquetColdStore (hour granularity), which the prune cycle applies.
  • Compaction merges closed hours (older than closedAfter, default 2h) into files of about targetFileMb, at most maxHoursPerRun (24) per run, under the prune lease. compaction: false turns it off.
  • clear() clears both tiers, including every cold file.
  • DuckDB engine (optional). engine: { duckdb: { memoryLimit, threads, localCacheMb } } with @duckdb/node-api installed. It never loads httpfs: 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/client
import { 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() creates telescope_entries (ReplacingMergeTree, partitioned by day, ordered by (type, created_at, id)) and telescope_rollups (SummingMergeTree) if missing. Rename them with table / rollupTable.
  • Retention changes apply at boot. The TTL's fingerprint is kept in the table comment; when retention changes, init() runs ALTER 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 configure prune, it does nothing.
  • Writes use async_insert=1, wait_for_async_insert=1 (asyncInsert: false to opt out).
  • Bring your own client. Pass client (a @clickhouse/client instance) instead of url; the provider then never closes it. clientOptions passes TLS, compression and other settings through when the provider creates the client.
  • New-exception dedup across pods (markFamilySeen) uses a KeeperMap table (telescope_seen_families, rename with seenFamiliesTable), written in keeper_map_strict_mode so 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 markFamilySeen out, so the alert falls back to deduplicating per pod — exactly as on any store without it.

On this page