0
# Pushgateway
1
2
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.
3
4
## Capabilities
5
6
### Pushgateway Class
7
8
The Pushgateway class provides methods to push, add, or delete metrics from a Prometheus Push Gateway.
9
10
```typescript { .api }
11
/**
12
* Push metrics to a Pushgateway
13
*/
14
class Pushgateway<T extends RegistryContentType> {
15
/**
16
* @param url Complete url to the Pushgateway. If port is needed append url with :port
17
* @param options Options
18
* @param registry Registry
19
*/
20
constructor(url: string, options?: any, registry?: Registry<T>);
21
22
/**
23
* Add metric and overwrite old ones
24
* @param params Push parameters
25
*/
26
pushAdd(
27
params: Pushgateway.Parameters
28
): Promise<{ resp?: unknown; body?: unknown }>;
29
30
/**
31
* Overwrite all metric (using PUT to Pushgateway)
32
* @param params Push parameters
33
*/
34
push(
35
params: Pushgateway.Parameters
36
): Promise<{ resp?: unknown; body?: unknown }>;
37
38
/**
39
* Delete all metrics for jobName
40
* @param params Push parameters
41
*/
42
delete(
43
params: Pushgateway.Parameters
44
): Promise<{ resp?: unknown; body?: unknown }>;
45
}
46
47
namespace Pushgateway {
48
interface Parameters {
49
/**
50
* Jobname that is pushing the metric
51
*/
52
jobName: string;
53
/**
54
* Label sets used in the url when making a request to the Pushgateway,
55
*/
56
groupings?: {
57
[key: string]: string;
58
};
59
}
60
}
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
import { Pushgateway, register, Counter } from "prom-client";
67
68
// Create a Pushgateway instance
69
const gateway = new Pushgateway("http://localhost:9091");
70
71
// Create metrics
72
const batchJobCounter = new Counter({
73
name: "batch_job_completed_total",
74
help: "Total completed batch jobs",
75
labelNames: ["job_type", "status"],
76
});
77
78
// Increment counter
79
batchJobCounter.inc({ job_type: "data_processing", status: "success" });
80
81
// Push metrics to gateway (replaces existing metrics for this job)
82
await gateway.push({ jobName: "data_processor_job" });
83
84
// Add metrics to gateway (merges with existing metrics)
85
await gateway.pushAdd({ jobName: "data_processor_job" });
86
87
// Delete metrics for a job
88
await gateway.delete({ jobName: "data_processor_job" });
89
```
90
91
### Push Operations
92
93
#### Push (PUT)
94
95
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.
96
97
```typescript { .api }
98
/**
99
* Overwrite all metric (using PUT to Pushgateway)
100
* @param params Push parameters
101
*/
102
push(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>;
103
```
104
105
**Usage Example:**
106
107
```typescript
108
import { Pushgateway, register, Gauge } from "prom-client";
109
110
const gateway = new Pushgateway("http://pushgateway:9091");
111
112
const jobDuration = new Gauge({
113
name: "batch_job_duration_seconds",
114
help: "Duration of batch job in seconds",
115
});
116
117
// Run batch job
118
const startTime = Date.now();
119
// ... job logic ...
120
const duration = (Date.now() - startTime) / 1000;
121
122
jobDuration.set(duration);
123
124
// Replace all metrics for this job
125
await gateway.push({
126
jobName: "nightly_backup",
127
groupings: { instance: "backup-server-1" },
128
});
129
```
130
131
#### Push Add (POST)
132
133
The `pushAdd` method adds metrics to existing ones in the Push Gateway. Values are summed for metrics with the same name and labels.
134
135
```typescript { .api }
136
/**
137
* Add metric and overwrite old ones
138
* @param params Push parameters
139
*/
140
pushAdd(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>;
141
```
142
143
**Usage Example:**
144
145
```typescript
146
import { Pushgateway, register, Counter } from "prom-client";
147
148
const gateway = new Pushgateway("http://pushgateway:9091");
149
150
const processedRecords = new Counter({
151
name: "records_processed_total",
152
help: "Total records processed",
153
});
154
155
// Process some records
156
processedRecords.inc(1000);
157
158
// Add to existing metrics (accumulates with previous pushes)
159
await gateway.pushAdd({
160
jobName: "record_processor",
161
groupings: { batch_id: "batch_123" },
162
});
163
```
164
165
#### Delete
166
167
The `delete` method removes all metrics for the specified job name and groupings from the Push Gateway.
168
169
```typescript { .api }
170
/**
171
* Delete all metrics for jobName
172
* @param params Push parameters
173
*/
174
delete(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>;
175
```
176
177
**Usage Example:**
178
179
```typescript
180
import { Pushgateway } from "prom-client";
181
182
const gateway = new Pushgateway("http://pushgateway:9091");
183
184
// Clean up metrics after job completion
185
await gateway.delete({
186
jobName: "temp_job",
187
groupings: { run_id: "run_456" },
188
});
189
```
190
191
### Grouping Labels
192
193
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.
194
195
```typescript { .api }
196
interface Parameters {
197
jobName: string;
198
groupings?: {
199
[key: string]: string;
200
};
201
}
202
```
203
204
**Usage Examples:**
205
206
```typescript
207
import { Pushgateway, register, Counter } from "prom-client";
208
209
const gateway = new Pushgateway("http://pushgateway:9091");
210
211
const itemsProcessed = new Counter({
212
name: "items_processed_total",
213
help: "Total items processed",
214
});
215
216
itemsProcessed.inc(500);
217
218
// Different grouping strategies
219
await gateway.push({
220
jobName: "etl_job",
221
groupings: {
222
instance: "worker-01",
223
batch_date: "2023-12-01",
224
region: "us-west-2",
225
},
226
});
227
228
// Another instance of the same job
229
await gateway.push({
230
jobName: "etl_job",
231
groupings: {
232
instance: "worker-02",
233
batch_date: "2023-12-01",
234
region: "us-east-1",
235
},
236
});
237
```
238
239
### Custom Registry
240
241
By default, the Pushgateway uses the global registry. You can specify a custom registry to push only specific metrics.
242
243
```typescript
244
import { Pushgateway, Registry, Counter } from "prom-client";
245
246
// Create custom registry for batch job metrics
247
const batchJobRegistry = new Registry();
248
249
const batchMetrics = new Counter({
250
name: "batch_operations_total",
251
help: "Total batch operations",
252
registers: [batchJobRegistry],
253
});
254
255
// Create Pushgateway with custom registry
256
const gateway = new Pushgateway(
257
"http://pushgateway:9091",
258
{},
259
batchJobRegistry
260
);
261
262
batchMetrics.inc(100);
263
264
// Push only metrics from the custom registry
265
await gateway.push({ jobName: "batch_processor" });
266
```
267
268
### Options Configuration
269
270
The Pushgateway constructor accepts an options object for HTTP configuration:
271
272
```typescript
273
import { Pushgateway, register } from "prom-client";
274
275
const gateway = new Pushgateway(
276
"http://pushgateway:9091",
277
{
278
timeout: 5000, // Request timeout in ms
279
headers: {
280
"Authorization": "Bearer token123",
281
"X-Custom-Header": "value",
282
},
283
// Additional HTTP options can be passed
284
}
285
);
286
```
287
288
### Error Handling
289
290
All Pushgateway methods return promises that should be handled appropriately:
291
292
```typescript
293
import { Pushgateway, register, Counter } from "prom-client";
294
295
const gateway = new Pushgateway("http://pushgateway:9091");
296
297
const jobsCompleted = new Counter({
298
name: "jobs_completed_total",
299
help: "Total completed jobs",
300
});
301
302
jobsCompleted.inc();
303
304
try {
305
const result = await gateway.push({ jobName: "my_job" });
306
console.log("Metrics pushed successfully", result);
307
} catch (error) {
308
console.error("Failed to push metrics:", error);
309
// Handle the error appropriately (retry, alert, etc.)
310
}
311
```
312
313
### Complete Batch Job Example
314
315
```typescript
316
import { Pushgateway, Registry, Counter, Gauge, Histogram } from "prom-client";
317
318
// Create registry for batch job metrics
319
const batchRegistry = new Registry();
320
321
// Create metrics
322
const recordsProcessed = new Counter({
323
name: "batch_records_processed_total",
324
help: "Total records processed in batch job",
325
registers: [batchRegistry],
326
});
327
328
const jobDuration = new Gauge({
329
name: "batch_job_duration_seconds",
330
help: "Duration of batch job in seconds",
331
registers: [batchRegistry],
332
});
333
334
const recordProcessingTime = new Histogram({
335
name: "batch_record_processing_seconds",
336
help: "Time to process individual records",
337
buckets: [0.001, 0.01, 0.1, 1, 5],
338
registers: [batchRegistry],
339
});
340
341
// Initialize Pushgateway
342
const gateway = new Pushgateway(
343
"http://pushgateway:9091",
344
{ timeout: 10000 },
345
batchRegistry
346
);
347
348
async function runBatchJob(batchId: string) {
349
const startTime = Date.now();
350
351
try {
352
// Process records
353
for (let i = 0; i < 1000; i++) {
354
const recordStart = Date.now();
355
356
// ... process record ...
357
358
const recordDuration = (Date.now() - recordStart) / 1000;
359
recordProcessingTime.observe(recordDuration);
360
recordsProcessed.inc();
361
}
362
363
// Set job duration
364
const totalDuration = (Date.now() - startTime) / 1000;
365
jobDuration.set(totalDuration);
366
367
// Push successful completion metrics
368
await gateway.push({
369
jobName: "data_processing_job",
370
groupings: {
371
batch_id: batchId,
372
status: "success",
373
instance: process.env.HOSTNAME || "unknown",
374
},
375
});
376
377
console.log(`Batch ${batchId} completed successfully`);
378
379
} catch (error) {
380
console.error(`Batch ${batchId} failed:`, error);
381
382
// Push failure metrics
383
await gateway.push({
384
jobName: "data_processing_job",
385
groupings: {
386
batch_id: batchId,
387
status: "failure",
388
instance: process.env.HOSTNAME || "unknown",
389
},
390
});
391
}
392
}
393
394
// Run batch job
395
runBatchJob("batch_001");
396
```
397
398
## Types
399
400
```typescript { .api }
401
interface Pushgateway.Parameters {
402
jobName: string;
403
groupings?: {
404
[key: string]: string;
405
};
406
}
407
408
type RegistryContentType = PrometheusContentType | OpenMetricsContentType;
409
```