kafka-pub-sub
Version:
Enterprise-grade Kafka publish/subscribe library for Node.js — producer pool, batch sending, DLQ, SSL/SASL, multi-broker, and real-world industry examples.
85 lines (76 loc) • 2.61 kB
JavaScript
const kafka = require('./config/kafka');
const config = require('./config/config');
/**
* Performs a lightweight connectivity probe against the configured Kafka brokers.
*
* Uses the admin client to fetch cluster metadata and derives broker health.
* Suitable for:
* - Kubernetes liveness / readiness probes
* - Load-balancer health endpoints
* - Startup checks in service initialisation
*
* @param {Object} [options={}]
* @param {number} [options.timeout=5000] - Max ms to wait for broker response.
* @return {Promise<HealthStatus>}
*
* @typedef {Object} HealthStatus
* @property {boolean} healthy - True when the cluster is reachable.
* @property {number} brokerCount - Number of brokers reported by the cluster.
* @property {string[]} brokers - Configured broker URLs.
* @property {string} clusterId - Kafka cluster ID string.
* @property {string} checkedAt - ISO timestamp of the check.
* @property {string} [error] - Error message when healthy=false.
*
* @example — Kubernetes readiness probe
* app.get('/health/kafka', async (req, res) => {
* const status = await HealthCheck();
* res.status(status.healthy ? 200 : 503).json(status);
* });
*
* @example — startup guard
* const status = await HealthCheck({ timeout: 10000 });
* if (!status.healthy) {
* console.error('Kafka unreachable, aborting startup:', status.error);
* process.exit(1);
* }
*/
const HealthCheck = async (options = {}) => {
const { timeout = 5000 } = options;
const checkedAt = new Date().toISOString();
const admin = kafka.admin();
let timer;
const timeoutPromise = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Health check timed out after ${timeout}ms`)), timeout);
});
const clearTimer = () => clearTimeout(timer);
try {
await Promise.race([admin.connect(), timeoutPromise]);
const cluster = await Promise.race([admin.describeCluster(), timeoutPromise]);
clearTimer();
await admin.disconnect();
return {
healthy: true,
brokerCount: cluster.brokers.length,
brokers: config.kafka_broker_urls,
clusterId: cluster.clusterId,
controllerId: cluster.controller,
checkedAt,
};
} catch (error) {
clearTimer();
try {
await admin.disconnect();
} catch (_) {
// ignore cleanup errors
}
return {
healthy: false,
brokerCount: 0,
brokers: config.kafka_broker_urls,
clusterId: null,
checkedAt,
error: error.message,
};
}
};
module.exports = HealthCheck;