Kafka¶
mite_kafka is mite’s Kafka integration, built on
aiokafka. It installs a producer and a
consumer onto the journey context and reports metrics for both.
Install: pip install mite[kafka] (no functional change today — every mite
install already includes it; this will matter starting in mite 3.0).
Basic usage¶
from mite_kafka import mite_kafka
@mite_kafka
async def journey(ctx):
async with ctx.transaction("Produce a message"):
await ctx.kafka_producer.create_and_start(bootstrap_servers="localhost:9092")
await ctx.kafka_producer.send_and_wait("my-topic", value=b"hello")
await ctx.kafka_producer.stop()
@mite_kafka installs ctx.kafka_producer and ctx.kafka_consumer for the
duration of the journey call, then removes both attributes afterwards.
Neither is started automatically — the decorator attaches the wrapper
objects, but it’s the journey’s job to call create_and_start(...) and
stop() on whichever one it uses, same as it would with a plain aiokafka
client.
Producer¶
ctx.kafka_producer wraps aiokafka.AIOKafkaProducer:
create_and_start(*args, **kwargs)— forwards everything toAIOKafkaProducer(...)and starts it.bootstrap_serversis the one argument you’ll always need.send_and_wait(topic, key=None, value=None, **kwargs)— sends a message and reports it (see Metrics, below). Other keyword arguments are passed straight toaiokafka’ssend_and_wait.transaction(message)— an async context manager aroundctx.transaction(message), for naming the surrounding mite transaction. This names a mite transaction; it is not Kafka’s own transactional producer API.stop()— stops the underlyingAIOKafkaProducer.
Consumer¶
ctx.kafka_consumer wraps aiokafka.AIOKafkaConsumer:
create_and_start(*topics, **kwargs)— forwards everything toAIOKafkaConsumer(*topics, ...)and starts it.get_messages()— an async generator. Each message consumed is reported (see Metrics, below), then yielded to the caller.stop()— stops the underlyingAIOKafkaConsumer.
@mite_kafka
async def journey(ctx):
await ctx.kafka_consumer.create_and_start("my-topic", bootstrap_servers="localhost:9092")
async for message in ctx.kafka_consumer.get_messages():
...
await ctx.kafka_consumer.stop()
Metrics emitted¶
Every
send_and_waitcall sends akafka_producer_statsmessage withtopicandkey.Every message yielded by
get_messagessends akafka_consumer_statsmessage withtopic,partitionandoffset— though onlytopicandpartitionare used as labels on the registered stat (below);offsetis sent but not currently turned into a metric.
These are registered as mite_kafka_producer_stats_counter (labelled by
topic, key) and mite_kafka_consumer_stats_counter (labelled by topic,
partition), listed alongside every other processor on Customizing miteʼs stats.