npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@tamasha/kafka-connection

v1.0.6

Published

KafkaJS connection manager for producers and consumers with safe cleanup

Readme

@tamasha/kafka-connection

KafkaJS connection manager for microservice architecture with connection instances.

  • Initialize connection with await KafkaConnection.init({...}) - returns a connection instance
  • Use produce() and subscribe() methods on the connection instance
  • Support multiple connection instances for different microservices
  • Safe cleanup with destroy() method

Install

npm install @tamasha/kafka-connection

Basic Usage

import { KafkaConnection } from "@tamasha/kafka-connection";

// Initialize connection - returns a connection instance
const kafka = await KafkaConnection.init({
  brokers: ["localhost:9092"],
  clientId: "my-app",
});

// Produce messages
await kafka.produce({
  topic: "events",
  messages: [
    {
      key: "user-123",
      value: JSON.stringify({ userId: "user-123", event: "login" }),
    },
  ],
});

// Subscribe to topics
await kafka.subscribe(
  {
    groupId: "my-consumer-group",
  },
  "events",
  async ({ topic, partition, message }) => {
    const data = JSON.parse(message.value?.toString() || "{}");
    console.log("Received:", data);
    // Process message...
  }
);

// Cleanup
await kafka.destroy();

Microservice Architecture

Each microservice can create its own connection instance:

// User Service
class UserService {
  private constructor(private kafka: any) {}

  static async create() {
    const kafka = await KafkaConnection.init({
      name: "user-service",
      brokers: ["localhost:9092"],
      clientId: "user-service",
    });
    return new UserService(kafka);
  }

  async publishUserEvent(event: any) {
    await this.kafka.produce({
      topic: "user-events",
      messages: [{ key: event.userId, value: JSON.stringify(event) }],
    });
  }

  async startConsuming() {
    await this.kafka.subscribe(
      { groupId: "user-service-consumer" },
      "order-events",
      async ({ message }) => {
        // Process order events...
      }
    );
  }

  async shutdown() {
    await this.kafka.destroy();
  }
}

// Order Service
class OrderService {
  private constructor(private kafka: any) {}

  static async create() {
    const kafka = await KafkaConnection.init({
      name: "order-service",
      brokers: ["localhost:9092"],
      clientId: "order-service",
    });
    return new OrderService(kafka);
  }

  async publishOrderEvent(event: any) {
    await this.kafka.produce({
      topic: "order-events",
      messages: [{ key: event.orderId, value: JSON.stringify(event) }],
    });
  }

  async shutdown() {
    await this.kafka.destroy();
  }
}

Connection Management

Named Connections

// Create named connections
const userKafka = await KafkaConnection.init({
  name: "user-service",
  brokers: ["localhost:9092"],
});

const orderKafka = await KafkaConnection.init({
  name: "order-service",
  brokers: ["localhost:9092"],
});

// Later, retrieve the same connection
const sameKafka = KafkaConnection.getConnection("user-service");

Default Connection

// If no name is provided, uses "default"
const kafka = await KafkaConnection.init({
  brokers: ["localhost:9092"],
});

// Retrieve default connection
const defaultKafka = KafkaConnection.getConnection("default");

Cleanup

// Destroy specific connection
await KafkaConnection.destroyConnection("user-service");

// Destroy all connections
await KafkaConnection.destroyAll();

Advanced Features

Custom Producer Configuration

const kafka = await KafkaConnection.init({
  brokers: ["localhost:9092"],
  defaultProducerConfig: {
    idempotent: true,
    maxInFlightRequests: 5,
  },
});

// Or specify per message
await kafka.produce(
  {
    topic: "events",
    messages: [{ key: "test", value: "test" }],
  },
  {
    idempotent: false,
  }
);

Batch Processing

// Produce multiple messages
await kafka.produceBatch([
  {
    topic: "events",
    messages: [{ key: "1", value: "message1" }],
  },
  {
    topic: "events",
    messages: [{ key: "2", value: "message2" }],
  },
]);

// Subscribe with batch handler
await kafka.subscribe(
  { groupId: "batch-consumer" },
  "events",
  async ({ batch }) => {
    for (const message of batch.messages) {
      // Process each message in batch
    }
  },
  { useBatch: true }
);

Multiple Topics

await kafka.subscribe(
  { groupId: "multi-topic-consumer" },
  ["topic1", "topic2", "topic3"],
  async ({ topic, message }) => {
    console.log(`Received from ${topic}:`, message.value?.toString());
  }
);

Notes

  • Each connection instance manages its own producers and consumers
  • Producers are lazily initialized and connected when first used
  • Consumers must be explicitly subscribed using subscribe()
  • Call destroy() during graceful shutdown to ensure all connections are closed
  • Connection instances are cached by name - calling init() with the same name returns the existing instance