CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-prom-client

Client for prometheus that provides comprehensive Prometheus metrics collection and exposition for Node.js applications

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

pushgateway.mddocs/

Pushgateway

The Pushgateway support in prom-client allows you to push metrics to a Prometheus Push Gateway. This is essential for batch jobs, scheduled tasks, and short-lived processes that cannot be scraped directly by Prometheus.

Capabilities

Pushgateway Class

The Pushgateway class provides methods to push, add, or delete metrics from a Prometheus Push Gateway.

/**
 * Push metrics to a Pushgateway
 */
class Pushgateway<T extends RegistryContentType> {
  /**
   * @param url Complete url to the Pushgateway. If port is needed append url with :port
   * @param options Options
   * @param registry Registry
   */
  constructor(url: string, options?: any, registry?: Registry<T>);

  /**
   * Add metric and overwrite old ones
   * @param params Push parameters
   */
  pushAdd(
    params: Pushgateway.Parameters
  ): Promise<{ resp?: unknown; body?: unknown }>;

  /**
   * Overwrite all metric (using PUT to Pushgateway)
   * @param params Push parameters
   */
  push(
    params: Pushgateway.Parameters
  ): Promise<{ resp?: unknown; body?: unknown }>;

  /**
   * Delete all metrics for jobName
   * @param params Push parameters
   */
  delete(
    params: Pushgateway.Parameters
  ): Promise<{ resp?: unknown; body?: unknown }>;
}

namespace Pushgateway {
  interface Parameters {
    /**
     * Jobname that is pushing the metric
     */
    jobName: string;
    /**
     * Label sets used in the url when making a request to the Pushgateway,
     */
    groupings?: {
      [key: string]: string;
    };
  }
}

Usage Examples:

import { Pushgateway, register, Counter } from "prom-client";

// Create a Pushgateway instance
const gateway = new Pushgateway("http://localhost:9091");

// Create metrics
const batchJobCounter = new Counter({
  name: "batch_job_completed_total",
  help: "Total completed batch jobs",
  labelNames: ["job_type", "status"],
});

// Increment counter
batchJobCounter.inc({ job_type: "data_processing", status: "success" });

// Push metrics to gateway (replaces existing metrics for this job)
await gateway.push({ jobName: "data_processor_job" });

// Add metrics to gateway (merges with existing metrics)
await gateway.pushAdd({ jobName: "data_processor_job" });

// Delete metrics for a job
await gateway.delete({ jobName: "data_processor_job" });

Push Operations

Push (PUT)

The push method replaces all metrics for the specified job name. This is useful when you want to ensure only the current metrics are present.

/**
 * Overwrite all metric (using PUT to Pushgateway)
 * @param params Push parameters
 */
push(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>;

Usage Example:

import { Pushgateway, register, Gauge } from "prom-client";

const gateway = new Pushgateway("http://pushgateway:9091");

const jobDuration = new Gauge({
  name: "batch_job_duration_seconds",
  help: "Duration of batch job in seconds",
});

// Run batch job
const startTime = Date.now();
// ... job logic ...
const duration = (Date.now() - startTime) / 1000;

jobDuration.set(duration);

// Replace all metrics for this job
await gateway.push({
  jobName: "nightly_backup",
  groupings: { instance: "backup-server-1" },
});

Push Add (POST)

The pushAdd method adds metrics to existing ones in the Push Gateway. Values are summed for metrics with the same name and labels.

/**
 * Add metric and overwrite old ones
 * @param params Push parameters
 */
pushAdd(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>;

Usage Example:

import { Pushgateway, register, Counter } from "prom-client";

const gateway = new Pushgateway("http://pushgateway:9091");

const processedRecords = new Counter({
  name: "records_processed_total",
  help: "Total records processed",
});

// Process some records
processedRecords.inc(1000);

// Add to existing metrics (accumulates with previous pushes)
await gateway.pushAdd({
  jobName: "record_processor",
  groupings: { batch_id: "batch_123" },
});

Delete

The delete method removes all metrics for the specified job name and groupings from the Push Gateway.

/**
 * Delete all metrics for jobName
 * @param params Push parameters
 */
delete(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>;

Usage Example:

import { Pushgateway } from "prom-client";

const gateway = new Pushgateway("http://pushgateway:9091");

// Clean up metrics after job completion
await gateway.delete({
  jobName: "temp_job",
  groupings: { run_id: "run_456" },
});

Grouping Labels

Grouping labels allow you to partition metrics by additional dimensions beyond the job name. This is useful for distinguishing between different instances, batches, or runs of the same job.

interface Parameters {
  jobName: string;
  groupings?: {
    [key: string]: string;
  };
}

Usage Examples:

import { Pushgateway, register, Counter } from "prom-client";

const gateway = new Pushgateway("http://pushgateway:9091");

const itemsProcessed = new Counter({
  name: "items_processed_total",
  help: "Total items processed",
});

itemsProcessed.inc(500);

// Different grouping strategies
await gateway.push({
  jobName: "etl_job",
  groupings: {
    instance: "worker-01",
    batch_date: "2023-12-01",
    region: "us-west-2",
  },
});

// Another instance of the same job
await gateway.push({
  jobName: "etl_job",
  groupings: {
    instance: "worker-02",
    batch_date: "2023-12-01",
    region: "us-east-1",
  },
});

Custom Registry

By default, the Pushgateway uses the global registry. You can specify a custom registry to push only specific metrics.

import { Pushgateway, Registry, Counter } from "prom-client";

// Create custom registry for batch job metrics
const batchJobRegistry = new Registry();

const batchMetrics = new Counter({
  name: "batch_operations_total",
  help: "Total batch operations",
  registers: [batchJobRegistry],
});

// Create Pushgateway with custom registry
const gateway = new Pushgateway(
  "http://pushgateway:9091",
  {},
  batchJobRegistry
);

batchMetrics.inc(100);

// Push only metrics from the custom registry
await gateway.push({ jobName: "batch_processor" });

Options Configuration

The Pushgateway constructor accepts an options object for HTTP configuration:

import { Pushgateway, register } from "prom-client";

const gateway = new Pushgateway(
  "http://pushgateway:9091",
  {
    timeout: 5000, // Request timeout in ms
    headers: {
      "Authorization": "Bearer token123",
      "X-Custom-Header": "value",
    },
    // Additional HTTP options can be passed
  }
);

Error Handling

All Pushgateway methods return promises that should be handled appropriately:

import { Pushgateway, register, Counter } from "prom-client";

const gateway = new Pushgateway("http://pushgateway:9091");

const jobsCompleted = new Counter({
  name: "jobs_completed_total",
  help: "Total completed jobs",
});

jobsCompleted.inc();

try {
  const result = await gateway.push({ jobName: "my_job" });
  console.log("Metrics pushed successfully", result);
} catch (error) {
  console.error("Failed to push metrics:", error);
  // Handle the error appropriately (retry, alert, etc.)
}

Complete Batch Job Example

import { Pushgateway, Registry, Counter, Gauge, Histogram } from "prom-client";

// Create registry for batch job metrics
const batchRegistry = new Registry();

// Create metrics
const recordsProcessed = new Counter({
  name: "batch_records_processed_total",
  help: "Total records processed in batch job",
  registers: [batchRegistry],
});

const jobDuration = new Gauge({
  name: "batch_job_duration_seconds",
  help: "Duration of batch job in seconds",
  registers: [batchRegistry],
});

const recordProcessingTime = new Histogram({
  name: "batch_record_processing_seconds",
  help: "Time to process individual records",
  buckets: [0.001, 0.01, 0.1, 1, 5],
  registers: [batchRegistry],
});

// Initialize Pushgateway
const gateway = new Pushgateway(
  "http://pushgateway:9091",
  { timeout: 10000 },
  batchRegistry
);

async function runBatchJob(batchId: string) {
  const startTime = Date.now();
  
  try {
    // Process records
    for (let i = 0; i < 1000; i++) {
      const recordStart = Date.now();
      
      // ... process record ...
      
      const recordDuration = (Date.now() - recordStart) / 1000;
      recordProcessingTime.observe(recordDuration);
      recordsProcessed.inc();
    }
    
    // Set job duration
    const totalDuration = (Date.now() - startTime) / 1000;
    jobDuration.set(totalDuration);
    
    // Push successful completion metrics
    await gateway.push({
      jobName: "data_processing_job",
      groupings: {
        batch_id: batchId,
        status: "success",
        instance: process.env.HOSTNAME || "unknown",
      },
    });
    
    console.log(`Batch ${batchId} completed successfully`);
    
  } catch (error) {
    console.error(`Batch ${batchId} failed:`, error);
    
    // Push failure metrics
    await gateway.push({
      jobName: "data_processing_job",
      groupings: {
        batch_id: batchId,
        status: "failure",
        instance: process.env.HOSTNAME || "unknown",
      },
    });
  }
}

// Run batch job
runBatchJob("batch_001");

Types

interface Pushgateway.Parameters {
  jobName: string;
  groupings?: {
    [key: string]: string;
  };
}

type RegistryContentType = PrometheusContentType | OpenMetricsContentType;

Install with Tessl CLI

npx tessl i tessl/npm-prom-client

docs

cluster.md

default-metrics.md

index.md

metrics.md

pushgateway.md

registry.md

tile.json