# Kafka

> A Rust-backed Kafka client that tracks confluent-kafka, with explicit timeouts and EOS.

Source: https://docs.pyrula.io/kafka/

`pyrula.kafka` is a Kafka client written in Rust, with native asyncio and an Arrow path
and no librdkafka. The API tracks `confluent-kafka`. Two things differ: every networked
call is bounded by a timeout, and batch APIs (`produce_many_*`, `poll_batch`,
`poll_arrow`) keep per-record work out of Python. Throughput numbers are on
[Benchmarks](https://docs.pyrula.io/kafka/benchmarks.md).

```python
from pyrula import kafka
```

`pip install "pyrula[kafka]"`. Wheels cover Linux (glibc and musl), macOS
and Windows on x86_64 and ARM (aarch64 Linux needs glibc 2.28+). AWS MSK IAM auth is an
extra: `"pyrula[kafka,msk]"`.

Calls work on batches and return [`Either`](https://docs.pyrula.io/primitives/either.md) values instead of raising.
The examples assume an `events` topic: a local broker auto-creates it, managed Kafka usually
needs it created first ([Admin](https://docs.pyrula.io/kafka/admin.md)).

## Produce

```python
from pyrula.kafka import KafkaProducerConfig, KafkaProducer

config = KafkaProducerConfig(bootstrap_servers="localhost:9092")

with KafkaProducer(config) as producer:
    receipt = producer.produce_many_bytes("events", values=[b"a", b"b", b"c"])
    report = receipt.get().unwrap_or_raise()  # blocks until the broker acks the batch
```

## Consume

```python
from pyrula.kafka import KafkaConsumerConfig, KafkaConsumer

config = KafkaConsumerConfig(
    bootstrap_servers="localhost:9092",
    topics=["events"],
    group_id="my-group",
)

with KafkaConsumer(config) as consumer:
    while True:
        batch = consumer.poll_batch(max_records=500, timeout_ms=1000).unwrap_or_raise()
        if len(batch) == 0:
            continue  # early polls can be empty while the group joins
        for record in batch:
            print(record.partition, record.offset, record.value)
        consumer.commit(batch).unwrap_or_raise()
        break
```

A record has `topic`, `partition`, `offset`, `key`, `value` (bytes), `headers` and `timestamp_ms`.

Coming from confluent-kafka, see [Migrating from confluent-kafka](https://docs.pyrula.io/kafka/confluent-compat.md).
