---
title: MS SQL [Tab]
slug: ms-sql-tab
createdAt: 2025-08-20T04:56:45.519Z
---

# 0) Big picture



**On each managed device (Windows/Linux/k8s node):**

- **Agent (service/daemon)**
  - **Collectors**
    - **SQL collectors**: instance inventory, configuration, storage, security, error log, databases/files, jobs, metrics, AG topology, backups, DB health.
    - **Service collectors**: generalized service inventory + OS/k8s/cloud status, endpoints, and service-level metrics for SQL Engine/Agent/Browser **and** any other product (IIS, Redis, NGINX, Kafka, etc.).
    - **Synthetic checks (optional)**: TCP/HTTP probes for exposed endpoints.
  - **Scheduler**: cadence tiers (discovery / snapshots / metrics).
  - **Local SQLite cache**:
    - Mirrors of selected server tables (trimmed types).
    - **Lookup catalogs** mirror (ref\_\*) with code→id mapping.
    - **identity\_map** (natural-key→UUID), **outbox** (deltas), **collection\_ledger** (when/what ran).
  - **Sync client**: batches idempotent ops to server.



**Server (PostgreSQL + API):**

- **Catalog endpoints** to deliver ref\_\* lookup rows to agents (by code).
- **Ingest API** (idempotent upserts; resolves lookup **codes→IDs**).
- **Merge/workers** to compute rollups, findings, KPIs, and alerts.



Security: mutual TLS or signed bearer; store SQL creds in OS keystore (DPAPI/libsecret), **never** plaintext.

# 1) Lookup catalogs (how agents use them)

- Source of truth: server ref\_\* tables (service kind/product/provider/platform/environment, endpoint protocol/type, metric name, health status, service status, start mode).
- **Agent boot**:
  1. Call GET /v1/catalog?since=… to download active ref\_\*.
  2. Cache them in SQLite (ref\_\* mirrors). Index by **code** and store the server **id**.
- **During collection**:
  - Always **emit lookup values as code** in payloads (e.g., product='MSSQL', service\_status='Running', metric\_name='CpuPct').
  - Server resolves code→id. If a new code appears, server **auto-creates** an active ref row (or rejects if locked down, your choice) and returns its id.
- Benefits: agents don’t break when catalogs evolve; tenant overrides still work (server maps to correct per-org row).

# 2) Schedules & cadences

| **Tier**          | **Interval (default)** | **What runs**                                                                                                               |
| ----------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| **Discovery**     | on start & hourly      | SQL instance discovery, databases list, service discovery (Engine/Agent/Browser/Other services), endpoints, AG membership   |
| **Snapshots**     | 15–60 min              | SQL config/storage/security/error log/backup coverage/DB health; service status & endpoints                                 |
| **Metrics**       | 1–5 min                | SQL perf metrics (CPU/PLE/BufferHit/BatchReq); **service metrics** (status, CPU, memory, restarts, port listening, latency) |
| **Heavy/nightly** | 24h (off-peak)         | Fragmentation sampling, extended security audits, long error-log scans                                                      |

# 3) Data collection (what to run and where it goes)



## 3.1 Service discovery & status (generic)



**Windows (SCM/WMI/PowerShell)**

- Enumerate: Get-Service 'MSSQL\*','SQL\*','SQLBrowser','SSRS\*','SSIS\*','SSAS\*' (+ any extra services you support).
- Details: Win32\_Service → Name (service\_name), DisplayName, PathName (binary\_path), StartMode (start mode), State→ runtime status.
- **Process**: map service → PID; Get-Process -Id for CPU %, WorkingSet MB, Handles, Threads.
- **Ports**: Get-NetTCPConnection or netstat -ano; join by PID to list endpoints.
- **Restarts**: EventLog (7031/7034/7036) in last 24h → crash\_count\_24h.



**Linux (systemd)**

- systemctl show \<unit>: ActiveState, ExecMainPID, ExecMainStartTimestamp, FragmentPath.
- /proc/$PID or ps -o pcpu,rss for CPU/mem.
- ss -ltnup for port listeners; join by PID.



**Kubernetes**

- List Deployments/StatefulSets/Pods; compute service runtime status from pod phases & container restarts (crash\_count\_24h); capture ports from container specs; store platform='Kubernetes', cluster\_name, namespace.



**Cloud PaaS (e.g., AWS RDS/Azure SQL)**

- Use cloud APIs (DescribeDBInstances/etc.) to map **status** and metadata; start\_mode='NotApplicable'; no local PID.



**Persist → monitored\_service**

- Natural key (agent):
  - Host-bound: device\_id|service\_name
  - Cloud: organization\_id|provider|region|service\_name
- Columns: taxonomy via lookup IDs (resolved server-side from code), identity fields, runtime service\_status\_id, start\_mode\_id, pid, uptime\_seconds, last\_start\_time, crash\_count\_24h, listen\_endpoints JSON (quick view), **health rollup** (see §5), detail JSON.



**Normalize endpoints (optional) → monitored\_service\_endpoint**

- For each port: upsert (service\_id, protocol\_id, port, ip, name, endpoint\_type\_id, tls\_enabled, path).
- Keep the array in listen\_endpoints too for quick reads; use the table when you need filtering/alerting by port/protocol.



**Service metrics → service\_health\_metric**

- Emit per metric:
  - ServiceStatus (1/0)
  - CpuPct, MemoryRSSMB, Threads, Handles
  - Restarts24h
  - PortListening (per endpoint; store port/protocol in extra)
  - Optional synthetic: HTTP\_2xxRate, LatencyMs, TLSExpiryDays
- Evaluate status via thresholds (see §5) and store status\_id + threshold\_snapshot.



**Link to SQL domain**

- For SQL Engine/Agent/Browser, one of:
  - Set monitored\_service.instance\_id (if discovered SQL instance exists), **and/or**
  - Add a service\_binding row with bound\_entity\_type='sql\_server\_instance' & bound\_entity\_id=….



## 3.2 SQL instance inventory →&#x20;

## sql\_server\_instance



Use T-SQL (minimal round trips):

:::BlockQuote
\-- Version, edition, collation, HADR flags SELECT SERVERPROPERTY('ServerName')        AS server\_name, SERVERPROPERTY('MachineName')       AS machine\_name, SERVERPROPERTY('ProductVersion')    AS product\_version, SERVERPROPERTY('ProductLevel')      AS product\_level, SERVERPROPERTY('Edition')           AS edition, SERVERPROPERTY('EngineEdition')     AS engine\_edition, SERVERPROPERTY('Collation')         AS collation\_server, SERVERPROPERTY('IsClustered')       AS is\_clustered, SERVERPROPERTY('IsHadrEnabled')     AS is\_hadr\_enabled; -- Uptime SELECT sqlserver\_start\_time FROM sys.dm\_os\_sys\_info; -- CPU/NUMA/hardware snapshot SELECT cpu\_count, hyperthread\_ratio, scheduler\_count, numa\_node\_count FROM sys.dm\_os\_sys\_info; -- Configuration highlights SELECT name, value\_in\_use FROM sys.configurations WHERE name IN ( 'min server memory (MB)','max server memory (MB)', 'max degree of parallelism','cost threshold for parallelism', 'backup compression default','optimize for ad hoc workloads', 'clr enabled','xp\_cmdshell','remote admin connections', 'filestream access level','contained database authentication' );
:::

**Ports**

- Windows: registry ...SuperSocketNetLib\Tcp\IPAll\TcpPort.
- Linux: /var/opt/mssql/mssql.conf or SELECT local\_tcp\_port FROM sys.dm\_exec\_connections WHERE session\_id = @@SPID;.



**Persist**

- Upsert (device\_id, instance\_name); fill columns; put extras in discovery\_detail.
- Also populate **sql\_instance\_config\_snapshot** (full sys.configurations into config\_map + default paths), **sql\_instance\_endpoint** (TDS/DAC/HADR), **sql\_instance\_storage\_summary**, **sql\_instance\_security\_summary**, **sql\_instance\_errorlog\_summary**.



## 3.3 Databases & files

- sql\_database: name/status/owner/size/recovery/collation/TDE/created\_at + **latest backup times** from msdb..backupset (join by db name).
- sql\_database\_file: per DB file: file\_id, logical/physical, type, size/max, autogrowth settings.



## 3.4 Agent jobs

- sql\_agent\_job: metadata + last/next run (from msdb..sysjobs, sysjobhistory, sysjobschedules), steps/schedule in JSON.
- (Optional) sql\_agent\_job\_run: one row per new outcome (step\_id=0) with start/finish/outcome; keep excerpt of messages.



## 3.5 SQL metrics →&#x20;

## sql\_instance\_metric\_sample



Every 1–5 min:

- CPU %, Memory %, PLE (sec), Buffer Cache Hit Ratio %, Batch Requests/sec.
- Evaluate with thresholds (see §5) → status.
- (If you later migrate to lookup-based metrics here, send metric\_name **codes** that match ref\_metric\_name.code.)



## 3.6 AG topology

- sql\_availability\_group, sql\_availability\_replica from sys.availability\_groups, sys.availability\_replicas, sys.dm\_hadr\_\* views.



## 3.7 Backup coverage snapshot

- sql\_backup\_status\_snapshot: per instance rollup of full/diff/log backups in last 24h, max full age, lists of DBs missing coverage.



## 3.8 DB health snapshot

- CHECKDB recency (parse ErrorLog or maintenance tables), fragmentation (sampled dm\_db\_index\_physical\_stats), DBCC SQLPERF(LOGSPACE) for log %, approximate data free %.
- Persist → sql\_database\_health\_snapshot.

# 4) Local SQLite design (agent)



**Pragmas**

:::BlockQuote
PRAGMA journal\_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign\_keys=ON;
:::

**Core meta**

- identity\_map(entity\_type TEXT, natural\_key TEXT, id TEXT PRIMARY KEY(entity\_type,natural\_key))
- outbox(id INTEGER PK AUTOINCREMENT, entity\_type TEXT, entity\_id TEXT, op TEXT CHECK(op IN ('UPSERT','DELETE')), payload TEXT, created\_at TEXT)
- collection\_ledger(collector TEXT PRIMARY KEY, last\_started\_at TEXT, last\_finished\_at TEXT, last\_success\_at TEXT, last\_error TEXT)



**Lookup mirrors**

- Tables mirroring ref\_\* with **id TEXT**, code TEXT, label, active, plus needed joins (e.g., ref\_metric\_name with default\_unit, default\_comparator).
- **Index by code**. Agent always uses code internally.



**Mirrors of domain tables**

- Subset of columns, JSON fields as TEXT, booleans as 0/1, timestamps as ISO-8601 TEXT in UTC.
- Add a **hash TEXT** (SHA256 over canonical JSON sans audit) to each **mutable** mirror to detect deltas.



**Natural keys (agent)**

- monitored\_service: host → device\_id|service\_name, cloud → organization\_id|provider|region|service\_name
- monitored\_service\_endpoint: service\_id|protocol|port|ip|path
- service\_health\_metric: append-only (service\_id|collected\_at|metric\_name)
- sql\_server\_instance: device\_id|instance\_name
- sql\_database: instance\_id|name
- sql\_database\_file: database\_id|file\_id
- sql\_agent\_job: instance\_id|name
- Snapshots & metrics: append-only (use (parent\_id, collected\_at\[, metric\_name]) uniqueness).



**Delta algorithm**

1. Build canonical JSON (sorted keys; drop id/created\_at/updated\_at/active).
2. Compute hash.
3. If new or hash changed → enqueue **UPSERT** to outbox.
4. If entity disappeared → enqueue **DELETE** (or set active=0 locally).



**Retention**

- Metrics: keep N (e.g., 10k) rows. Snapshots: 30 days. Job runs: 30–90 days. Daily trim task.

# 5) Thresholds, statuses, and health rollups



**Catalog**

- All metric names live in ref\_metric\_name(code, default\_unit, default\_comparator, …).
- Agent emits metrics using **code**; server resolves to id.



**Threshold table (server)**

- Use your existing sql\_metric\_threshold and treat metric\_name as a **code** that matches ref\_metric\_name.code.
- scope JSON can point to an **instance** or a **service**:
  - For SQL metrics: \{"instance\_id":"…"}
  - For service metrics: \{"service\_id":"…"} or by product/service\_kind (you can expand to accept \{"product":"MSSQL"}).



**Evaluation**

- For each sample (SQL or service), fetch applicable threshold (most specific wins), apply default\_comparator unless overridden in row.
- Produce status/status\_id and store threshold\_snapshot with the exact numbers used.



**Service health rollup (for monitored\_service.health\_status\_id)**

- Rule of thumb (compute at ingest):
  - If service\_status != Running → rollup = Critical.
  - Else if any metric **Critical** in last N minutes → Critical.
  - Else if any metric **Warning** in last N minutes → Warning.
  - Else → Good.
- Persist rollup on the **service row** for fast list views.

# 6) Sync protocol (agents → server)



**Batch envelope (example)**

:::BlockQuote
\{ "device\_id": "uuid", "organization\_id": "uuid", "batch\_id": "uuid", "sent\_at": "2025-08-19T07:00:00Z", "ops": \[ \{ "op\_id": "uuid", "op": "UPSERT", "entity": "monitored\_service", "id": "uuid",                       // agent-stable "natural\_key": "device|MSSQLSERVER", "payload": \{ "organization\_id": "uuid", "device\_id": "uuid", "service\_name": "MSSQLSERVER", "product\_code": "MSSQL",          // LOOKUP CODES "service\_kind\_code": "Database", "provider\_code": "OnPrem", "platform\_code": "Windows", "environment\_code": "Prod", "service\_status\_code": "Running", "start\_mode\_code": "Auto", "pid": 1234, "uptime\_seconds": 86400, "listen\_endpoints": \[ \{"protocol\_code":"TCP","ip":"\*","port":1433,"name":"TDS"} ], "detail": \{ "svcAccount": "NT Service\\\MSSQLSERVER" } } }, \{ "op\_id": "uuid", "op": "UPSERT", "entity": "service\_health\_metric", "id": "uuid", "payload": \{ "service\_id": "uuid", "collected\_at": "2025-08-19T07:00:00Z", "metric\_name\_code": "CpuPct", "value\_num": 12.4, "unit": "%", "status\_code": "Good", "threshold\_snapshot": \{ "comparator": ">", "warning": 80, "critical": 90 } } } ] }
:::

**Server ingest**

- Resolve **codes→IDs** using ref\_\* caches; auto-create unknown codes if allowed.
- Enforce **natural-key uniqueness** with ON CONFLICT on server tables:
  - monitored\_service: (organization\_id, COALESCE(device\_id,UUID\_ZERO), service\_name)
  - Other entities per their unique constraints.
- Idempotency: ignore duplicate batch\_id/op\_id.
- DELETE ops → soft delete (active=false) and updated\_at=now().



**ACK & cleanup**

- Return accepted\_op\_ids\[] + rejected\[].
- Agent deletes accepted from outbox, logs rejected with reason, and retries after exponential backoff.

# 7) What table stores what (cheat sheet)



**Generic service layer**

- **monitored\_service**: one row per OS/cloud/k8s service (Engine, Agent, Browser, IIS, Redis, etc.). Holds taxonomy (via lookups), runtime **service status**, start mode, PID/uptime, endpoints (inline JSON), **overall health rollup**, and extended details.
- **monitored\_service\_endpoint**: normalized per-endpoint rows (protocol/port/ip/path/tls). Use when filtering, probing, or alerting by endpoint.
- **service\_health\_metric**: time-series for service-level KPIs (status, CPU, memory, restarts, port listening, HTTP latency/codes, etc.).
- **service\_binding**: polymorphic links to domain objects (e.g., sql\_server\_instance, RDS resource, k8s deployment).



**SQL domain**

- **sql\_server\_instance**: instance identity, version, edition, sp\_configure highlights, connectivity, HW/licensing, AG flags.
- **sql\_instance\_config\_snapshot**: full sys.configurations + default paths.
- **sql\_instance\_storage\_summary**: tempdb, drive space summaries, growth policy.
- **sql\_instance\_security\_summary**: SA status, principals, TDE, auditing.
- **sql\_instance\_errorlog\_summary**: 24h counts + last error, sample lines.
- **sql\_instance\_endpoint**: TDS/DAC/HADR endpoints (SQL-aware).
- **sql\_database** & **sql\_database\_file**: database catalog and files.
- **sql\_agent\_job** & **sql\_agent\_job\_run**: agent jobs & sampled run history.
- **sql\_instance\_metric\_sample**: SQL perf counters (CPU, PLE, BufferHit, Batch/s).
- **sql\_availability\_group** & **sql\_availability\_replica**: AG topology.
- **sql\_backup\_status\_snapshot**: backup coverage rollup.
- **sql\_database\_health\_snapshot**: CHECKDB/fragmentation/capacity.
- **sql\_metric\_threshold**: thresholds for evaluating samples (both SQL & service metrics via scope).
- **(Optional)** sql\_instance\_daily\_kpi: aggregated KPIs per day.



**Lookup catalogs**

- **ref\_\***: service taxonomy, providers, platforms, environments; endpoint protocol/type; metric names; status/start-mode catalogs; (SQL-specific: recovery model/DB status/HADR roles if you choose to normalize them later).

# 8) Mapping rules (agent → server)



**From raw values to lookup codes**

- Service:
  - service\_kind\_code: ‘Database’ for SQL Engine/Agent/Browser; other products accordingly.
  - product\_code: ‘MSSQL’, ‘Redis’, ‘IIS’, ‘NGINX’, etc.
  - provider\_code: ‘OnPrem’ | ‘AWS’ | ‘Azure’ | …
  - platform\_code: ‘Windows’ | ‘Linux’ | ‘Kubernetes’ | ‘CloudService’
  - environment\_code: customer-tagged (‘Prod’/’Dev’/…).
  - service\_status\_code: map from OS states (Running/Stopped/…).
  - start\_mode\_code: map from SCM/systemd modes (Auto/Manual/Disabled/NotApplicable).
- Endpoint:
  - protocol\_code: ‘TCP’ | ‘UDP’ | ‘HTTP’ | ‘HTTPS’ | ‘gRPC’ | …
  - endpoint\_type\_code: ‘TSQL’ | ‘DAC’ | ‘HADR’ | ‘HTTP’ | …
- Metrics:
  - metric\_name\_code: ‘CpuPct’, ‘MemoryRSSMB’, ‘PortListening’, ‘HTTP\_5xxRate’, ‘ServiceStatus’, ‘BatchRequestsPerSec’, etc.
  - status\_code: ‘Good’ | ‘Warning’ | ‘Critical’ | ‘Unknown’ (after evaluation).



**Joining service↔SQL**

- Prefer setting monitored\_service.instance\_id for MSSQL Engine/Agent; additionally create a service\_binding if you need many-to-one semantics (e.g., a proxy service that “backs” multiple instances).

# 9) Error handling, resilience, and guardrails

- Collectors must **degrade gracefully** (e.g., missing permission to read ErrorLog) and write messages to collection\_errors on the snapshot table.
- SQL connectivity failures:
  - Set sql\_server\_instance.connectable=false, still populate **service rows** (Engine/Agent status) so you can alert that **SQL isn’t reachable** while OS services might be up/down.
- Backoff on high CPU or long-running queries; enforce per-collector time budgets (e.g., 30–60s).
- Protect secrets (never send creds in payloads). Sign/verify batches (HMAC device key).

# 10) Retention & rollups

- **SQLite**: metrics 10k rows per entity; snapshots 30 days.
- **Server**:
  - Raw metrics >90 days → downsample (hourly/daily).
  - Job runs & error-logs: 90–180 days (configurable).
  - Snapshots: 180–365 days.
  - Daily KPIs: 13 months.

# 11) Testing checklist

- **Catalog sync**: unknown codes are created or rejected per policy; agent can continue.
- **Identity stability**: instance rename, service rename, AG failover; natural keys still map to same UUID or intentionally create new rows per design.
- **Delta hashing**: ensure stable canonicalization (sorted keys; normalized numbers/booleans) to avoid false positives.
- **Load**: 1 host with 3 instances, 100+ DBs, 400 files, 200 jobs, metrics at 1-min cadence — outbox size & server ingest throughput OK.
- **Chaos**: stop/start Engine/Agent; crash/restart spikes; block T-SQL — service layer continues to populate & alert.
- **Cross-product**: add a non-SQL service (Redis). Verify monitored\_service + endpoints + metrics flow without any SQL dependencies.

# 12) Example “first run” flow (SQL + services)

1. **Catalog pull** → cache ref\_\* by code.
2. **Service discovery**
   - Create/UPSERT monitored\_service rows for **MSSQL Engine** (service\_name='MSSQLSERVER', product='MSSQL', service\_kind='Database', service\_status='Running', start\_mode='Auto', listeners \[TCP:1433]).
   - Create rows for **SQLAgent** and **SQLBrowser** (link instance\_id if known).
3. **SQL discovery**
   - Connect to SQL; write sql\_server\_instance and supporting snapshots/endpoints.
   - Link Engine service to instance\_id.
4. **Metrics** (minutely)
   - Emit SQL metrics (sql\_instance\_metric\_sample) and service metrics (service\_health\_metric).
   - Threshold-evaluate → status codes.
5. **Sync**
   - Flush outbox in batches; server resolves codes→IDs, upserts, and computes health rollups.
6. **Nightly**
   - Run fragmentation sampling + CHECKDB recency parse; write sql\_database\_health\_snapshot.

# 13) Implementation tips & gotchas

- **Normalize what matters**: keep endpoints in both JSON (fast UI) and rows (alerting/probing).
- **Use views for legacy API** if you later swap enum text → lookup IDs in SQL-domain tables.
- **Avoid duplicate service rows** on Windows named instances: use precise service names (MSSQL$FOO, SQLAgent$FOO) as the identity.
- **DAC port** often unset; handle NULL.
- **Error log** via xp\_readerrorlog may require elevated rights; fallback to filesystem read (Windows service account permissions) or Extended Events.
- **Kubernetes**: for multi-pod services, you can either:
  - Track a single **logical** monitored\_service for the Deployment/StatefulSet (aggregate metrics), or
  - Track **per-pod** services and bind them; pick one approach and stay consistent.

## Appendix A — Minimal SQL for key collectors (reference)

- Instance uptime/version: sys.dm\_os\_sys\_info, SERVERPROPERTY.
- Config snapshot: sys.configurations; default paths via SERVERPROPERTY('InstanceDefault\*Path').
- Endpoints: sys.endpoints, sys.tcp\_endpoints (TDS/DAC/HADR).
- Storage: sys.dm\_os\_volume\_stats, sys.master\_files, tempdb.sys.database\_files.
- Security: sys.server\_principals, sys.server\_role\_members, sys.sql\_logins, sys.dm\_server\_audit\_status.
- Databases: sys.databases + backup info from msdb..backupset.
- Files: sys.database\_files.
- Agent jobs: msdb..sysjobs, sysjobschedules, sysjobhistory.
- Metrics: sys.dm\_os\_performance\_counters, sys.dm\_os\_ring\_buffers (or XE/perf counters as you prefer).
- AG: sys.availability\_groups, sys.availability\_replicas, sys.dm\_hadr\_\*.
- Log space: DBCC SQLPERF(LOGSPACE).

