Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
mariadb_exporter
MariaDB metrics exporter for Prometheus written in Rust.
Features
- Modular collectors – Enable only what you need; heavy/optional collectors stay off by default.
- Compatibility – Metric names align with Prometheus
mysqld_exporter(prefixedmariadb_). - Lean defaults – Essential availability, InnoDB, and replication metrics enabled by default; optional collectors opt-in.
- Low footprint – Designed to minimize cardinality and avoid expensive scans.
- Resilient – Serves
/metrics(HTTP 200) even when MariaDB is unreachable. During an outage,mariadb_upbecomes0, and DB-dependent metrics are omitted to avoid stale data. Only an overload of the exporter itself is signalled with a status code — see Scrape concurrency and timeout. - No stale data – A collector never serves a previous scrape's values as current. If its source becomes unavailable (plugin uninstalled,
performance_schematable missing, feature disabled, privilege revoked) the series it owned disappear instead of freezing. See Scrape outcomes. - Optional tracing – OpenTelemetry/OTLP is a default-off Cargo feature. Release binaries keep local logs and
x-request-id; rebuild with--features telemetryfor OTLP. See Optional OpenTelemetry tracing.
Download or build
Install via Cargo:
Or grab a prebuilt binary, .deb, or .rpm from the
GitHub Releases — built for
Linux (x86_64 and aarch64, static musl) and macOS (x86_64 and aarch64).
Container images (linux/amd64, linux/arm64) are published to ghcr.io.
Usage
Recommended Setup (Secure)
Best practice: Use Unix socket with dedicated user
Create the exporter user with minimal privileges:
-- Create user for local socket connection only with connection limit
@'localhost' IDENTIFIED BY '' WITH MAX_USER_CONNECTIONS 3;
-- Grant minimal required permissions for all collectors
SELECT, PROCESS, REPLICATION CLIENT ON *.* TO 'exporter'@'localhost';
FLUSH PRIVILEGES;
Run the exporter:
Why this is secure:
- ✅ No password needed (socket authentication)
- ✅ User restricted to
localhostonly (no network access) - ✅ Minimal privileges (read-only + monitoring)
- ✅ Connection limit prevents resource exhaustion
- ✅ No exposure to network attacks
Alternative: TCP Connection
For remote monitoring or testing:
Create user for network access:
@'%' IDENTIFIED BY 'strong_password_here' WITH MAX_USER_CONNECTIONS 3;
SELECT, PROCESS, REPLICATION CLIENT ON *.* TO 'exporter'@'%';
FLUSH PRIVILEGES;
Common DSN Formats
- Unix socket (recommended):
mysql:///mysql?socket=/var/run/mysqld/mysqld.sock&user=exporter - TCP:
mysql://user:password@host:3306/database - TLS required:
mysql://user:password@host/mysql?ssl-mode=REQUIRED - TLS verify identity:
mysql://user:password@host/mysql?ssl-mode=VERIFY_IDENTITY&ssl-ca=/path/to/ca.pem
Change Port
Default port is 9306:
Available collectors
Collectors are toggled with --collector.<name> or --no-collector.<name>.
--collector.default(enabled) – Core status (uptime, threads, connections, traffic), InnoDB basics, replication basics, binlog stats, config flags, version,mariadb_up, audit log enabled status.--collector.exporter(enabled) – Exporter self-metrics (process, scrape, cardinality).--collector.innodb– Advanced InnoDB metrics fromSHOW ENGINE INNODB STATUS: LSN tracking, checkpoint age, active transactions, semaphore waits, adaptive hash index stats.--collector.tls– TLS session + cipher info.--collector.query_response_time– Buckets fromquery_response_timeplugin.--collector.statements– Statement digest summaries/top latency fromperformance_schema.--collector.schema– Table size/row estimates (largest 20 non-system tables).--collector.replication– Replica role/lag/thread status, relay log size/pos, binlog file count, and per-channel replication metrics for multi-source replicas.--collector.locks– Metadata/table lock waits fromperformance_schema.--collector.metadata–metadata_lock_infotable counts.--collector.userstat– Per-user stats (requires@@userstat=1andUSER_STATISTICS).--collector.system– Host CPU/memory/load andMariaDBprocess-group usage, read from the OS (never from the database). Only meaningful when the exporter runs on the database host. Seesrc/collectors/system/README.md. Process-group memory is read from/proc/<pid>/statm(RSS);--system.process-memory=pssswitches to/proc/<pid>/smaps_rollup, which accounts shared pages proportionally but makes the kernel walk every page-table entry — budget for it before enabling.
Enabled by default
defaultexporter
Everything else is opt-in.
Replication lag semantics:
mariadb_slave_status_seconds_behind_masterandmariadb_replica_seconds_behind_master_secondsuse-1for unknown lag (NULL, stopped replication, query failure, or not a replica).- On multi-source replicas, aggregate lag is the worst known channel lag (max), and aggregate
*_io_running/*_sql_runningare1only when all channels are running. - Per-channel replication metrics are exported as
mariadb_replica_*_by_channel{channel_name,connection_name}.
Enable all collectors
To enable all collectors for maximum visibility:
Or using environment variables:
Note: Some collectors require additional privileges or database configuration:
innodb– RequiresPROCESSprivilege (included in recommended setup)tls– Only shows data if TLS/SSL is enabledquery_response_time– Requiresquery_response_timeplugin enabledstatements– Requiresperformance_schemaenabledschema– Queriesinformation_schema(can be slow on large databases)locks,metadata– Requireperformance_schemaenableduserstat– Requires@@userstat=1andUSER_STATISTICSenabledsystem– Reads the OS, not the database. Only enable it when the exporter runs on the same host asMariaDB; on managed services (RDS, SkySQL, …) it would describe the exporter's host instead
InnoDB Advanced Metrics
The --collector.innodb provides deep visibility into InnoDB internals by parsing SHOW ENGINE INNODB STATUS:
Metrics exposed:
mariadb_innodb_lsn_current– Current log sequence numbermariadb_innodb_lsn_flushed– LSN flushed to diskmariadb_innodb_lsn_checkpoint– Last checkpoint LSNmariadb_innodb_checkpoint_age_bytes– Uncheckpointed bytes (LSN current - checkpoint)mariadb_innodb_active_transactions– Count of active InnoDB transactionsmariadb_innodb_semaphore_waits_total– Semaphore wait events (internal contention)mariadb_innodb_semaphore_wait_time_ms_total– Total semaphore wait timemariadb_innodb_adaptive_hash_searches_total– Adaptive hash index hitsmariadb_innodb_adaptive_hash_searches_btree_total– AHI misses requiring B-tree lookup
Use cases:
- Monitor checkpoint age to prevent log file overflow
- Track LSN progression for write workload analysis
- Detect long-running transactions
- Identify internal InnoDB contention (semaphore waits)
- Measure adaptive hash index efficiency
Requirements:
PROCESSprivilege (forSHOW ENGINE INNODB STATUS)
Enable with:
Scrape outcomes
Every collector reports one of three outcomes per scrape, and the exporter settles the registry accordingly.
| Outcome | Meaning | Effect on the registry | /metrics |
|---|---|---|---|
| Fresh | The collector published a current snapshot. A successful empty result is Fresh when "zero rows" is the current truth. | The new snapshot replaces the old one; entities that vanished from a valid snapshot are removed. | Exposed as usual. |
| Skipped | The collector published nothing because its source is known to be unavailable — plugin not installed, performance_schema table absent, feature disabled, privilege revoked. |
Every series the collector owned is removed. | Those series are absent. Siblings are unaffected. |
| Err | An unexpected or transient fault — lost connection, timeout, deadlock, malformed data, or a feature probe that itself failed. | The last good snapshot is preserved so the collector can resume. | HTTP 200 with mariadb_up 1, # Error collecting metrics from '<name>': … comments, and only the mariadb_exporter_* self-observation families. Database-dependent families are withheld for that scrape so a preserved snapshot is never timestamped as current. |
Connectivity failure is unchanged: HTTP 200, mariadb_up 0, fresh exporter/build metrics,
and no database metrics. mariadb_up is never fabricated to 0 because a collector failed
— the connectivity check succeeded, so it stays 1.
Scrape concurrency and timeout
The three outcomes above describe a scrape that ran. Two situations are about the scrape itself and are answered with a status code instead, because there is no honest exposition to return:
| Situation | Status | Meaning |
|---|---|---|
| A scrape is already in flight | 503 Service Unavailable |
/metrics is single-flight. Overlapping scrapes are refused rather than piled onto an already-slow server. |
The scrape exceeded --scrape.timeout-ms |
504 Gateway Timeout |
The scrape was aborted, so its in-flight queries were dropped and their pooled connections returned. |
--scrape.timeout-ms defaults to 15000. Set it below your Prometheus scrape_timeout so
the exporter, not the scraper, decides when to give up.
Note that the shipped default does not satisfy that advice: Prometheus's own
scrape_timeout defaults to 10s, which is below 15000ms, so with both defaults the
scraper gives up first and the exporter's budget never fires. Nothing breaks — the client
disconnect drops the request future, which releases the gate and aborts the scrape — but the
504 never appears and the decision of when to give up stays with Prometheus. Lower
--scrape.timeout-ms below your scrape_timeout to move it back to the exporter.
The single-flight gate is held by the request, not by the scrape task. It is therefore
released on every exit path — success, collector error, panic, timeout, and client
disconnect — so a scrape that never finishes cannot wedge /metrics at 503 permanently
(nbari/pg_exporter#34).
A gate release is not a promise that all work has finished: a spawn_blocking sample already
running cannot be cancelled, and the server may still be finishing a statement it was told to
stop. The gate bounds exporter concurrency, not server-side work; a role-level connection
limit is the hard backstop there.
An aborted scrape is recorded as an abort, never as a success: every collector still in
flight increments
mariadb_exporter_collector_scrape_aborted_total{collector="..."} and reports
mariadb_exporter_collector_last_scrape_success 0. Alert on
rate(mariadb_exporter_collector_scrape_aborted_total[5m]) > 0 to catch a collector that
is not finishing within --scrape.timeout-ms — the collector is not necessarily at fault,
since the abort bounds the whole scrape.
Per-collector timers only start after the connectivity check, so a scrape abandoned while
SELECT 1 is still in flight moves none of them. mariadb_exporter_scrape_aborted_total
counts that case: it is incremented once per scrape, without a collector label, whenever a
scrape exceeds --scrape.timeout-ms.
The two counters are deliberately asymmetric, because a client disconnect and a budget timeout are not observed the same way. A disconnect drops the request future, so no code in the exporter runs at that point — it cannot increment a scrape-level counter. Those aborts are visible only through the per-collector counter, and only for collectors that had already started. A budget timeout, by contrast, is observed by the exporter itself and increments both.
Alerting implications
Because an unavailable source now yields absence rather than a stale or zero value,
threshold alerts on those series go quiet instead of firing on stale data. Alerts that need
to notice a disappearing source should use absent() / absent_over_time(), and scrape
health should be watched with the exporter's own metrics:
# The exporter is up but a collector keeps failing.
mariadb_exporter_collector_last_scrape_success == 0
# A source that used to report has gone away.
absent_over_time(mariadb_info_schema_query_response_time_seconds_count[10m])
An honest zero is still published where zero is a fact — for example mariadb_ssl_server_configured 0
when TLS is genuinely not in use, or mariadb_replica_configured 0 on a server with no
replication. A zero is never published to stand in for "could not read".
On normal shutdown (SIGINT or SIGTERM on Unix), the exporter drains its HTTP server, then waits up to two seconds for the shared MariaDB pool to close gracefully, including TLS shutdown. Exceeding that pool-close limit returns an error and a nonzero exit status.
Project layout
mariadb_exporter
├── bin
├── cli
├── collectors
│ ├── config.rs
│ ├── default
│ ├── exporter
│ ├── innodb
│ ├── locks
│ ├── metadata
│ ├── mod.rs
│ ├── query_response_time
│ ├── register_macro.rs
│ ├── registry.rs
│ ├── replication
│ ├── schema
│ ├── statements
│ ├── system
│ ├── tls
│ ├── userstat
│ └── util.rs
└── src/lib.rs
Each collector lives in its own subdirectory for clarity and easy extension.
Optional OpenTelemetry tracing
OpenTelemetry/OTLP support is a default-off Cargo feature. Standard release
binaries, packages, and container images omit it. Prometheus metrics, local logs
(RUST_LOG / -v), request spans, and x-request-id correlation remain available
in every build.
| Build | Endpoint configured | Behavior |
|---|---|---|
| Default | No | Local logging only |
| Default | Yes | Local logging only; startup warning that OTEL configuration is ignored |
--features telemetry |
No | Local logging only; no exporter is started |
--features telemetry |
Yes | Local logging plus OTLP/gRPC traces, incoming trace context, and x-trace-id responses for active traces |
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
Only OTLP/gRPC is supported. Optional OTEL_EXPORTER_OTLP_HEADERS supplies
comma-separated key=value authentication metadata; HTTPS uses native certificate
roots. A default build warns once on stderr when OTEL_EXPORTER_OTLP_ENDPOINT is
set and never prints the endpoint or header values.
For a custom telemetry-enabled image:
Testing
Zero-setup option: the repo ships a compose-based Dev Container (Rust + MariaDB, plus an optional Prometheus + Grafana profile). With DevPod:
scripts/dev-up, thenjust testinside — no host database needed.
Run tests:
Run with container-backed integration (requires a container runtime):
If you use rootless Podman, export DOCKER_HOST so testcontainers can connect:
Test with Unix socket connection (production-like setup):
# Test with combined MariaDB + exporter container (most realistic)
Lint both the default build and the telemetry feature:
Socket Connection Testing
For detailed information on testing with Unix socket connections, see TESTING_SOCKET.md.
Quick start:
# Test with combined MariaDB + exporter container (most realistic)
Developer Guidelines
See the Development Guide (CONTRIBUTING.md) for the full local workflow, safe-coding rules, and the pre-commit hook. Additional tooling:
- .devcontainer/ — one-command Rust + MariaDB dev
environment (+ optional Prometheus/Grafana via
just metrics-dev). - scripts/benchmark/ — self-contained local
soak/leak harness (
run-soak.sh+check-soak.sh) driven bymariadb_loadtest.py.
Architecture
The project follows a modular collector architecture:
mariadb_exporter/
├── bin/ # Binary entry point
├── cli/ # CLI argument parsing
├── collectors/ # All metric collectors
│ ├── mod.rs # Collector trait and registration
│ ├── registry.rs # Collector orchestration
│ ├── config.rs # Collector enable/disable logic
│ └── */ # Individual collector modules
└── exporter/ # HTTP server (Axum)
Adding a New Collector
- Create a subdirectory under
src/collectors/with amod.rs - Define a struct implementing the
Collectortrait:register_metrics(&self, registry: &Registry)- Register Prometheus metricscollect(&self, pool: &MySqlPool)- Fetch data and update metrics (async)enabled_by_default(&self)- Whether collector runs by default
- Add ONE line to
register_collectors!macro insrc/collectors/mod.rs:register_collectors!
The macro automatically generates all registration boilerplate.
Strict Linting Rules
This project enforces strict clippy lints (see Cargo.toml):
- DENY:
unwrap_used,expect_used,panic,indexing_slicing,await_holding_lock - Use
?for error propagation, never.unwrap()or.expect() - Use
.get()instead of[index]for slicing - Use pattern matching or
.ok()instead of.unwrap()
Exceptions are allowed only in test code with #[allow(clippy::unwrap_used)].
Testing
# Run unit tests
# Run with container integration
# Lint (must pass)
# Validate Grafana dashboard
Dashboard Development
When adding metrics to the Grafana dashboard:
- Ensure metrics are exported by collectors
- Add panels following existing structure (clean, professional, no emojis)
- Use template variables (
$job,$instance) - Add clear descriptions (Goal/Action format)
- Validate before committing:
just validate-dashboard
See grafana/README.md for detailed dashboard documentation.
Commit Guidelines
- Run tests before committing:
cargo test - Run clippy:
cargo clippy --all-targets --all-features - Validate dashboard if modified:
just validate-dashboard - Keep commit messages clear and descriptive
Notes
- User statistics: enable with
SET GLOBAL userstat=ON;(or@@userstat=1) to exposeuserstatmetrics. - Metadata locks: load
metadata_lock_infoplugin for themetadatacollector. - Performance schema is needed for statements/locks collectors to return data.
- Optional collectors skip gracefully when prerequisites aren't present.