Five minutes of everything
Serie: SiteArchitectureTeil 5 von 5
The post in this series that took GoBlog apart closed on a promise of further updates in the near future, which is the kind of sentence one writes in the confident expectation of never being held to it. The updates came all the same, and most of them came from one direction I had not anticipated: the instruments I had built to watch the blog turned out to be most useful when pointed back at themselves.
What follows is an account of that - of a sampling policy that did not do what I had described it as doing, of where the server’s time was actually going, and of a load test that found the slowest thing in the whole application sitting inside the very mechanism meant to keep it observable.
Once more, telemetry woes
The earlier post set out the trace policy with a certain satisfaction: whatever I cause myself is always exported, anonymous reading exports nothing unless something failed, and a failure drags its whole trace along with it. The policy was sound enough. The mechanism beneath it was not.
The decision of whether to keep a span was taken per span, as each one ended. That sounds innocuous until one recalls the order in which spans end, which is children first and the root last - the database statement finishes before the request that issued it. A trace that only learnt it was worth keeping late, because the handler failed after its queries had already returned, arrived at the backend as a root span and nothing else, its children long since discarded. The failures I most wanted to see in full were, by construction, precisely the ones I could see least.
The spans of a trace that is still undecided are now held in memory until a verdict arrives, and then either flushed in order or let go. The server span moved to the very outside of the middleware chain, too, where it had not been: panics used to unwind past it without a trace, and a good dozen routes - sitemaps, the robots file, the contact form - produced no span of their own at all, their outgoing calls drifting about as orphaned roots of traces nobody had begun.
And the policy changed while I was at it. A trace of every failure tells me what breaks, but nothing about what an ordinary page view looks like when nothing does, so public reading is now sampled at a tenth. The visitor’s address, browser and referrer travel on the span and nowhere else - not into metrics, not into logs - and two smaller embarrassments went out on the same occasion: the Telegram bot token, which the Telegram API expects in the URL path and which therefore sat in plain text on every outgoing span, and a client address that any visitor could set to whatever they pleased by sending a header of their own invention.
The second part of the quest: performance
With a few days of that data in Grafana, the question worth asking was no longer whether the blog was healthy but where its time was spent, and the answer was not the one I would have guessed. The database accounted for almost none of it. Feeds accounted for forty-one percent.
A feed renders every post it contains, in full, and a post with code in it spends nearly all of its rendering time in the syntax highlighter - ninety-eight percent, measured locally. Some of that is the honest cost of highlighting. Some of it was not, and the comment that now sits above the lookup explains the worst of it better than I could paraphrase it:
lexers.Get is not a map lookup. A name it does not know — and the empty name of a block without a language — makes it test every filename pattern of every registered lexer, some three hundred of them, before it gives up: 1.65 ms per block on a fast machine, against 10 µs to tokenise the block itself.
A post consisting largely of terminal transcripts paid that on every render, for every block. The answer depends on the name alone, and so it is now worked out once and kept.
Summaries had a similar habit. To produce the first paragraph of a post for a list page, the blog rendered the entire post, highlighter included, and then threw away everything but that first paragraph - twelve milliseconds per summary, for every entry of every list. A renderer without the highlighter yields the same text in a sixth of a millisecond, and rendered post bodies are now cached outright, cleared whenever the page cache is, and served from memory in under a microsecond.
The MCP server, meanwhile, was paying for a decision I had never actually made. App passwords were stored as bcrypt, which is exactly right for a password a person chose and entirely pointless for a forty-character token drawn at random:
A key-derivation function makes a leaked hash expensive to brute-force, which matters for a password a person chose; a generated token has about 258 bits of entropy and cannot be brute-forced at any cost per guess. What bcrypt at cost 12 did cost was a quarter of a second of CPU on every MCP request.
Generated tokens are now stored as SHA-256 digests, and an existing one has its hash replaced the next time it is used successfully. Passwords that came from the config file were chosen by a human being and keep their bcrypt. I watched the changeover happen in production: the first request after the deployment paid its quarter of a second one final time, and every request since has spent about half a millisecond on the check.
Two smaller matters rounded it off. The connection pool had been keeping four of its sixteen connections idle and closing the rest as soon as a burst of traffic subsided, which over four days came to 530 connections closed only to be reopened on the next burst. And tag pages filtered on the lower-cased tag, which no index covered.
Quis custodiet ipsos custodes?
Every one of those changes came with a question I could not yet answer from the dashboards. Is the render cache large enough, or merely full? How many bcrypt hashes are left? The answers became metrics - the occupancy of every cache in bytes against its bound, how often each one pushes out an entry to make room, and the stored app passwords by scheme - and the tests for those metrics turned up two faults of their own.
The first was found by a test that deliberately takes every connection in the pool and then asks for the metrics. The metric collector reads some of its figures from the database, and it waited for a connection like any other caller, so that with the pool exhausted it waited out the whole export deadline. The comment now standing guard over it states the consequence:
With the pool exhausted they would otherwise wait for a connection until the reader’s export timeout, and the export of that cycle, every metric in it, would fail at the moment the pool gauges matter most.
A saturated pool, in other words, would have made the pool’s own gauges vanish from the dashboard at the precise moment they had something to say. The pool’s figures are read first now, from counters that need no connection at all, and the collector’s own statements give up after two seconds.
The second showed up in the logs on every deployment: five errors, each reporting that the database was closed. The shutdown steps all run at once, and the pool had been closing before the final export of metrics, which reads from it. The pool now waits for that export to finish, and the most recent deployment went by without a single error.
Does it scale, though ?
That left the question I had actually set out to answer: how well does the cache hold up when somebody leans on it? So I leant on it - sixteen clients requesting every page in the sitemap and every feed, at random, from my own machine for five minutes.
The cache held. It answered 78,663 page requests and missed none. Everything else about the run was wrong. Throughput began at 577 requests a second and fell steadily to 175. The server’s own time per request rose from one and a half milliseconds to twenty, evenly across every kind of page, and the CPU, rather than working harder, grew less busy as the test went on. A machine that is doing less and achieving less is a machine waiting on something, and since memory and the number of goroutines stayed perfectly flat, that something had to be inside the process.
It was the decision the earlier post defended hardest. A trace’s verdict has to outlive its root span, so that work detached from a request - a Telegram announcement, a federation delivery - still knows whether its trace is being kept. “Therefore, it survives for five minutes,” I wrote then. What I had not considered was what five minutes of verdicts amounts to under load: every single trace of the last five minutes, kept or dropped, in one table. Removing the expired ones meant walking the whole table, and that walk ran on every new request, under the one lock every span has to take. The more requests there had been, the longer each new one waited behind the others - a cost quadratic in the traffic, serialised onto a single core, which is exactly why the CPU looked so idle.
Since every verdict lives for the same five minutes, they expire in the order in which they were recorded, and so the fix is a queue: verdicts go in at the back as their traces finish and come out at the front as they fall due. The comment above it says what it must guarantee:
It runs on every new trace, under the lock every span takes, while the table holds every trace of the last TTL; so it must cost each verdict one visit in total rather than a visit per request, which a scan of the table did.
At 150,000 verdicts a request had been paying a full millisecond for that walk; it now pays under one microsecond, and the same whether the table holds a hundred thousand verdicts or none. On the way through I found a second fault in the same table: a verdict whose root span ended a second time was never removed at all, which over a long enough uptime is a leak however rarely it happens.
The same test against the new build, then. 196,120 requests in five minutes, every one of them answered from the page cache and not one of them reaching the renderer; between 630 and 670 requests a second from the first half-minute to the last; and the server’s own share of each request flat at three quarters of a millisecond throughout. What remains of the twenty milliseconds my client measured is the distance between my desk and the data centre, and that is not something a change to the Go code can do anything about.
The per-article counters, I should add, now believe that this autumn’s posts enjoyed a sudden and remarkable revival late one Friday evening. They were counting exactly as they were built to, and I was the one who chose to let them.
One Go binary, then, that now tells me how full each of its caches is, how many slow hashes it still keeps, and what its connection pool is doing at the moment the pool runs out - and that was being slowed down, for want of a queue, by the very table it uses to decide what is worth watching.
Tags: Architecture, Go, OpenTelemetry, PostgreSQL, Self-hosting
