Pulse System Design
Request tracing, query profiling, runtime metrics and alerting that run inside the process, with no collector, no Redis and no second deployment.
github.com/MUKE-coder/pulse/pulsev1.3.0Questions this page answers
"Design a metrics and monitoring platform" is a classic prompt. This is the in-process version of that problem, which changes the answers in interesting ways: no collector to scale, and a hard rule that the measurement must not cost what it is measuring.
What is Pulse?
An observability tool that runs inside the Go application rather than alongside it: request timings, every database query with the line that issued it, memory and goroutine counts, errors with stack traces, health checks and alerts, with a dashboard embedded in the binary. A separate library that Grit mounts. It exists because the standard answer is a monitoring stack bigger than the application it watches, so small deployments install nothing and know nothing.
Worked through in Problem statement →Why build this in-process rather than running Prometheus and a collector?
For the application that is one container and a database, a monitoring stack is bigger and harder to operate than the thing it monitors, so it does not get installed and the answer to "why was it slow" stays "nobody knows". In-process costs a dependency instead of an architecture. It stops being the right trade once there are enough replicas that you need a combined view.
Worked through in Problem statement →What stops the profiler from slowing down the requests it measures?
Storing a metric is a buffer push or a queue append, and the call returns immediately. Nothing on the request path waits on storage. The moment measurement is a measurable fraction of request time, every latency number it reports includes itself, which makes the tool actively misleading rather than merely expensive.
Worked through in System requirements →How do you keep memory bounded under unexpected traffic?
A fixed-size ring buffer, so the bound is the data structure rather than a cleanup goroutine that is supposed to keep up. The oldest entry is overwritten rather than memory growing. That is a much stronger guarantee than any policy, and it is what lets the thing run in a container with a limit. There is a trap inside that answer, and this product fell into it: a buffer bounded by its capacity can also allocate that whole capacity up front, so an idle process pays for history it does not have. Until v1.3.0 Pulse held about 38 MB of empty ring buffers in a 45 MB heap. Capacity should be the ceiling and the allocation should grow towards it, which is a different sentence from the one most people give in an interview.
Worked through in System requirements →You can see that a route is slow. How do you know it got slower?
From a current number alone, you do not. A route that went from 40ms to 90ms three deploys ago looks healthy, because 90ms is not slow in absolute terms and nothing in a point-in-time view remembers the 40. So keep a rolling baseline per route and per percentile over a window long enough to be stable, a week being the usual choice, and show today as a ratio against it rather than only as an absolute. Then pair it with the deploy marker: attributing a step change to the restart that preceded it turns "something got slower" into "this release got slower", which is the difference between an investigation and a fix. It is also cheap, because an hourly per-route per-percentile summary is tiny next to the request records it summarises, and it is the part worth keeping for months after the detail has aged out.
Worked through in Low level design →The dashboard says which route is slow. How do you find out which line?
For a query, the profiler already records the file and line that issued it. For everything else it is pprof, which is in the Go runtime and needs no library: register the handlers and go tool pprof can pull a CPU, heap, allocation, goroutine, mutex or block profile over HTTP from the running process. The reason it is not simply on by default is that those endpoints are an unauthenticated description of your program, and a thirty second CPU profile is a denial of service if anyone can ask for one. So they sit behind the dashboard credentials, and the two that cost something merely to collect, mutex and block, stay off until you turn them on: asking for a block profile on a process that is not collecting one answers 409 and names the option to add, rather than returning an empty profile that reads as "nothing is blocking".
Worked through in High level design →You sample traces to control cost. Does that not make your error rate wrong?
It would, which is why sampling and counting are separated. Traces are sampled; per-minute rollups count every single request. Totals, error rates and objectives are therefore exact at any sample rate. Computing an error rate from a ten per cent sample gives an answer with no stated error bar that people then act on, which is worse than having no number.
Worked through in Capacity estimation →Your retention says 24 hours but the buffer holds two minutes of traffic. Who tells the user?
The tool does. It reports when buffer capacity rather than the retention setting is what limits history, along with dropped writes and unclean restarts. A monitoring system that silently holds two minutes while its settings claim a day is actively misleading, and of all tools it is the one that must not hide its own gaps.
Worked through in Bottlenecks and improvements →How do you find an N plus one query?
By tallying repeated query patterns within a single request and flagging when the same shape runs more than a handful of times. It is the single most common cause of a slow page and the hardest to see in a log of individual queries, because each one is fast. Recording the file and line that issued the query is what turns "this query is slow" into "this line is slow".
Worked through in High level design →Capturing request bodies sounds risky.
It is, in two ways. It is a security risk, handled by redacting passwords, tokens, card numbers and keys before anything is stored rather than before it is displayed. And it is a correctness risk: in one version here the error middleware read the body and put back only the first four kilobytes, so every request with a Content-Length reached the handler truncated. Mobile and curl uploads failed while browsers, which send chunked, did not.
Worked through in Bottlenecks and improvements →You have four replicas. Where is the dashboard?
There are four of them, and whichever one the load balancer picks is what you see. That is the structural limit of an in-process design and the point at which a real collector earns its cost. The bridge is an OpenTelemetry exporter: keep the in-process detail, ship spans out for the combined view.
Worked through in Scalability and performance →What should alerting look like?
Two-phase firing so a single spike does not page anybody, a cooldown so one problem is not fifty notifications, and burn-rate alerting against an objective rather than a raw threshold. A threshold on a noisy metric pages people for nothing, and the second time that happens the alert stops being read.
Worked through in Low level design →Memory or SQLite for storage?
Memory is a ring buffer with the highest write ceiling and loses everything on restart. SQLite appends to a queue committed in batches by one writer, so it survives a restart at a lower ceiling. For an application restarted more often than it is busy, which is most of them, surviving the restart is worth more than the throughput.
Worked through in Capacity estimation →1.Problem statement
Something is slow. Answering why needs per-request latency, the queries each request ran, how long each took, where in the code they came from, what the heap and the goroutine count were doing at the time, and which of those is unusual. That is a known problem with known answers, and all of the standard ones are a second deployment: a collector, a time series database, a dashboard, and a budget line.
For a large team that is correct. For the application that is one container and a database, it is a monitoring stack that is bigger and harder to run than the thing it monitors, so it does not get installed, and the answer to "why was it slow" stays "nobody knows".
An in-process profiler changes the trade. It costs a dependency instead of an architecture. What it must not cost is the thing it is measuring: a monitor that adds latency to the request path, or that grows without bound until it is the reason for the outage, has made the problem it was bought to solve.
There is a subtler requirement too. The moment you sample to control cost, every total computed from the samples is wrong, and an error rate that is wrong in an unknown direction is worse than no error rate. So the counts and the traces have to be separated: sample what you store, count everything.
The system has to be able to:
- Trace every request with a latency, a trace identifier and a route.
- Capture every database query with its duration and the file and line that issued it.
- Detect N plus one patterns within a single request.
- Sample continuously: heap, goroutines, garbage collection pauses.
- Serve CPU, heap, allocation, goroutine, mutex and block profiles to go tool pprof.
- Show the database plan behind a slow query, with EXPLAIN and never EXPLAIN ANALYZE.
- Compare a route against its own rolling baseline, so a regression is told apart from a route that was always slow.
- Capture panics and errors with a stack trace, fingerprinted so duplicates collapse.
- Run health checks on a schedule and answer Kubernetes probes.
- Alert on a threshold without firing on a single spike.
- Compute service level objectives from exact counts, not from samples.
- Never block the request path on storage.
- Say when its own buffers, rather than the retention setting, are what limits history.
2.System requirements
Functional requirements
- Middleware for tracing and for error and panic capture.
- A GORM plugin capturing queries, callers, N plus one patterns and pool statistics.
- A runtime sampler on a five second interval, with goroutine leak detection.
- Memory ring buffer storage, or SQLite for survival across restarts.
- Per-minute rollups of every request, independent of the sample rate.
- Per-route rolling baselines, with the deploy a step change belongs to.
- Authenticated pprof endpoints, with mutex and block profiling opt-in.
- EXPLAIN plans for slow queries, opt-in because they are extra queries.
- A threshold alert engine with two-phase firing and a cooldown.
- Multiwindow burn-rate alerting on service level objectives.
- Secret redaction over captured bodies, errors and outbound URLs.
- Notification channels: Slack, Discord, email, and webhooks signed with HMAC.
- A Prometheus exposition endpoint, and JSON or CSV export.
- A WebSocket feed with per-client channel subscriptions.
- An embedded React dashboard of twelve pages.
Non-functional requirements
- Never in the request path. storing a metric is a ring buffer push or a queue append. The request never waits for storage, because a profiler that adds latency is measuring itself.
- Bounded by construction. fixed-size ring buffers with an atomic head index. Capacity is the ceiling on history, and the allocation grows towards it rather than being reserved at startup, so an idle process does not pay for traffic it never had.
- Exact counts despite sampling. per-minute rollups count every request. Totals, error rates, objectives and load-test comparisons are therefore independent of the sample rate and of how much the buffer held.
- Honest about its own limits. it alerts when buffer capacity rather than the retention setting is what bounds history, when writes were dropped, and after an unclean restart. A monitor quietly losing data is worse than no monitor.
- Redacts before storing. passwords, tokens, card numbers, JWTs and keys are stripped from bodies, error messages and outbound URLs whatever the field is called. A profiler is otherwise a credential store nobody meant to build.
- No CGo, no external service. pure Go SQLite and an embedded frontend. The reason it is installed is that installing it is one line.
3.Capacity estimation
Numbers for a mid-sized deployment. They are here to size the thing, not to predict your traffic: change an assumption and the sums below move with it.
Assumptions
| Parameter | Value |
|---|---|
| Requests per second | 926 average, 4,630 peak |
| Queries per request | 4 to 12 |
| Request record | ~500 bytes |
| Query record | ~300 bytes |
| Runtime sample interval | 5 seconds |
| Default retention | 24 hours |
Per-request overhead
The design requirement is that this stays invisible. The moment it is a percentage of request time, every latency number it reports includes itself.
Memory at full sampling
Which is exactly why the capacity warning exists. At this rate the buffer, not the 24 hour retention setting, is what decides how much history there is, and without being told nobody would know. The last line of that sum used to be a bug rather than a design: the buffers were allocated at full size up front, so a process serving almost nothing carried about 38 MB of a 45 MB heap and looked like a leak. v1.3.0 grows them instead.
Sampling, and what it does not touch
This is the central design decision. Sampling controls storage; the rollups keep totals and error rates exact. Computing an error rate from a 10% sample would give an answer with no stated error bar, which people would then act on.
SQLite throughput
Runtime sampling
4.High level design
Middleware and a database plugin feed a storage layer that never blocks, and everything else reads from it.
Core components
- Tracing middleware. a trace identifier, a timer and a route label per request. Sampled for storage, counted always.
- Error middleware. recovers panics, captures stack traces and request context, fingerprints the error so repeats collapse into one entry with a count.
- GORM plugin. every query with its duration and the file and line that issued it, plus per-request tallies of repeated patterns for N plus one detection, plus pool statistics.
- Runtime sampler. heap, goroutines and garbage collection on a five second tick, with a leak threshold.
- Storage. a generic ring buffer in memory, or a batched SQLite writer. Both are append-and-return; neither makes a request wait.
- Aggregator. per-minute rollups of every request, which is what makes totals and objectives exact while traces are sampled.
- Alert engine. threshold rules with two-phase firing so a single spike does not page anybody, a cooldown, and signed webhook delivery.
- Capacity watch. notices when the buffer rather than the retention setting bounds history, when writes were dropped, and when the last shutdown was unclean.
- Baseline store. a long, cheap per-route per-percentile summary, so the current figure can be read against what the route normally does rather than only against a threshold, and a step change can be attributed to the deploy it followed.
- Profile endpoints. CPU, heap, allocation, goroutine, mutex and block profiles behind the dashboard credentials. The dashboard says which route; these say which line.
Request flow
A request measured, and what it costs the request
- 1A request arrives. The tracing middleware starts a timer and attaches a trace identifier, which also goes out in the response so a complaint can be tied to a record.
- 2The handler runs. Nothing about it knows it is being measured, which is the point: instrumentation each handler participates in is instrumentation half of them forget.
- 3Every query the handler issues passes through the GORM plugin, which times it and records the file and line it came from. The caller is what turns "this query is slow" into "this line is slow".
- 4Repeated query patterns inside one request are tallied. Five or more of the same shape is an N plus one, which is the single most common cause of a slow page and the hardest to see from a log of individual queries, because each one is fast.
- 5Captured context is redacted before it is stored: passwords, tokens, card numbers, JWTs, keys, whatever the field is named. Without this a profiler becomes a store of credentials that nobody decided to build and nobody is guarding.
- 6The records are pushed into a fixed-size ring buffer, or appended to a queue that one writer commits in batches. Either way the call returns immediately; the request does not wait on storage, because a profiler that adds latency is measuring itself.
- 7Separately, and regardless of the sample rate, the request is counted into a per-minute rollup. This is the decision that makes the numbers trustworthy: traces are sampled, counts are complete, so an error rate is a fact rather than an estimate with no error bar.
- 8The dashboard, the alert engine and the objective burn rates all read from the rollups for anything that is a total, and from the buffers for anything that is an example. When the buffer rather than the retention setting is what limits history, it says so.
Data flow
- Sampling decides what is stored, never what is counted. Every total in the product comes from the rollups.
- Redaction happens before storage, not before display, so a leaked secret is never written down in the first place.
- The ring buffer is a fixed slice with an atomic head. Bounded memory is not a tuning option, it is the data structure.
- The SQLite path trades peak write throughput for surviving a restart, which is the right trade for an application that is restarted more often than it is busy.
5.Technology stack
| Component | What it is |
|---|---|
| Language | Go, no CGo |
| Host | Gin and GORM |
| Storage | in-memory ring buffers, or pure Go SQLite |
| Default retention | 24 hours |
| Defaults | sample rate 1.0, slow request 1s, slow query 200ms, N+1 at 5 |
| Runtime sampling | every 5 seconds, leak threshold 100 goroutines |
| Export | Prometheus, JSON, CSV, OpenTelemetry |
| Dashboard | 12 pages embedded in the binary |
6.API design
Mounted under the configured prefix
| Method | Endpoint | What it does |
|---|---|---|
| GET | /pulse/ui | The embedded dashboard |
| GET | /pulse/api/requests | Traces, filtered by route, status and latency |
| GET | /pulse/api/db/n1 | N plus one findings grouped by route and pattern |
| GET | /pulse/api/slos | Compliance, error budget and burn rates |
| GET | /pulse/api/routes/baselines | Each route against its own rolling baseline |
| GET | /pulse/api/lifecycle | Deploy time and instance identity, to attribute a step change |
| GET | /pulse/api/profile/heap | A heap profile, in pprof format |
| GET | /pulse/api/profile/block | 409 and the option to add, when block profiling is off |
| GET | /pulse/metrics | Prometheus exposition |
| GET | /pulse/live | Kubernetes liveness |
| GET | /pulse/ready | Kubernetes readiness, composite over health checks |
How Grit mounts it, including the bug the comment is there to prevent
pulseOpts := []pulse.Option{pulse.WithAppName(cfg.AppName),pulse.WithCredentials(cfg.PulseUsername, cfg.PulsePassword),pulse.WithExcludePaths("/studio/*", "/sentinel/*", "/docs/*", "/pulse/*"),pulse.WithPrometheus(),// Request-body capture needs v1.0.1 or later. Before that the error// middleware read the body and put back only the first 4 KB, so every// request carrying a Content-Length reached the handler truncated:// uploads from mobile and curl failed while browsers, which send// chunked, did not. Pin below v1.0.1 and you want// pulse.WithRequestBodyCaptureDisabled() back.}if cfg.PulseStorage == "sqlite" && cfg.PulseStorageDSN != "" {pulseOpts = append(pulseOpts, pulse.WithSQLite(cfg.PulseStorageDSN))}if cfg.PulseProfiling {// Behind the dashboard credentials. A 30s CPU profile anyone can ask// for is a denial of service, so this is opt-in and stays opt-in.pulseOpts = append(pulseOpts, pulse.WithProfiling(), pulse.WithPprofHandlers())}// Mutex and block profiling cost something merely to collect, so they are// separate switches. Left off, asking for the profile answers 409 and names// the option, rather than returning an empty one that reads as "all clear".if cfg.PulseMutexProfileFraction > 0 {pulseOpts = append(pulseOpts, pulse.WithMutexProfiling(cfg.PulseMutexProfileFraction))}if cfg.PulseBlockProfileRate > 0 {pulseOpts = append(pulseOpts, pulse.WithBlockProfiling(cfg.PulseBlockProfileRate))}p := pulse.Mount(context.Background(), r, db, pulseOpts...)
7.Low level design
Core types
O(1) append into a fixed-size slice behind an atomic head index and a short write lock. The reason memory is bounded regardless of traffic.
Times every query, records the caller, and keeps per-request tallies of repeated patterns. Tallies have an idle expiry so an abandoned request cannot leak one.
Per-minute rollups of every request. The separation between what is sampled and what is counted lives here.
Reports when a ring buffer rather than the retention setting is what bounds history. A monitor that silently holds two minutes of data while its settings claim a day is actively misleading.
A rolling per-route per-percentile summary over a long window, with the current figure expressed as a ratio against it. Cheap to keep, because it is a summary of records that have already aged out, and the only thing in the product that can tell a regression from a route that was always slow.
*bool and *float64 so "not set" and "explicitly zero" are different. A sample rate of 0 and an unset sample rate must not mean the same thing.
Design principles applied
- Measuring must not be measurable. push and return. Every design choice in the storage layer exists so the request path never waits.
- Sample the examples, count the totals. sampling is necessary and making totals approximate is not. Rollups keep the numbers exact at a cost that does not depend on the sample rate.
- Bounded by the data structure. a ring buffer cannot grow. That is a stronger guarantee than a cleanup goroutine that is supposed to keep up.
- Report your own failures. dropped writes, truncated history and unclean restarts are surfaced. A monitoring tool that hides its own gaps is the one tool that must not.
- Redact on the way in. before storage, not before display. The alternative is a database of captured secrets with a filter in front of it.
Patterns
| Pattern | Where it is used |
|---|---|
| Ring buffer | bounded retention as a data structure |
| Batched single writer | durability without blocking the request |
| Fingerprinting | duplicate errors collapsed into one entry with a count |
| Two-phase alerting | a threshold must hold, not just be touched |
| Multiwindow burn rate | the Google SRE workbook objective alerting |
8.Scalability and performance
- Overhead per request is microseconds and does not grow with traffic, because the work is a timer and a buffer push.
- Memory is fixed by the buffer sizes. The question is never how much memory it will use, it is how much history that memory buys, which is what the capacity warning answers.
- Sampling is the lever for storage volume, and it costs nothing in accuracy because the rollups count everything.
- Baselines are the one thing kept long. A per-route per-percentile summary costs almost nothing next to the records it came from, which is what makes "slower than last week" affordable in a process whose detailed memory is minutes.
- The SQLite backend serialises on one writer, which is the right shape for SQLite and a lower ceiling than memory. Choose it for surviving restarts, not for throughput.
- Everything is per process. Behind several replicas each has its own dashboard and its own view, which is the main structural limit of an in-process design and the point at which a real collector earns its cost.
- The OpenTelemetry exporter is the bridge out: keep the in-process dashboard for the single-instance case and ship spans to a collector when there are enough instances for that to be worth running.
9.Bottlenecks and improvements
What breaks first
- Per-process view. with four replicas there are four dashboards and no combined picture, and the one you reach through the load balancer is whichever replica answered.
- Buffer rather than retention. at high traffic a memory buffer holds minutes while the configured retention says a day. It is surfaced, and it still surprises people.
- Capture that changes behaviour. reading a request body to record it is a real risk to the request. In v1.0.0 it truncated every body with a Content-Length to 4 KB, so mobile and curl uploads failed while browsers did not.
- Dashboard exposure. it holds request bodies, errors and query text. Redaction reduces what it contains; it does not make the dashboard safe to leave open.
- Alert noise. threshold rules on a noisy metric page people for nothing, and the second time that happens the alert stops being read.
What to do about it
- Export to a collector once there are replicas. the OpenTelemetry path gives one combined view. Keep Pulse mounted for the per-process detail it is good at.
- Size buffers from the actual rate. requests per second times the history you want. Or move to SQLite, which trades write ceiling for a retention setting that means what it says.
- Pin the version when capture is on. v1.2.0 or later wraps the body and passes it through whole, and v1.3.0 stops the memory backend reserving its whole capacity at startup. Below v1.0.1, turn request body capture off.
- Judge a route against itself, not against a threshold. baselines give a ratio rather than an absolute, and the deploy marker attributes a step change to the release before it. A threshold cannot tell a route that doubled from a route that has always been that slow, and the first of those is the one worth waking up for.
- Authenticate the dashboard and exclude it from itself. credentials always, and exclude the monitoring routes from tracing so the tool does not fill its own buffers with views of itself.
- Prefer burn-rate alerts to thresholds. multiwindow burn rate fires on budget actually being consumed rather than on an instant being bad, which is most of the difference between an alert people act on and one they mute.
