# ClientKafkaProxy

**Kind:** Interface

**Source:** [`packages/microservices/interfaces/client-kafka-proxy.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/interfaces/client-kafka-proxy.interface.ts#L9)

**Part of:** [Microservices](subsystem-packages-microservices)

`ClientKafkaProxy` defines the Kafka client resources managed by a microservice client proxy. It exposes nullable `consumer` and `producer` references so the proxy can create, reuse, and clean up Kafka connections during its lifecycle.

## Properties

| Property | Type |
|---|---|
| `consumer` | `Consumer | null` |
| `producer` | `Producer | null` |

## Diagram

```mermaid
graph LR
  Proxy[Kafka Client Proxy] --> Interface[ClientKafkaProxy]
  Interface --> Consumer[consumer: Consumer | null]
  Interface --> Producer[producer: Producer | null]
  Consumer --> Kafka[Kafka Broker]
  Producer --> Kafka
```

## Usage

```ts
import type { Consumer, Producer } from 'kafkajs';
import type { ClientKafkaProxy } from './client-kafka-proxy.interface';

class KafkaClient implements ClientKafkaProxy {
  consumer: Consumer | null = null;
  producer: Producer | null = null;

  async publish(topic: string, message: unknown) {
    if (!this.producer) {
      throw new Error('Kafka producer has not been initialized.');
    }

    await this.producer.send({
      topic,
      messages: [{ value: JSON.stringify(message) }],
    });
  }

  async close() {
    await this.consumer?.disconnect();
    await this.producer?.disconnect();

    this.consumer = null;
    this.producer = null;
  }
}
```

## AI Coding Instructions

- Treat `consumer` and `producer` as optional lifecycle-managed resources; always handle the `null` case before calling Kafka methods.
- Initialize Kafka clients before subscribing, consuming, or publishing messages, and reset references to `null` after disconnecting.
- Use the KafkaJS `Consumer` and `Producer` types when implementing this interface.
- Ensure shutdown logic disconnects both resources safely, using optional chaining or explicit null checks.
