Docs/Ecosystem/Pulse: Production Telemetry

Pulse: Production Telemetry

Opt-in Go production telemetry with a non-blocking Recorder, 16-bin latency Histogram, Nock SQL rollups, Quiver hooks, and a Sight dashboard plugin.

github.com/fletchhq/pulse

pulsepkg.go.dev

Updated 2026-12-06 fletch docs show pulse/pulse 8 min read

On this page

Pulse is an opt-in production telemetry toolkit and health dashboard for Go and Fletch applications. It records HTTP requests, SQL queries, Quiver background jobs, queue depths, cache lookups, outbound HTTP calls, grouped exceptions, and Go runtime gauges through a non-blocking Recorder, rolls them up into 16-bin latency histograms, and renders an observability dashboard inside Sight.

Introduction

Running a separate metrics stack just to see slow routes, slow SQL queries, failing background jobs, and grouped panics adds infrastructure you may not need on day one. At the same time, writing telemetry straight to a database on every HTTP request can slow down or lock up application traffic.

github.com/fletchhq/pulse buffers events in memory behind a bounded channel and flushes aggregated minute, hour, and day rollups in the background. You can keep rollups in memory during development (MemoryStore) or persist them across multiple nodes in SQLite or Postgres (pulse/nock), then inspect them inside your existing Sight admin panel with pulse/pulsesight.

Installation

Install the module with go get:

go get github.com/fletchhq/pulse@v0.1.0

The root package github.com/fletchhq/pulse and pulse/pulsetest depend only on the Go standard library (CGO_ENABLED=0). Database persistence, Quiver job instrumentation, and the Sight UI live in sub-packages inside the same module, so Go compiles only the sub-packages you import.

Package Dependencies What it provides
github.com/fletchhq/pulse Go stdlib Recorder, collectors, Store, MemoryStore, 16-bin Histogram, Window, Stats, Series, LoadOverview
github.com/fletchhq/pulse/nock fletch/nock, fletch/quiver SQLite and Postgres rollup Store, Migrate, QueryObserver, PruneJob, PruneArgs
github.com/fletchhq/pulse/quiver fletch/quiver Job Middleware and SampleDepth queue-depth sampler
github.com/fletchhq/pulse/pulsesight sight, crest, live, auth/rbac sight.Plugin ("pulse"), dashboard widgets, views, and stylesheet handler
github.com/fletchhq/pulse/pulsetest Go stdlib StoreContract(t, newStore) contract test suite for custom Store backends

When github.com/fletchhq/pulse is in your go.mod, fletch ax sync and fletch docs index its embedded guide and skill automatically.

Core concepts

Non-blocking recorder lifecycle

Every collector writes into a *pulse.Recorder created with pulse.New(store, opts...). Recording calls enqueue into a bounded channel (WithBufferSize, default 8192) and drop new events instead of blocking a request or worker when the buffer fills.

Call rec.Start(ctx) at startup to run the background flusher (WithFlushInterval, default 5s), rec.Flush(ctx) when you need an immediate write in tests or scripts, and rec.Close(ctx) during graceful shutdown so buffered rollups flush before exit. Read rec.Dropped() and rec.FailedFlushes() to monitor recorder health, and rec.Store() to access the backing pulse.Store.

rec := pulse.New(
	store,
	pulse.WithSampleRate(0.25),
	pulse.WithSlowThreshold(pulse.Requests, 500*time.Millisecond),
	pulse.WithSlowThreshold(pulse.Queries, 100*time.Millisecond),
	pulse.WithFrameworkPackages("github.com/yourorg/internal/"),
)
rec.Start(ctx)
defer rec.Close(shutdownCtx)

When WithSampleRate is below 1, ordinary events are sampled and their counts are scaled up in rollups. Slow events (at or above WithSlowThreshold) and exceptions always bypass sampling so latency spikes and crashes are never lost. If a metric exceeds WithMaxKeys distinct keys in a single flush (default 500), extra keys fold into "(other)" so unnormalized paths or ad-hoc SQL cannot cause unbounded cardinality.

Metrics, buckets, and 16-bin histograms

Pulse tracks eight Metric kinds across three rollup periods (pulse.Minute, pulse.Hour, pulse.Day, listed in pulse.Periods):

  • Requests (keyed by route, e.g. "GET /users/{id}")
  • Queries (keyed by pulse.Fingerprint(sql))
  • Jobs (keyed by "<queue>/<kind>")
  • QueueDepth (gauge keyed by queue name)
  • Cache (keyed by "<op> <keyPrefix>", Failed counts misses)
  • Outbound (keyed by target host)
  • Exceptions (keyed by exception fingerprint)
  • Runtime (gauges keyed by HeapAlloc, HeapInuse, Sys, Goroutines, GCPause, NumGC)

Each pulse.Bucket stores counts (Count, Failed, ClientErrors, Slow), totals (Sum, Max, Last), and a fixed 16-bin pulse.Histogram (HistogramBins = 16, upper bounds in HistogramBounds from 1ms up to 1m, plus an open top bin). Because bin boundaries are fixed, b.Merge(other) and h.Merge(other) combine rollups across flushes and across multiple server nodes by addition.

Histogram exposes Add(d, n), Merge(o), Total(), and Quantile(q, limit) (which interpolates within a bin and clamps to limit when positive).

Time windows, Stats, and Series

Query rollups over built-in dashboard windows (Window1h, Window6h, Window24h, Window7d, listed in pulse.Windows, or parsed with pulse.ParseWindow(key)). Call w.Query(metric, now) to build a pulse.Query aligned to whole periods, and use q.LimitOr(def) when applying default limits to TopSlow or Exceptions queries.

Aggregate returned buckets with:

  • pulse.Total(buckets) to fold all buckets into one pulse.Stats.
  • pulse.Summarize(buckets) to group buckets by key, busiest first.
  • pulse.Series(buckets, w, now, valueFn) to produce one int64 point per period across the window, oldest first.
  • pulse.LoadOverview(ctx, store, w, now) to fetch the full pulse.Overview snapshot (Requests, PerMinute, Queries, Jobs, Cache, Outbound, Exceptions, QueueDepth, HeapInuse, Goroutines, RequestTrend).

pulse.Stats provides Avg(), MaxDuration(), Quantile(q) (clamped to Max), and FailRate().

Common tasks

Choosing and migrating a store

Use pulse.NewMemoryStore for local development or single-process tests, and pulse/nock for persistent SQLite or Postgres storage. Both implement pulse.Store (WriteBuckets, QueryRollups, TopSlow, Exceptions, PruneBefore).

import (
	"github.com/fletchhq/pulse"
	pulsenock "github.com/fletchhq/pulse/nock"
)

store, err := pulsenock.New(db, pulsenock.WithTablePrefix("pulse_"))
if err != nil {
	return err
}
if err := store.Migrate(ctx); err != nil {
	return err
}
import (
	"time"

	"github.com/fletchhq/pulse"
)

store := pulse.NewMemoryStore(
	pulse.WithRetention(7*pulse.Day),
	pulse.WithEntryLimit(1000),
	pulse.WithExceptionLimit(500),
)

pulsenock.Migrate(ctx, db, opts...) is a package-level shortcut if you prefer migrating before constructing the store. pulse/nock merges rollups with INSERT ... ON CONFLICT upserts across <prefix>buckets, <prefix>entries, and <prefix>exceptions, so multiple application nodes can write to one shared database.

To keep SQL tables bounded, call store.Prune(ctx, olderThan) (which also drops minute rollups older than one day) or register pulsenock.PruneJob(store) with Quiver and schedule pulsenock.PruneArgs{OlderThan: 7 * pulse.Day} (Kind() == "pulse.prune"):

quiver.Handle(queue, pulsenock.PruneJob(store))

Instrumenting HTTP, SQL, jobs, cache, outbound HTTP, exceptions, and runtime

Wire each collector to the same *pulse.Recorder:

// 1. HTTP requests (ignore health probes, admin panel, and Pulse CSS)
r.Use(pulse.HTTPMiddleware(
	rec,
	pulse.WithIgnorePaths("/healthz", "/readyz", "/admin", pulsesight.StylesheetPath),
))

// 2. Nock SQL queries (pass the same table prefix to prevent self-observation)
db.AddObserver(pulsenock.QueryObserver(rec, "pulse_"))

// 3. Quiver jobs and periodic queue-depth sampling
queue.Use(pulsequiver.Middleware(rec))
pulsequiver.SampleDepth(ctx, rec, 15*time.Second, func(ctx context.Context) (map[string]int64, error) {
	return inspectQueueDepths(ctx, queue)
})

// 4. Outbound HTTP clients
httpClient := pulse.WrapHTTPClient(rec, &http.Client{Timeout: 10 * time.Second})

// 5. Runtime heap, GC, and goroutine gauges
rec.StartRuntimeSampler(ctx, 15*time.Second)

For custom instrumentation outside middleware:

  • HTTP routes: customize route grouping with pulse.WithRoute(fn) (default pulse.DefaultRoute, which falls back to pulse.NormalizePath to replace numeric, UUID, and long hex/token segments with {id}), or record manually with rec.RecordRequest(route, status, d, detail).
  • SQL: normalize statements with pulse.Fingerprint(sql) (replaces literals and placeholders with ? and collapses IN lists to (?...)), or call rec.RecordQuery(ctx, sql, d, err).
  • Cache: wrap lookups with pulse.TrackCache[V](rec, "user:", func() (User, bool) { ... }) or call rec.RecordCache(op, keyPrefix, hit).
  • Outbound HTTP: wrap an http.RoundTripper directly with pulse.NewTransport(rec, base) or call rec.RecordOutbound(method, host, status, d, err).
  • Exceptions: call rec.RecordException(ctx, err, stack) (passing nil captures debug.Stack()). Panics caught by HTTPMiddleware or pulsequiver.Middleware are wrapped in *pulse.PanicError (Error(), Unwrap()), recorded as exceptions, and re-panicked. Stack traces parse into []pulse.Frame with App distinguishing your code from stdlib, github.com/fletchhq/, and WithFrameworkPackages prefixes.
  • Runtime: call rec.SampleRuntime() to capture a single snapshot on demand.

Mounting the Sight observability dashboard (pulse/pulsesight)

github.com/fletchhq/pulse/pulsesight registers Pulse as a sight.Plugin (PluginID() == "pulse"). Mount the stylesheet handler, register the plugin on Sight, and grant pulsesight.DefaultPermission ("pulse:view") to operator roles:

mux.Handle(pulsesight.StylesheetPath, pulsesight.StylesheetHandler())

panel := sight.New("admin",
	sight.WithPlugins(
		pulsesight.Plugin(
			store,
			pulsesight.WithRecorder(rec),
			pulsesight.WithGroup("Observability"),
			pulsesight.WithPanelPath("/admin"),
		),
	),
)

Passing pulsesight.WithRecorder(rec) surfaces Dropped() and FailedFlushes() health counters alongside the sample rate. The plugin installs five Sight pages — Overview (pulse), Requests (pulse-requests), Queries (pulse-queries), Jobs (pulse-jobs), and Exceptions (pulse-exceptions) — plus summary widgets on Sight's main dashboard unless pulsesight.WithoutDashboard() is set. All views render with Crest, Live, and sight/ui under strict @alpinejs/csp with no inline scripts or eval.

Advanced usage

Querying rollups and building custom views

You can read rollups directly from any pulse.Store to expose health summaries, alerts, or custom charts:

now := time.Now().UTC()
w := pulse.ParseWindow(req.URL.Query().Get("window"))

overview, err := pulse.LoadOverview(ctx, store, w, now)
if err != nil {
	return err
}

p95 := overview.Requests.Quantile(0.95)
failRate := overview.Requests.FailRate()

slowQueries, err := store.TopSlow(ctx, pulse.Query{
	Metric: pulse.Queries,
	From:   now.Add(-w.Span),
	To:     now,
	Limit:  20,
})

Inside pulse/pulsesight, the Crest UI components and view models are exported (Page with Mount, PageHead, Head, Link, RankCard, Panel, Row, Cell, Trend, ExceptionView, FrameView) so custom Sight extensions can inspect or compose Pulse's page layout structures.

Contract testing custom pulse.Store implementations

Verify any custom pulse.Store backend against the stdlib-only contract suite in github.com/fletchhq/pulse/pulsetest:

func TestCustomPulseStore(t *testing.T) {
	pulsetest.StoreContract(t, func(t *testing.T) pulse.Store {
		return newMyPulseStore(t)
	})
}

The suite verifies bucket merging, range boundaries ([From, To)), TopSlow ordering, exception grouping and counts, PruneBefore, and a full Recorder round trip through LoadOverview.

Reference

Recorder options (pulse.New)

Option Default Purpose
WithSampleRate(r) 1.0 Samples ordinary events at rate r (0 to 1); slow events and exceptions bypass sampling
WithBufferSize(n) 8192 Bounded ingestion channel capacity before events drop
WithFlushInterval(d) 5s Background flusher interval
WithSlowThreshold(m, d) 1s (Requests, Jobs, Outbound), 100ms (Queries) Threshold marking events for metric m as slow
WithMaxKeys(n) 500 Distinct keys per metric per flush; overflow folds into "(other)"
WithMaxEntries(n) 1000 Slow entries written per flush
WithFrameworkPackages(prefixes...) stdlib + github.com/fletchhq/ Additional import prefixes treated as framework stack frames
WithClock(now) time.Now Clock used to timestamp recorded events
WithLogger(l) slog.Default() Logger for failed store flushes

Storage and pulsesight options

Package Option Default / purpose
pulse (MemoryStore) WithRetention(d) 7 * pulse.Day (minute rollups kept at most pulse.Day)
pulse (MemoryStore) WithEntryLimit(n) 1000 slow entries retained per metric
pulse (MemoryStore) WithExceptionLimit(n) 500 grouped exceptions retained
pulse (MemoryStore) WithStoreClock(now) time.Now for retention pruning
pulse/nock WithTablePrefix(p) "pulse_" prefix for buckets, entries, and exceptions tables
pulse/nock WithClock(now) time.Now for Store.Prune
pulse/pulsesight WithGroup(label) "Pulse" sidebar navigation group in Sight
pulse/pulsesight WithPermission(perm) DefaultPermission ("pulse:view")
pulse/pulsesight WithPanelPath(path) "/admin" base mount path for widget links
pulse/pulsesight WithRecorder(r) Displays Dropped(), FailedFlushes(), and sample rate
pulse/pulsesight WithStylesheetPath(path) StylesheetPath ("/_pulse/pulse.css")
pulse/pulsesight WithClock(now) time.Now for dashboard window end
pulse/pulsesight WithoutDashboard() Omits Pulse widgets from Sight's main dashboard