Most teams start their Prometheus journey with the usual suspects: node_exporter for host metrics, cAdvisor for containers, and maybe postgres_exporter or redis_exporter for their datastores. That's enough to answer infrastructure questions, but it tells you almost nothing about whether your application is actually doing its job. I learned this the hard way running a payment processing pipeline where CPU and memory looked perfect while thousands of jobs were silently stuck in a pending queue. Building a custom Prometheus exporter was the only way to expose the state that mattered, and in my experience, it's one of the highest-leverage things a platform team can do for application-specific monitoring.
Writing a prometheus exporter isn't complex once you understand the exposition format, but designing one that is reliable, low-cardinality, and maintainable in production requires more than copying an example from GitHub. This article covers the patterns I've used to ship custom metrics and robust instrumentation for everything from legacy Java monoliths to Go microservices that couldn't be modified directly.
Why Off-the-Shelf Exporters Leave Gaps in Application Visibility
Standard exporters are fantastic at telling you how the platform is behaving. They will tell you that your Kubernetes nodes are under memory pressure or that your Postgres instance has a high number of dead tuples. What they cannot tell you is that your order service has 4,200 orders in a payment_verification_failed state, or that your feature flag evaluation latency for a specific tenant has tripled.
Business-logic and domain-specific states are invisible to generic monitoring. That's the gap custom exporters fill. I tend to categorize application-specific metrics into three buckets:
State Metrics That Reflect Business Queues
These are gauges that represent the current count of items in a meaningful state. Think unprocessed_invoices, emails_pending_send, or shipments_awaiting_carrier_pickup. Unlike request latency or error rates, these metrics have no natural RED/USE equivalent. You have to query the application's source of truth directly — usually a database, Redis, or an internal API — to get them. If you only monitor request metrics, you'll miss the backlog building up asynchronously.
Operational Metrics Hidden Behind Proprietary APIs
Many commercial or legacy systems expose health via a vendor-specific HTTP endpoint, JMX bean, or CLI tool. A license server, a proprietary job scheduler, or an older ERP doesn't speak Prometheus. An exporter acts as a translation layer. I once wrote one that scraped a SOAP endpoint every 30 seconds, parsed the XML response for license utilization, and exposed it as a gauge. Without that bridge, we had no way to alert before we hit the license limit and blocked deployments.
Derived Health Signals That Require Correlation
Sometimes a single raw value isn't useful, but a derived calculation is. For example, comparing the timestamp of the last successful background job run against time() to expose seconds_since_last_successful_sync. This is far more actionable than just logging the event. If you are already investing in Structured Logging: JSON Format, Context Fields and Log Aggregation, you have the raw data, but logs are for forensics — metrics are for alerting. The exporter turns that event stream into a continuous signal.
Choosing Between Direct Instrumentation and a Standalone Exporter Process
When you need custom metrics, you have two fundamental architectural choices. You can instrument the application code directly using a Prometheus client library, or you can build a standalone exporter that runs alongside the application and probes it from the outside. The right choice depends entirely on whether you own the application code and how you deploy.
In my experience, direct instrumentation is always preferable when you can do it. It has lower overhead, lower latency, and avoids an extra moving part. A standalone exporter is the pragmatic choice for third-party software, legacy systems you can't rebuild, or when you need to aggregate metrics from multiple sources without touching every service.
I've seen teams try to use the Pushgateway as a shortcut for this — having a cron job push metrics to it instead of running a proper exporter. Don't. The Pushgateway is designed for short-lived batch jobs, not for long-lived gauges. It masks instance failures and makes staleness handling a nightmare.
| Approach | When to Use | Scrape Model | Failure Mode |
|---|---|---|---|
| Direct Instrumentation (Client Library) | You own the code (Go, Java, Python, Node.js) | Prometheus scrapes /metrics on the app itself |
App down = target down, clear signal |
| Standalone Exporter (Sidecar / Separate Deployment) | Black-box apps, databases, vendor APIs, legacy systems | Prometheus scrapes the exporter; exporter scrapes the app | Exporter can be up while app is down; requires up + custom exporter_last_scrape_success check |
| Pushgateway | Only for batch/cron jobs that exit quickly | Job pushes, Prometheus scrapes gateway | Stale metrics persist after job failure; high cardinality risk |
| OpenTelemetry Collector with Prometheus Receiver | When standardizing on OTel and need translation | Collector scrapes or receives, Prometheus scrapes collector | Adds complexity; useful if you already run the Collector |
How Deployment Topology Affects Your Decision
On Kubernetes, the pattern is well established. For direct instrumentation, you add Prometheus annotations or a ServiceMonitor and let Prometheus discover your pods. For standalone exporters, you typically run them as a sidecar in the same Pod if the metric is 1:1 with the app instance, or as a separate Deployment with a Service if it aggregates a shared resource like a single Redis queue. The Kubernetes Documentation on monitoring and service discovery is essential reading for getting scrape discovery right without hardcoding IPs.
In Docker or VM-based environments, I've found it cleaner to co-locate the exporter on the same host and use file_sd_configs for discovery. The Docker Documentation covers Prometheus-friendly logging, but for custom exporters you'll still need to manage TLS and network access to the /metrics endpoint yourself.
Designing Cardinality-Safe Metric Names and Label Schemas
This is where most first-time exporter authors get burned. A poorly designed label set can create a cardinality explosion that kills your Prometheus server. I once saw a team add user_id and request_id as labels to a histogram — they created millions of series in an afternoon and had to drop the WAL and restart.
Follow the Prometheus naming conventions strictly. They exist for a reason. Instrumenting correctly now saves you from painful recording rule rewrites later.
Naming and Type Conventions That Prevent Confusion
Use base units and add the suffix that describes the type. Counters must end in _total, histograms and summaries should concern _seconds or _bytes, and gauges should describe the current state.
myapp_queue_jobs_pending(Gauge) - correct. Describes current depth.myapp_jobs_processed_total(Counter) - correct. Monotonically increasing count.myapp_job_processing_duration_seconds(Histogram) - correct. Base unit is seconds, not milliseconds.myapp_jobs_pending- ambiguous. Is it a gauge or a total? Add the verb.
Always prefix with your application or domain name, e.g., myapp_ or payments_, to avoid collisions with other exporters in the same Prometheus.
The Cardinality Budget You Can't Exceed
Every unique combination of label values creates a new time series. A metric with 3 labels each having 10, 5, and 100 possible values is 5,000 series. Add a fourth label with 1,000 values and you're at 5 million.
Keep label values bounded and known in advance. Good labels: queue_name (5 queues), status (success, failure, retry), region (us-east-1, eu-west-1). Dangerous labels: email_address, order_id, ip_address, error_message. If you need high-cardinality data for debugging, that belongs in logs or traces, not metrics. For that, pair your metrics with a system like the one described in Distributed Tracing with Jaeger and Grafana Tempo: Setup and Best Practices — use metrics to know that something is wrong, and traces/logs to find out why.
I enforce a simple rule: if a label's cardinality is unbounded or user-controlled, it cannot be a Prometheus label. Use a log field instead.
Building a Production-Grade Python Exporter for Queue Depth Monitoring
Let's make this concrete. Suppose we have a background worker that processes jobs from a Postgres table. The application itself isn't instrumented, so we need a standalone exporter that queries SELECT status, count(*) FROM jobs GROUP BY status and exposes the result.
Below is a pattern I've reused several times. It uses the official prometheus_client Python library, handles scrape failures gracefully, and avoids blocking the HTTP handler with a DB call on every scrape.
from prometheus_client import start_http_server, Gauge, Counter
import psycopg2
import time
import os
# Gauges for current state
QUEUE_DEPTH = Gauge(
'myapp_queue_jobs_pending',
'Current number of jobs by status',
['queue', 'status']
)
# Counter for exporter health - critical for alerting
SCRAPE_SUCCESS = Gauge(
'myapp_exporter_last_scrape_success',
'1 if last scrape succeeded, 0 otherwise'
)
SCRAPE_DURATION = Gauge(
'myapp_exporter_last_scrape_duration_seconds',
'Duration of last scrape'
)
DB_DSN = os.environ["DATABASE_DSN"]
def collect_metrics():
start = time.time()
try:
conn = psycopg2.connect(DB_DSN, connect_timeout=5)
cur = conn.cursor()
cur.execute("""
SELECT queue_name, status, COUNT(*)
FROM jobs
WHERE created_at > NOW() - INTERVAL '24 hours'
GROUP BY 1, 2
""")
# Clear old label combinations before setting new ones
# to avoid stale series when a status goes to 0
QUEUE_DEPTH.clear()
for queue, status, count in cur.fetchall():
QUEUE_DEPTH.labels(queue=queue, status=status).set(count)
SCRAPE_SUCCESS.set(1)
cur.close()
conn.close()
except Exception as e:
# Never let an exception crash the exporter
# Expose failure so Prometheus can alert on it
SCRAPE_SUCCESS.set(0)
print(f"scrape failed: {e}")
finally:
SCRAPE_DURATION.set(time.time() - start)
if __name__ == '__main__':
start_http_server(8000)
while True:
collect_metrics()
time.sleep(15)
A few things to note here that only become obvious after running this in production. First, we use a background loop instead of a custom collector that queries on every HTTP GET to /metrics. If Prometheus scrapes with a 10s interval and your DB query takes 8s, a synchronous collector will cause scrape timeouts and overlapping queries. A background loop decouples collection from exposition. Second, we explicitly clear() the gauge before repopulating. Without this, if a status like failed goes from 5 to 0, the old series with value 5 will persist forever as a stale metric.
For Go services where you can instrument directly, the pattern is even cleaner. You would register a collector that updates the metric in-process:
package main
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
"time"
)
var (
jobsPending = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "myapp_queue_jobs_pending",
Help: "Current number of jobs by status",
},
[]string{"queue", "status"},
)
lastScrapeSuccess = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "myapp_exporter_last_scrape_success",
Help: "1 if last scrape succeeded",
})
)
func updateQueueMetrics() {
for {
counts, err := queryDB() // your DB logic
if err != nil {
lastScrapeSuccess.Set(0)
} else {
jobsPending.Reset()
for _, c := range counts {
jobsPending.WithLabelValues(c.Queue, c.Status).Set(float64(c.Count))
}
lastScrapeSuccess.Set(1)
}
time.Sleep(15 * time.Second)
}
}
func main() {
prometheus.MustRegister(jobsPending, lastScrapeSuccess)
go updateQueueMetrics()
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8000", nil)
}
Exposing Metrics Securely and Scraping Them Reliably at Scale
An exporter that works on your laptop is not the same as one that works at scale. You need to handle authentication, TLS, service discovery, and scrape reliability.
Securing the /metrics Endpoint
Do not expose /metrics to the public internet. In Kubernetes, use NetworkPolicies to restrict access to only the Prometheus namespace. If you need authentication — for example, an exporter running outside your VPC — use basic auth with TLS or run it behind a reverse proxy. The prometheus_client libraries don't handle auth natively for exposition, so you'll need to front it with something like nginx or use the prometheus_client's make_wsgi_app with auth middleware.
I've also found it useful to expose two ports: one for /metrics and one for /healthz or /ready. That way your liveness probe doesn't get confused with your scrape endpoint.
Configuring Prometheus for Resilient Scraping
Your scrape config should be defensive. Set a timeout shorter than your interval, and add relabeling to make debugging easier.
scrape_configs:
- job_name: 'myapp-queue-exporter'
scrape_interval: 30s
scrape_timeout: 10s
metrics_path: /metrics
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_app]
action: keep
regex: myapp-queue-exporter
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
metric_relabel_configs:
# Drop high-cardinality debug metrics in production
- source_labels: [__name__]
regex: 'myapp_debug_.*'
action: drop
This configuration assumes Kubernetes service discovery, but the same principles apply to static configs or Consul. The critical part is the metric_relabel_configs — it gives you a last chance to drop expensive series before they are ingested. I've used this to temporarily drop a misbehaving metric without redeploying the exporter.
Pair this with proper alerting. Don't just alert on up == 0. Alert on myapp_exporter_last_scrape_success == 0 for more than 5 minutes. The exporter process can be up while the DB is unreachable, and up will still be 1. For a complete alerting workflow, I recommend setting up the rules as described in Prometheus and Alertmanager: Complete Setup for Production Monitoring — your custom metrics are only valuable if someone gets notified when they breach a threshold.
Debugging Stale Metrics, Memory Leaks, and Scrape Timeouts in Production
Once your exporter is deployed, the next set of problems is subtle. Metrics that never disappear, memory that grows linearly, and scrapes that time out intermittently.
Eliminating Stale Series and Ghost Labels
Prometheus has a concept of staleness: if a target stops exposing a series, Prometheus will mark it stale after 5 minutes. But if your exporter keeps exposing the series with its last value forever — because you never cleared it — Prometheus has no way to know it's stale. This is exactly what happens if you do Gauge.labels(...).set(0) only when you see a zero count, but you skip setting it entirely when the query returns no rows for that label combination.
The fix, as shown in the Python example, is to either clear() or Reset() the metric before each collection cycle and then repopulate it. For client libraries that don't support clear, set the value to 0 explicitly for all known label combinations, or maintain a set of previously seen label values and remove those not seen in the last collection.
Diagnosing Memory Growth in Long-Running Exporters
I've debugged two common causes for this. First, unbounded label cardinality — discussed above — which creates new series objects that are never freed. Second, holding onto database connections or HTTP clients without timeouts. Always set connect_timeout and statement_timeout for your DB queries, and use a circuit breaker if the dependency is flaky. An exporter that blocks for 60 seconds on a dead DB will pile up threads/goroutines and eventually OOM.
Instrument your exporter itself. Expose process_resident_memory_bytes via the default Python or Go client collectors, and create a dashboard that tracks your exporter's own scrape duration and memory usage. If myapp_exporter_last_scrape_duration_seconds starts climbing toward your scrape_timeout, you have a problem before Prometheus starts logging context deadline exceeded errors.
Handling Slow Dependencies Without Blocking Scrapes
If your exporter needs to call a slow upstream — say an external SaaS API that takes 4 seconds — never do it synchronously inside the Prometheus scrape handler. Use the background refresh loop pattern. Prometheus should always get an instant response from /metrics with the last known values. I've found that a 15-30 second background refresh is a good balance between freshness and load, even if Prometheus scrapes every 10 seconds. The last value will be slightly stale, but that's far better than a timed-out scrape that yields no data at all.
Frequently Asked Questions
Should I use a Gauge or Counter for queue depth and job failures?
Use a Gauge for queue depth because it can go up and down — myapp_queue_jobs_pending is a classic gauge. Use a Counter for cumulative events like myapp_jobs_failed_total that only increases and is reset on restart. If you need to alert on the rate of failures, a Counter with rate() or increase() is what you want. Never use a Counter for something that needs to decrease.
How do I handle metrics that require database queries without overloading the database?
Cache and throttle. Run your query in a background loop every 15-30 seconds instead of on every scrape, and expose the cached result. Add a query timeout of 3-5 seconds, keep the query lightweight with appropriate indexes, and consider reading from a replica. I also add a myapp_exporter_last_scrape_success gauge so I can alert if the DB becomes unreachable without spamming the DB with failed retries.
Can I write a custom exporter in any language, or do I need to use Go?
You can use any language. The exposition format is just text over HTTP, so any language that can serve HTTP can be an exporter. That said, Go and Python have the most mature client libraries and the best performance characteristics for this use case. If you're already writing your service in Java, use the Java client and instrument directly rather than writing a separate Python exporter.
What is the difference between a custom exporter and direct instrumentation with a client library?
Direct instrumentation means adding prometheus_client code inside your application to expose /metrics from the app itself — lowest overhead and best for services you own. A custom exporter is a separate process that probes your application externally via its API, database, or logs — ideal for black-box, legacy, or vendor systems you cannot modify. Both produce the same Prometheus exposition format.