Writing a custom Prometheus exporter

A custom exporter is the bridge between a system Prometheus cannot scrape directly and the metrics your alerts depend on. This page covers how to design, build, test and run one.

On this page

When a custom Prometheus exporter is the right answer

Build a custom exporter when a system whose health matters for alerts exposes no metrics Prometheus can read, and no existing exporter covers it. An exporter is an HTTP endpoint that Prometheus pulls from on each scrape. Prometheus discovers targets through service discovery or static configuration, sends an HTTP request to the exporter, and stores whatever the endpoint returns. Before writing code, check the exporter catalog and the system's own metrics endpoint, since many databases, network devices and appliances already offer one or a supported exporter. For short-lived batch jobs that cannot be scraped, the Pushgateway is the narrower option, and a textfile collector on the host may fit machine-level work. A custom exporter makes sense when the system is long-running, can be queried for its state, and has no other way into Prometheus. Confirm the system's management API, its authentication model and its rate limits with the vendor or your own administrators before you commit to a design.

Treat the exporter as a security surface from the first design review. The security model warns that exporters which take targets from URL parameters can be made to send requests to arbitrary endpoints by anyone with HTTP access to them. A custom exporter that queries an internal system will hold that system's credentials, so decide where those secrets are stored, which network segment the exporter can reach, and who can scrape it. Scrapes also create load on the monitored system, so each collection path needs a bounded cost. Plan for the exporter to be unavailable at times, because an alert that depends on it will fire when the exporter fails, and you should know which alert covers that case.

Prometheus values reliability over precision, as its overview documentation states, and it is not suited to workloads that need every event counted exactly, such as per-request billing. An exporter should therefore report current state and approximate rates that alerts can act on, and it should not be the system of record for financial or compliance counts. Decide early which values the exporter will report and how stale data will be handled, and confirm with the business owners of the system that a best-effort view meets their need.

How the exporter, target and Prometheus fit together

The exporter is a separate process that sits beside the target system and talks to it through an access path you define, usually a local API, a protocol client or a query interface. Each scrape triggers the exporter to read the target and turn its state into metrics, which it returns on an HTTP endpoint. Prometheus discovers the exporter through static configuration or service discovery and pulls from it on a schedule. Check the trust boundary: the exporter's credentials and network reach define what it can read, and anyone who can reach the endpoint can read those metrics.

Prometheus pulls metrics from a custom exporter that reads the target through a bounded account.

Design decisions to settle before writing code

An exporter is small, but a few early choices decide whether it stays maintainable and safe to run. Each card below is a decision to make on paper first, with the trade-off it carries for the team that will operate the exporter and the Prometheus server that scrapes it.

Which metrics the system exposes

Start from what operators will ask during an incident: is the target up, how busy is it, how many operations fail, how long they take. Map each question to a metric before writing any collector. Fewer, well-chosen metrics are cheaper to scrape, easier to alert on, and easier to keep stable across exporter versions. Check whether the target already exposes counters you can read, since recomputing them in the exporter adds work and drift. Name the metrics once and treat names as a public interface that dashboards and alert rules will depend on.

Prometheus overview

One exporter per process

Each exporter should watch one target process or service instance. A single exporter that fans out to many systems couples their failures, makes scrape timeouts hard to reason about, and blurs which target a metric describes. The trade-off is more processes to deploy, supervise and configure. Where one host runs several instances of the same system, decide whether each instance gets its own exporter port or whether the exporter reads a shared endpoint, and write that rule down so later additions follow it.

Labels that keep cardinality low

Labels multiply the number of series Prometheus stores. Use labels for bounded dimensions such as operation type, status class or queue name. Keep unbounded values such as user IDs, request paths with identifiers, file names or raw error messages out of labels entirely. Write a short list of allowed label names and their value sets, and review every new label against it. The trade-off is less detail per series in exchange for storage, query speed and memory that stay predictable as the target grows.

Reading state on each scrape or caching

An exporter can query the target every time Prometheus scrapes it, or poll in the background and serve the last result. Reading on scrape gives fresh values but ties scrape duration to the target's response time, so slow queries cause scrape timeouts. Caching keeps scrapes fast and protects the target from load, but the values can lag and a failed poll must be reported rather than hidden. Decide the maximum acceptable staleness and whether an error in collection should mark the target as down.

Handling credentials to the target

Most exporters need a username, password, token or certificate to reach the system they monitor. Store that secret where only the exporter process can read it, such as a file with restricted permissions or the secret store your platform provides, and never in a command line argument that appears in process listings. Use a read-only account with the narrowest permissions that return the metrics. Remember that the exporter's own HTTP endpoint also needs protection, since Prometheus supports TLS and basic authentication for it.

Prometheus security model

Which official client library to use

The official client libraries for Go, Java, Python, Ruby and Rust provide the metric types, registries and HTTP handler that exporters need, so most teams should start there rather than hand-writing the exposition format. Choose the language your team can operate and debug in production, and check that the library version you pin is one your organization can keep current. Confirm the library's current release line and its support status with the project before standardizing, because a library that falls behind can cause compatibility issues with the server.

Collection patterns and when each fits

With scrape-time collection, the exporter reads the target system each time Prometheus requests /metrics. The values are as current as the moment of the scrape, and the exporter holds no state between requests. This is the default model in the official client libraries, where a custom collector's collect logic runs inside the HTTP handler. It fits systems that answer quickly and cheaply, such as reading a local file, a status endpoint or a small query.

  • Staleness: values are as fresh as the scrape interval allows, with no cache age to explain.
  • Load: every scrape hits the target system, so scrape interval and the number of Prometheus servers scraping it multiply the load.
  • Timeouts: a slow read delays the whole response and can make the scrape fail, so the collector needs its own deadline.
  • Concurrency: multiple scrapes may run at once, so shared state inside the collector must be safe under concurrent access.
  • Failure visibility: a failed read should produce an error metric or a failed scrape that alerts can catch.

Before choosing this pattern, confirm in the official exporter guidelines and your language client library documentation how collectors are registered and how they handle errors and timeouts.

How to build the exporter step by step

This sequence takes a team from an undefined idea to an exporter that a Prometheus server scrapes successfully, with a check at each stage so problems surface before the exporter reaches production. Each step produces a artifact the next step depends on.

  1. Define the metric set from real signals

    Start with the system's own signals: the counters, gauges and state values its operators already check by hand, such as queue depth, job counts, connection pool use or last successful run. The engineer who knows the system and one person who will own the alerts should agree on a short list, with each metric tied to a question someone needs answered. Write the list in a document with the metric type, the labels and the reason for each. The step is done when every metric has a named consumer, either a dashboard panel or an alert rule, and no metric exists only because it was easy to read.

  2. Choose names and base units

    Apply the official Prometheus naming guidance to every metric and label: a clear prefix for the exporter, base units such as seconds and bytes rather than milliseconds or megabytes, the _total suffix on counters, and labels that stay bounded in number. Review the list with a second engineer and reject any label whose values come from user input, request IDs or unbounded identifiers. The check is a reviewed table where every name and unit matches the guidance and every label has a short list of possible values.

  3. Implement collectors that run at scrape time

    Build the collection logic so it reads the system when Prometheus scrapes the exporter, not on a background timer that writes stale values. Use the official client library for the implementation language, register a custom collector, and have it query the target system on each call with a sensible timeout. Keep failure handling explicit: if the system cannot be read, the exporter should report a scrape error metric rather than silently return zeros. The check is a manual scrape in a local run that returns the expected series with current values, and a deliberately broken target that produces the error metric.

  4. Expose the HTTP metrics endpoint

    Serve the metrics on a dedicated HTTP path, conventionally /metrics, on a port chosen for this exporter alone. Bind to the interface the Prometheus server can reach, and document the port in the runbook so it does not collide with another exporter on the same host. Follow the one-exporter-per-process guidance: if the system needs two unrelated collectors, run two processes. The check is a curl request against the endpoint that returns text in the Prometheus exposition format with HELP and TYPE lines for every metric.

  5. Add a configuration and credentials path

    Move the target address, timeouts, the collection scope and any credentials into a configuration file or environment variables, never into source code. Store secrets in the platform your organization already uses for them, and restrict file permissions so only the exporter's service account can read them. If the exporter needs to reach a remote system, check whether it accepts target parameters from URLs, because the Prometheus security model warns that such exporters can be used to send requests to arbitrary endpoints. The check is a run with the configuration file changed and no code change, plus a review confirming no secret appears in the repository or the process list.

  6. Write unit tests for the collectors

    Test the parsing and translation logic against recorded or mocked responses from the target system, covering normal output, empty output, malformed output and timeouts. Assert the metric names, types, label sets and values the collector emits. Run the suite in the continuous integration pipeline so a change to the collector cannot silently rename a metric that dashboards and alerts depend on. The check is a passing test run that includes at least one test for each failure path, and a test that fails when a metric name is changed on purpose.

  7. Run promtool check metrics against the output

    Capture the output of the running exporter and pass it to promtool check metrics, which validates the exposition format and reports problems with names, units and types against the Prometheus conventions. Fix every reported issue in the code rather than suppressing it, and rerun the check after each change. Repeat the check after upgrading the client library, because format rules can change between versions. The check is a clean promtool report on a captured scrape from a realistic target state, saved with the exporter's release artifacts so reviewers can see it passed.

  8. Add a scrape job and verify the target is up

    Add a scrape job to the Prometheus configuration with the exporter's address and a job name that matches the naming convention in use. Reload the configuration through the method your deployment allows, then open the targets page or query the built-in up metric for that job. The up series should be 1 for each instance, and a stopped exporter should turn it to 0 within the scrape window. The step is complete when the target shows as up, the expected series appear in a query, and stopping the exporter produces the expected alert or status change.

Testing the exporter with promtool check metrics

Before an exporter is deployed, run its output through promtool check metrics to confirm the exposition text follows Prometheus format and naming rules. Start the exporter locally, then pipe the endpoint output into the checker, for example with curl -s | promtool check metrics, adjusting the port and path to your exporter. The tool reads the text exposition format from standard input and reports lint problems with line references. Run it on every change, and add it to CI so a renamed metric or a missing # TYPE line fails the build instead of reaching a scrape target.

The checker catches structural and convention errors: malformed lines, metric names with invalid characters, counters that do not end in _total, missing or inconsistent # HELP and # TYPE metadata, histograms with missing _bucket, _sum or _count series, and unit suffixes that do not match common base units. Fixing these early matters because a metric name is hard to change once dashboards and alert rules depend on it. Confirm the exact lint set against the promtool version you install, since checks change between Prometheus releases.

promtool check metrics does not prove the values are right. It cannot tell whether a gauge reports the true queue depth, whether a counter resets when it should, or whether a label set will stay small in production. It also says nothing about behavior when the monitored system is slow or times out, which is where collector logic and scrape-time work need separate tests. Finally, before relying on the data, point a non-production Prometheus server at the exporter, check the targets page, run queries in the expression browser, and confirm series and label counts look as expected.

Security risks in an exporter you write

An exporter sits between your network and a system that often holds credentials and sensitive data, so it becomes an attack surface the moment it listens. The risks below cover the endpoint, the secrets it needs, the way it accepts targets, the labels it emits, the endpoints it exposes and the privileges it runs with.

Serving metrics without TLS or authentication

An exporter that answers scrapes over plain HTTP with no login exposes everything it reports to anyone who can reach the port. Prometheus can use TLS, client certificates and HTTP basic authentication with bcrypt-hashed passwords, but basic authentication without TLS sends credentials in cleartext. Check that the exporter either serves TLS or sits on a network segment reachable only by the Prometheus servers, and confirm how the Prometheus scrape configuration supplies its credentials.

Prometheus security model

Storing target credentials in config files

Most exporters must log in to the system they monitor, so the exporter holds a database password, API token or service account key. Writing that value into a flat configuration file in the repository or a shared host turns every reader of the file into a credential holder. Load secrets from environment variables, a mounted secret file or a secrets manager, restrict file permissions, and rotate the credential on the schedule your security policy sets.

Taking targets from URL parameters

An exporter that accepts a target address as a URL parameter can be pointed at any host the exporter can reach, which turns it into a proxy for internal scanning. The Prometheus security model warns that exporters such as SNMP and Blackbox work this way. If your exporter follows the same pattern, restrict the allowed target list, validate addresses against it, and limit who can reach the endpoint.

Leaking sensitive values through labels

Label values are stored, queried and shown in dashboards and alerts, often by people who should never see the underlying data. Usernames, customer identifiers, email addresses, query text or internal hostnames placed in labels expose that data and also inflate cardinality. Review every label your collectors emit, keep identifiers that are sensitive out of labels, and check alert annotations and notification payloads for the same values.

Adding admin-style endpoints by mistake

Debugging handlers, reload endpoints or routes that reset counters can be added during development and left in the release build. Prometheus disables its own admin HTTP APIs by default and gates destructive operations behind explicit flags, and your exporter should follow the same principle. Expose only the metrics path and health path your design needs, and test the running binary for any additional routes before release.

Running with more privilege than needed

An exporter that runs as root, uses an administrator database account or mounts host paths it never reads gives an attacker that same reach if the exporter is compromised. Run it as a dedicated unprivileged user, grant a read-only role scoped to the statistics views it queries, and restrict filesystem and network access in the service unit or container. Ask the system owner to confirm which read permissions the collectors actually need.

Running and maintaining the exporter after launch

The most important decision after go-live is who owns the exporter. Name a team that receives its build failures, its scrape errors and its upgrade notices, and record that owner next to the exporter's repository. An exporter that nobody owns tends to keep running quietly while its client library, its Prometheus version and its target system drift apart. Monitor the exporter itself with the up series that Prometheus generates for each scrape job, which shows whether the last scrape succeeded, and with scrape_duration_seconds, which shows how long collection takes. Alert on repeated failures of up and on a duration that creeps toward the scrape timeout, because slow collection often comes before outright failure. Confirm with your team which of your targets' scrape intervals and timeouts these checks depend on.

Version the exporter with semantic versioning and publish a changelog for every release that changes metric names, types, labels or units. Treat a change to any of those as a breaking change for dashboard and alert authors, even if the exporter's code change looks small. Plan client library upgrades on the same cycle as your other services, and read each library's release notes before bumping it, since changes to the exposition format or default collectors can alter what the endpoint returns. Prometheus itself changes on its own release cycle, documented in the Prometheus release cycle page, so check which minor release line your servers run before you test the exporter against it. Keep a staging Prometheus that scrapes a test copy of the exporter so you can catch breakage before production does.

Write down the metric contract in a document that lists each metric's name, type, unit, labels, label values and meaning, along with the release in which it appeared. Dashboard and alert authors should work from that contract, not from what they happen to see on the endpoint. When you retire a metric, announce the removal in the changelog, keep the old name exposed for at least one release cycle where the consumers can migrate, and then remove it. Check the promtool output and your alert rules for references to the old name before the removal ships, because an alert that silently matches nothing is one of the most common ways retirements go wrong. Ask your team to confirm how many dashboards and rules reference each metric before you remove it.

Questions teams ask before building an exporter

How much effort does a custom Prometheus exporter take?

Effort depends mostly on the shape of the target system, not on Prometheus itself. The main drivers are the number of metrics you expose, how complex the target's API or data format is, how authentication and credentials work, how much testing you need against real data, and how much documentation the owning team expects. A small exporter reading one status endpoint with a handful of gauges is a different job from one that walks a multi-tenant API with pagination, token refresh and dozens of labeled series. Ask any partner for a quote built from a written list of metrics, the target's access model and the test environment, so the price follows from the scope rather than a guess.

Can our in-house team build a custom exporter?

Often yes, if at least one engineer knows the target system well and another can review Prometheus conventions. The official exporter guidelines cover naming, label choices, one exporter per process and scrape-time collection, and a team that reads them can avoid most early mistakes. The harder parts are usually the target's API quirks, failure handling when the target is slow or down, and keeping metric names stable after dashboards and alerts depend on them. Assess whether the team can own the code for the life of the system, including Go or Python maintenance and upgrades to client libraries.

What do we need to provide for an exporter project?

Plan to provide access to the target system in a non-production environment, sample or representative data, a test environment that can be reached from where the exporter will run, and a named owner for the metric contract. The contract owner decides which metric names and labels are stable, because renaming a metric later breaks dashboards and alert rules. You should also provide a list of questions the business needs answered, such as which queues or tenants matter, and the security rules for credentials. Confirm these items in the written scope before work starts.

Should we try an existing exporter before writing our own?

Check for an existing exporter first. The Prometheus documentation lists many community exporters, and the official guidance is to reuse one when it already covers the system well. A custom exporter makes sense when no maintained exporter exists, when an existing one exposes the wrong metrics or labels for your use case, or when the target is internal software. Review the exporter's license, last release, open issues and how it handles credentials before you adopt it. If an existing exporter covers most needs, a small wrapper or sidecar may be cheaper than a full build.

How long does a first version of an exporter take?

The timeline depends on the number of metrics, the target's API maturity, how quickly test access arrives and how many review rounds the metric contract needs. Delays most often come from waiting for credentials or test data, not from writing the collector code. Ask for a schedule in the written scope with milestones for the metric list, a working build against the test environment, promtool checks and a documented handover. Any duration you are given should be tied to those milestones and to the access you have agreed to provide.

What does ongoing support for a custom exporter cover?

Ongoing support usually covers updates when the target system changes its API, upgrades to the Prometheus client library, fixes for scrape errors and performance problems, and review of new metrics before they ship. It can also include keeping documentation current and checking the exporter against new Prometheus releases. Support is recurring work, so ask whether it is offered as a retainer, how requests are prioritized, and who receives alerts when the exporter stops returning data. Agree on the target versions covered, since changes to the target system are the most common source of breakage.

How do we test an exporter before it reaches production?

Test the exporter in three layers: check the output format and metric names with promtool check metrics, run it against a test instance of the target system, and confirm that it returns correct values when the target is slow, partially available or returning errors. Your engineers should also check that scrape time stays within limits and that label values cannot grow without bound. Record what each test proves so the security and operations teams can review the evidence before go-live.

How DeployOpen scopes and delivers a custom exporter

DeployOpen scopes a custom exporter in writing before any code is written. The scope document fixes the metric set (each metric name, type, unit, help text and label set), the target access the exporter needs (which API, database or host it reads from, under which service account, and from which network segments), the security requirements (how the HTTP endpoint is protected, where credentials are stored, and what the process is allowed to read), and the acceptance tests that define done. Those tests usually include promtool check metrics output on the exposition, a scrape against a staging target, and a check that the exporter reports an error rather than stale values when its source is unavailable. Agreeing these items up front keeps the quote tied to a defined surface, and it gives your team a checklist to review before work starts.

During the build, DeployOpen implements the collectors, runs the linting and unit tests, and then tests the exporter the way it will run in production: one process per monitored system, scrape-time collection, and a load check against the source system so that the exporter does not add meaningful pressure to it. Security testing of the exporter is part of hardening, not an afterthought. Because exporters often take targets or credentials from configuration or URL parameters, DeployOpen reviews how those inputs are validated, how the process is sandboxed and what it can reach on the network, and then delivers a findings report with fixes and a retest. The metric contract is documented alongside the code: each metric's meaning, its labels, the cardinality it can produce and the alert rules it supports, so that dashboard and alerting authors can rely on it across releases.

Once the exporter is in service, DeployOpen can continue with ongoing support, updates when the client library or the monitored system changes, and periodic re-testing under a retainer. Ask any provider to confirm, in the quote, who owns the source code and documentation after handover, which environments the acceptance tests run in, and how metric contract changes are versioned and communicated to your alerting owners. Those answers determine whether the exporter stays maintainable after the engagement ends.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.