ENGINEERING NOTE / 09 SQL SERVERPOSTGRESQLMARIADBSCYLLADBWSFCARCHITECTURE
From Daily Checks to a Database Engineering Command Center
It started as a way to stop running the same checks by hand. The interesting engineering began when the monitoring system itself needed a work queue, ownership, recovery and inventory discovery — and kept going when the same surface started changing production: a second queue, one executor, explicit confirmation and an audit trail. The whole thing was specified by me and built with AI as the implementation engine.
TABLE OF CONTENTS
- Make the routine disappear
- One process should not own the whole estate
- Claiming work is not enough — ownership matters
- Metrics became the contract between collectors and operations
- A model has to beat a straight line
- The AI health report is a filter with a model on the end
- Analysis: capture everything, decide deterministically, read once
- Findings get a memory
- Inventory discovery was the point where monitoring became management
- Where observation stopped being enough
- The second queue: how a change gets to run
- The guardrails that came with it
- How it was built: my design, AI as the implementation engine
- Takeaway
The starting point was ordinary database operations work: check whether services are up, confirm backups, look for replication problems, inspect disk space, review jobs, and repeat the same process across several database engines.
The estate included SQL Server, PostgreSQL, MariaDB and ScyllaDB, with the SQL Server instances living on Windows failover clusters. The old process depended on several tools, manual sessions and engine-specific scripts. It produced a snapshot once a day, had almost no useful historical context, and naturally developed coverage gaps whenever the person doing the checks was unavailable.
The obvious answer was “automate the checks.” That was necessary, but it was not the interesting part.
A single script can automate one check. A platform that continuously inspects a heterogeneous database estate has to answer a different class of question: what is the source of truth for inventory, how does work get distributed once one collector is no longer enough, what happens if a worker dies mid-check, how do two workers avoid duplicating the same work, which metadata belongs in a metric label, how does a new endpoint enter the system without someone hand-editing configuration — and what changes the moment the same surface starts doing more than observing?
Those questions are what turned a collection of scripts into a small distributed system. The last one is what turned the distributed system into a control plane.
Make the routine disappear§
The first version replaced a human, once-a-day workflow with collectors running on a short interval and exporting Prometheus-compatible metrics. The portal reads Prometheus directly: thresholds are configured in the portal, and whatever breaches one becomes an alert card on the home page. There is no dashboarding layer in between any more — the one that was there at the start turned out to be a second place to maintain the same thresholds, and it went.
-
01 BEFORE
Engine-specific tools, a manual connection per endpoint, run checks, interpret output, repeat.
-
02 AFTER CONFIRMED
Inventory drives scheduled work; engine-specific collectors export Prometheus metrics; the portal evaluates thresholds and raises the breaches; a human reviews anomalies.
The home page started as a list of whatever was breaching. That answers what is wrong now, and nothing else: it cannot say whether this week is better than last. It now leads with four health KPIs — uptime, backup success rate, active alerts and hosts with alerts — each scored against a target, with the change from the previous period and a trend behind it. Each card opens a page with the trend against the target and the hosts that pull it down, worst first.
The trends were the first thing that did not scale naively. A thirty-day range query over tens of thousands of backup-age series took the better part of a minute; the cards instead take a couple of dozen sampled instant queries per period, cached and refreshed in the background.
The direct time saving was real: the manual round had been taking roughly two hours of focused DBA time every day, and it became a short anomaly review over a page that had already done the looking.
Removing the dashboarding layer left one gap: nothing showed a host’s metrics over time any more, and the useful question is usually a correlation — did the long-running queries start when page life expectancy dropped? The portal grew a Metrics page for exactly that: up to eight hosts picked by environment, site, product and engine, panels as time graphs with the worst value per step, and a click on any moment to see what was running then. Each engineer keeps their own saved dashboard.
But the operational change was larger than the two hours. The detection window moved from “someone looked today” to a regular automated interval, and engines that previously had weaker coverage entered the same operating model.
The distribution model changed with it. The daily round had belonged to whoever was on call — one person, looking, and everyone else finding out later if at all. The report is now generated on a schedule and posted straight into the team’s Microsoft Teams channel. Estate health stopped being something one engineer went and fetched, and became something the whole team receives, at the same time, in a place they already are.
- DBA TIME RECLAIMED
- ≈2 h/day
- WHO GETS THE REPORT
- the team
- DELIVERY
- Teams
That last one matters more than it sounds. A report someone has to go and open is a report that gets opened when someone remembers. A report that arrives where the team already talks is one that gets read, questioned and picked up — and any engineer, not only the on-call one, can take an item.
The platform also had a second purpose: lower the barrier for the rest of the database team to contribute automation and experiment with AI-assisted operational workflows. Instead of every engineer having to assemble inventory access, execution plumbing, metrics and a UI around each new idea, the portal gave the team a shared engineering surface to build on.
That solved the workflow problem. It also exposed the next scaling problem.
One process should not own the whole estate§
Once the number and variety of checks increased, I did not want collection throughput to depend on one long-running process iterating through the full inventory.
PostgreSQL became the coordination layer. At a high level, the schema contains an inventory and a queue of checks to perform. Workers claim work with the standard pattern:
SELECT ...
FROM check_queue
WHERE state = 'pending'
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1;
SKIP LOCKED matters because workers do not need to negotiate with each
other in application code. Each worker asks PostgreSQL for the next
claimable row; rows already locked by another worker are skipped. Adding a
worker increases collection capacity without changing collector logic.
The row is selected and its ownership state is updated in the same short transaction. The database row lock protects the atomic claim; the persisted owner and state protect ownership after that transaction commits. Those are two different guarantees, and the second is what lets the worker continue to own the work after the lock itself is gone.
The scheduler itself uses a PostgreSQL advisory lock so that only one worker instance performs the scheduling role at a time — a leader election cheap enough not to justify a separate coordination service for this amount of work.
Two refinements arrived once there really were several replicas. A due check goes back to the worker that ran it last, and another worker takes over only after a grace period, so hosts do not hop between replicas every cycle. And each worker drops the series for hosts it is no longer the latest checker of, so Prometheus never sees the same host from two replicas, or a frozen value for a host nobody checks any more.
Claiming work is not enough — ownership matters§
The first queue design still had a failure mode: a work item being “in progress” did not by itself make completion ownership explicit. With multiple workers, the system needs to distinguish this check is running from this specific worker owns this claim and is the only worker allowed to complete it.
The queue was changed so a worker records its identity when it claims an item. Completion is ownership-aware — a different worker cannot mark that item complete, and a worker that lost its claim logs the fact instead of overwriting another worker’s result. There is also stale-claim recovery: if a worker disappears while holding work, the item cannot remain permanently stranded. Old claims become eligible for recovery after a bounded timeout.
-
01 PENDING
A check is eligible and unclaimed.
-
02 CLAIM
A worker records its own identity as owner and moves the item to RUNNING.
-
03 RUNNING → COMPLETE
The owning worker, and only the owning worker, marks the item complete.
-
04 OWNER DISAPPEARS OBSERVED
The claim goes stale after a bounded timeout and returns to PENDING.
The important part is not the exact timeout. It is that failure recovery is part of the queue’s own semantics rather than an operational instruction that says “restart the worker if it gets stuck.”
Metrics became the contract between collectors and operations§
Each database engine has different native concepts, but operations needs a common vocabulary. The metrics layer normalises signals such as connectivity, service state, disk capacity, backup health, replication state, scheduled jobs and engine-specific cluster health. Labels carry dimensions such as engine, endpoint, environment and operational role.
That abstraction is useful because the portal does not need to understand how SQL Server, PostgreSQL, MariaDB or ScyllaDB obtained a particular signal. The collector owns engine semantics; the metrics layer owns the operational contract. It is also what let a fifth target type join without anyone downstream noticing: Windows failover clusters are now read over WinRM — node state, which node owns each SQL Server instance, how evenly the instances are spread — and they emit the same kind of series as everything else.
A model has to beat a straight line§
History also made forecasting possible. Every volume with a week of disk history gets a predicted date on which it reaches 90% used. The baseline is a linear forecast, recalculated once a day by whichever worker holds the scheduling role. Next to it, an optional container keeps scikit-learn out of the collector image and trains a random forest per volume that predicts the daily change in used space from calendar features.
The interesting rule is which forecast gets used. Each model is scored on the last two weeks of history that it did not see, and the forest replaces the line only when it beats it by at least 5%. On flat volumes the two errors sit within rounding of each other, and without the margin the stored model flipped from one retrain to the next on a tie. A more complex model has to earn its place; a tie goes to the one that is easier to explain.
The AI health report is a filter with a model on the end§
The normalised metrics layer is also what made a language model useful here rather than merely impressive. A scheduled job produces a written health report for the estate and posts it to the team — but the interesting design decision is what the model is allowed to see.
The naive version of this feature ships a dashboard’s worth of metrics into a prompt every morning and asks for a summary. That is the version that gets expensive, slow and vague at exactly the same time.
Instead, thresholds are evaluated first, deterministically, before any model is involved. Rules decide what counts as breaching. Only the breaching series — plus the small amount of identity a human needs to act on them: engine, endpoint, environment, operational role — are assembled into the payload. The model receives an exception set, not an estate.
Three things follow from that boundary, and each of them was worth the restraint:
Signal. A model asked to find the anomaly inside thousands of healthy rows will either bury the real one or invent a plausible one. Given only what already breached, it has nothing to hallucinate a problem out of — the findings are constrained to metrics that a human can go and check.
Cost and latency stay bounded. Context is a budget, and the estate is not a fixed size. Tying the request to the breach count rather than the inventory count is what keeps a scheduled job predictable as the estate grows.
Reviewability. Every statement in the report traces back to a specific metric on a specific endpoint at a specific time. That is what makes the output something an engineer can disagree with, which is the minimum bar for letting generated text into an operational channel.
Analysis: capture everything, decide deterministically, read once§
The same discipline shaped the on-demand path, and it grew into a section of its own. An engineer picks an engine and hosts from the product and environment tree — or a whole failover cluster — and the checks to run: activity, error log, wait statistics, resources, configuration, top queries. Every host is captured at the same moment, twice a gap apart for the checks that compare snapshots, so the four nodes of a cluster are looked at as one picture rather than four conversations.
Rules run over the captures first. A full transaction log, a volume under five percent free, a login storm, a request running for longer than the threshold — each is a deterministic finding with evidence and a code, before any model has seen anything.
Then the combined picture is read once. The model gets the findings, the captures and a little context, and returns priorities first, per-node detail after, and — this is the part I care about — it is asked to confirm, rank or dismiss each deterministic finding, add what the rules missed, and finish with what this capture cannot tell.
The model may also propose fixes. It does not get to run them. A suggestion is catalogued with its risk and a score, shown as the script it would run, and marked as unverified output; an engineer reviews it, and only then does it go through the same action job queue as every other change, against the host it was written for. Suggestions expire a couple of hours after the capture they came from, because a fix written against a snapshot is only as current as the snapshot. A KILL carries the fingerprint of the session it names, and the executor compares it before acting — if that session is gone, or a different one has its id, the job skips rather than guessing.
Then the platform checks its own work. A finished fix queues a read-only run of the same host, capturing only the checks the original finding came from, and the card reports each finding as gone, still there, or not checked. A fix is not done when its script exits zero; it is done when the next look agrees. The whole loop, from capture to verdict, has a note of its own: The Model Proposes, the Human Disposes, the Platform Verifies.
Findings get a memory§
Every check, every health report and every analysis run used to rediscover the same breaches from scratch. Each one was accurate and none of them knew whether it had seen the problem before — which is the first question anyone asks.
Findings now have an identity: one item per host, port and finding. An item opens when a breach is first seen, counts every sighting after that, keeps its history, and reopens with that history if it comes back. Two decisions made it useful rather than noisy:
- Fold per host, not per series. Backup age is reported per database. When the tracker first ran on the development stack, about nineteen thousand breaching series folded into nine items — the breaching databases counted, the worst five named.
- Condition labels are evidence, not identity. A database that goes from RESTORING to OFFLINE is still the same problem, so state, role and volume live in the evidence rather than in the key.
And one rule that matters more than both: an item resolves by itself only on evidence that it is gone — a successful check that collected the metric and found it under the threshold. A check that failed to connect proves nothing, so it resolves nothing.
The first version was fed by the health reports and the analysis runs as well. It has since been narrowed to a single source: the collectors’ own checks. Each check updates only its own host’s items, and a check older than the host’s last one changes nothing. The design, and how resolving turned out to be the hard half, is in A Finding Needs an Identity Before It Can Have a History.
Inventory discovery was the point where monitoring became management§
The system originally assumed that inventory already existed. That eventually became too manual, so I added a discovery/onboarding flow to the portal: an operator submits a candidate endpoint, and the platform runs a verification pipeline before adding it to inventory.
The public version of that flow is intentionally simplified:
- Candidate endpoint submitted by an operator.
- Derive approved metadata for the endpoint.
- Probe the expected listener.
- Attempt real engine authentication — an actual database-level login with the appropriate engine driver, not just a TCP handshake.
- Validate engine context.
- Create the inventory entry.
A successful network connection is not enough — a port being open only proves that something answered. The discovery flow performs an actual database connection before accepting an endpoint, which catches the case where DNS resolves and a listener exists but the endpoint is not a usable target for the platform.
That was a subtle architectural shift. The portal was no longer merely reading metrics about a preconfigured estate; it had started to participate in the lifecycle of that estate by verifying and onboarding resources into it.
Where observation stopped being enough§
That is why I now think of it less as a “DBA dashboard” and more as a database engineering command centre. Monitoring remains the foundation, but management actions have been built around the same inventory and execution model — and that changes the design requirements. A monitoring bug can produce a bad graph. A management bug can change a production system.
The Clusters page is where that shift is easiest to see. It starts as observation: one tile per geo-cluster, live and DR sites, the replication link between them, health overlaid from the same Prometheus series everything else reads.
Drilling into a MariaDB geo-cluster shows the Galera members on each side, the async link from the live site to the read-only DR site, and — top right — the failover action itself. A failover swaps live and DR roles for every member, reverses the replication link, moves the read-only expectation to the new DR site, flips the matching cluster rows, and runs as one transaction behind a confirmation typed back by the operator.
The second tab on that page is where the platform started repairing things rather than reporting them. Replication repair reads both sides’ state and the last errors, offers the fixes that fit, applies one ranked fix at a time, and as a last resort rebuilds the DR side from a fresh backup of the live master — every step re-verified live on the nodes, and refusing on any surprise.
The rebuild is where production corrected the design twice. The first version streamed the backup from the live master to the DR node, and the link between the sites turned out to run at well under a megabyte a second — a copy step measured in most of a day. But the backup volume is already replicated to the other site for disaster recovery, so the rebuild now restores from that copy, waits for it while a fresh backup is still arriving, and keeps the network copy only as the fallback. The second correction was the replica’s start position: the GTID position a backup records mixes the master’s own writes with history it once applied as a replica, and neither that nor the one-domain slice of it the tooling used is a position the master’s binary logs can serve. The rebuild now starts from the GTID of the backup’s own binlog coordinates instead — and checks the position against what the master can still serve as soon as the backup is extracted, so a bad one fails minutes into the job rather than at the very end of it. That failure has its own write-up: The Backup’s GTID Was Not the Master’s Position.
SQL Server got the same treatment through the Windows failover clusters. The drill-in shows the cluster members, and underneath them the live distribution of SQL Server instances across the nodes, read over WinRM.
From there, two actions. Rebalancing moves roles between nodes, one at a time, until no node owns more than its share — and because a patching window leaves roles wherever the last reboot put them, it can run on a schedule that only moves anything when the cluster is actually uneven.
Even spread is not the same as good placement, though. Where a cluster has more instances than nodes, some of them have to share, and which ones share matters more than how many. A read-only card suggests the pairing: it takes each instance’s hourly CPU, batch requests and buffer pool churn over a week, tries every grouping a rebalance allows, and picks the one whose busiest node is lowest — adding the instances’ loads hour by hour, so two instances busy at different times pair well. It also works out the worst case when each node is drained for patching. It changes nothing; if the cluster’s preferred owners would leave it noticeably worse than the suggestion, the rebalance dialog says so.
Max server memory follows the instances. Each instance’s memory ceiling is set from the node it is actually running on — the node’s RAM less a reserve, shared out by weighted shares — once the roles have stayed put for long enough after a move. It replaced a scheduled task that lived on every node and knew nothing about the others.
It also gained a hard floor the hard way. One run set an instance to about 5 GB — arithmetically correct for its share of a crowded node, and too little for the database upgrade scripts a patch runs on the instance’s first start, so it did not come up. No target now goes below a configurable minimum (10 GB by default), even when that takes a node past its budget; the job summary says when it does. The other change runs the opposite way: when the shares suggested by a week of load drift far enough from the saved ones, the tab nudges — and leaves the decision to a human.
The cluster-aware memory reconciliation has a note of its own: Making SQL Server memory follow the failover.
The second queue: how a change gets to run§
None of those actions are executed by the portal. Nor by the check workers, which are read-only by construction and hold read-only credentials. A management action requested in the portal — or over the REST API, which has an endpoint for every one of them — becomes a job in a second queue, and the stack’s single action executor is the only process that ever claims one.
The queue semantics that were useful for monitoring turned out to be even more important here, and stricter:
- Claimed once. A job is claimed by one executor and heartbeats while it runs; a job whose executor goes quiet is marked lost, not retried.
- Nothing retries itself. A failed change is a decision for a human. The action can be requested again; the platform will not do it on its own.
- A running job can be stopped — and a stop is not an undo. The stop request rides back on the job’s next heartbeat; the executor terminates the job’s processes but not the wrapper around them, so the exit is still recorded and the job ends as failed, marked as stopped by whoever asked. Whatever it had already changed stays changed, and the job page says so.
- One change per target at a time. Jobs carry a lock key for the host or cluster they touch, so two changes to the same thing cannot interleave — and a geo failover, or disabling a host, is refused while jobs are still working on it, with the job that is in the way named.
- Changing actions need an explicit confirmation, stored with the job. A plain confirm for routine changes, the word typed back for a geo failover, and the host name typed back for a script or a high-risk fix.
- Schedules run as their owner. A Saturday-night rebuild requested on a cron schedule is checked against the owner’s permissions on every run, not once when the schedule was created.
- The monitoring loop closes it. When a changing job finishes, its host and every member of its geo-cluster are checked next, ahead of the backlog — and a host that was mid-check when the job ended is checked once more, because that check may have read the old state.
How a job is claimed, kept alive, locked, stopped and settled when its executor disappears is covered in Inspect and Change Are Different Verbs.
The guardrails that came with it§
Giving a web page the ability to fail over a production cluster raises the bar for everything around it, and most of the second half of the project went there rather than into new actions.
Every capability is a permission, and an editable matrix decides which role holds which. Directory groups map users to roles when they sign in; service accounts get tokens checked against the same matrix, so a script has exactly the rights its owner would have in the browser.
Every mutating action — in the browser or over the API — lands in the audit log with who, what, which host, from where, and the before and after.
And the smaller things that make the above hold: database, SSH and WinRM credentials are encrypted at rest and never shown again once entered; the PowerShell that reads and moves cluster roles is a fixed set of templates with parameters passed as data, never formatted into the script; and the coordination database is backed up on a schedule, because the inventory, the topology and the credentials cannot be rebuilt from the estate.
How it was built: my design, AI as the implementation engine§
The platform started as my idea and my implementation plan, and it was built with AI as the implementation engine throughout. That is worth stating plainly, because how the work was done is part of what the work demonstrates.
The order was the same every time, and the order is the whole method:
- Decide what the system has to guarantee. The inventory is the source of truth; a claim has an owner; a stale claim recovers on its own; a label is schema; an endpoint proves itself before it is trusted; a change runs once, in one place, and leaves a record.
- Write the plan before any code. Decompose the platform into units small enough to describe completely — this collector, this queue transition, this discovery step, this action’s lock key — each with an explicit acceptance condition.
- Let the model implement the unit. Engine-specific driver code across four engines and WinRM, exporter plumbing, the portal’s views, the executor, refactors and tests: this is work with a known shape, and a fast implementer working against a precise specification is very good at it.
- Review it as though a stranger wrote it, because in the way that matters, one did. Then verify against a real engine, not against a description of one.
What stayed with me was every judgement that a specification cannot be delegated from: the architecture, the consistency boundaries, the blast radius of anything that touches a production database, and the decision about what the system is for.
One consequence of building this way is that the platform ended up with an API for every flow a human can click through — analyse, review, run the suggested fix, read the audit row — because the thing that was helping me build it is also the kind of thing that would want to drive it. That has since stopped being hypothetical. An incident copilot now fetches, in one bounded, read-only call per incident, the service behind the alert, its hosts and clusters, and the live signals the check cycle now collects on every pass — blocking chains, long-running work, the oldest open transaction, waits by category — under a role of its own; and the production portal publishes its current problems to a small file that an MCP server reads, so an agent can ask what is wrong in production without holding a single production credential.
The other consequence was less flattering. After a few months the portal looked and read like generated output: invented terms, dashes and arrows standing in for punctuation, subtitles that repeated their headings. The fix was the same as for the code — a specification, applied everywhere. The UI moved onto an existing design system, and every template, message and permission description was rewritten to a controlled-English style guide: short sentences, imperative instructions, standard terms. Generated text needs the same review as generated code; it just fails more quietly.
The result is a delivery speed that would not have been available to one engineer doing operations work at the same time — a multi-engine collector fleet, a coordination layer, a portal, a discovery pipeline, an AI reporting path and an audited control plane — without giving up authorship of the design or accepting code into a production path that I could not defend line by line.
There is a symmetry here I did not plan and now think is the point. The discipline that made the build work is the discipline that made the health report work, and later the suggested fixes: be specific about what you are asking for, send only what is needed to answer it, and keep the judgement about correctness on the human side of the boundary. Used that way, AI is leverage on an engineer’s plan. Used the other way round, it is a very fast way to generate confident, unowned systems.
Takeaway§
The useful change was not that a dashboard replaced a checklist. It was that a once-daily, person-dependent operating routine became a continuously running system with distributed scheduling, worker ownership, failure recovery, multi-engine collectors, historical metrics and verified onboarding underneath it — and that its output stopped belonging to whoever happened to be on call.
The second change was the one I had been circling from the start: the same inventory, queue semantics and metrics turned out to be most of what a safe control plane needs. What they did not provide — one executor, explicit confirmation, a lock per target, no silent retries, an audit row for every change — is the part that separates a tool that reports on production from one that is allowed to touch it.