Skip to content

AsyncConfluentConsumer

faststream.confluent.helpers.AsyncConfluentConsumer #

AsyncConfluentConsumer(
    *topics: Topic,
    config: ConfluentFastConfig,
    logger: LoggerState,
    admin_service: AdminService,
    partitions: Sequence[TopicPartition],
    bootstrap_servers: str | list[str] = "localhost",
    client_id: str | None = "confluent-kafka-consumer",
    group_id: str | None = None,
    group_instance_id: str | None = None,
    fetch_max_wait_ms: int = 500,
    fetch_max_bytes: int = 52428800,
    fetch_min_bytes: int = 1,
    max_partition_fetch_bytes: int = 1 * 1024 * 1024,
    retry_backoff_ms: int = 100,
    auto_offset_reset: str = "latest",
    enable_auto_commit: bool = True,
    auto_commit_interval_ms: int = 5000,
    check_crcs: bool = True,
    metadata_max_age_ms: int = 5 * 60 * 1000,
    partition_assignment_strategy: str
    | list[Any] = "roundrobin",
    max_poll_interval_ms: int = 300000,
    session_timeout_ms: int = 10000,
    heartbeat_interval_ms: int = 3000,
    security_protocol: str = "PLAINTEXT",
    connections_max_idle_ms: int = 540000,
    isolation_level: str = "read_uncommitted",
    allow_auto_create_topics: bool = True,
    on_assign: Callable[..., None] | None = None,
    on_revoke: Callable[..., None] | None = None,
    on_lost: Callable[..., None] | None = None,
)

An asynchronous Python Kafka client for consuming messages using the "confluent-kafka" package.

Source code in faststream/confluent/helpers/client.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def __init__(
    self,
    *topics: "Topic",
    config: config_module.ConfluentFastConfig,
    logger: "LoggerState",
    admin_service: "AdminService",
    # kwargs options
    partitions: Sequence["TopicPartition"],
    bootstrap_servers: str | list[str] = "localhost",
    # consumer options
    client_id: str | None = "confluent-kafka-consumer",
    group_id: str | None = None,
    group_instance_id: str | None = None,
    fetch_max_wait_ms: int = 500,
    fetch_max_bytes: int = 52428800,
    fetch_min_bytes: int = 1,
    max_partition_fetch_bytes: int = 1 * 1024 * 1024,
    retry_backoff_ms: int = 100,
    auto_offset_reset: str = "latest",
    enable_auto_commit: bool = True,
    auto_commit_interval_ms: int = 5000,
    check_crcs: bool = True,
    metadata_max_age_ms: int = 5 * 60 * 1000,
    partition_assignment_strategy: str | list[Any] = "roundrobin",
    max_poll_interval_ms: int = 300000,
    session_timeout_ms: int = 10000,
    heartbeat_interval_ms: int = 3000,
    security_protocol: str = "PLAINTEXT",
    connections_max_idle_ms: int = 540000,
    isolation_level: str = "read_uncommitted",
    allow_auto_create_topics: bool = True,
    # rebalance callbacks
    on_assign: Callable[..., None] | None = None,
    on_revoke: Callable[..., None] | None = None,
    on_lost: Callable[..., None] | None = None,
) -> None:
    self.admin_client = admin_service
    self.logger_state = logger

    self._on_assign = on_assign
    self._on_revoke = on_revoke
    self._on_lost = on_lost

    self.topics = list(topics)
    self.partitions = partitions

    if not isinstance(partition_assignment_strategy, str):
        partition_assignment_strategy = ",".join(
            [
                x if isinstance(x, str) else x().name
                for x in partition_assignment_strategy
            ],
        )

    config_from_params = {
        "allow.auto.create.topics": allow_auto_create_topics,
        "topic.metadata.refresh.interval.ms": 1000,
        "bootstrap.servers": bootstrap_servers,
        "client.id": client_id,
        "group.id": group_id or "faststream-consumer-group",
        "group.instance.id": group_instance_id,
        "fetch.wait.max.ms": fetch_max_wait_ms,
        "fetch.max.bytes": fetch_max_bytes,
        "fetch.min.bytes": fetch_min_bytes,
        "max.partition.fetch.bytes": max_partition_fetch_bytes,
        "fetch.error.backoff.ms": retry_backoff_ms,
        "auto.offset.reset": auto_offset_reset,
        "enable.auto.commit": enable_auto_commit,
        "auto.commit.interval.ms": auto_commit_interval_ms,
        "check.crcs": check_crcs,
        "metadata.max.age.ms": metadata_max_age_ms,
        "partition.assignment.strategy": partition_assignment_strategy,
        "max.poll.interval.ms": max_poll_interval_ms,
        "session.timeout.ms": session_timeout_ms,
        "heartbeat.interval.ms": heartbeat_interval_ms,
        "security.protocol": security_protocol.lower(),
        "connections.max.idle.ms": connections_max_idle_ms,
        "isolation.level": isolation_level,
    } | config.consumer_config

    self.config = config_from_params
    self.consumer = Consumer(self.config, logger=_LazyLoggerProxy(logger))

    # A pool with single thread is used in order to execute the commands of the consumer sequentially:
    # https://github.com/ag2ai/faststream/issues/1904#issuecomment-2506990895
    self._thread_pool = ThreadPoolExecutor(max_workers=1)

admin_client instance-attribute #

admin_client = admin_service

logger_state instance-attribute #

logger_state = logger

topics instance-attribute #

topics = list(topics)

partitions instance-attribute #

partitions = partitions

config instance-attribute #

config = config_from_params

consumer instance-attribute #

consumer = Consumer(
    self.config, logger=_LazyLoggerProxy(logger)
)

topics_to_create property #

topics_to_create: list[Topic]

start async #

start() -> None

Starts the Kafka consumer and subscribes to the specified topics.

Source code in faststream/confluent/helpers/client.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
async def start(self) -> None:
    """Starts the Kafka consumer and subscribes to the specified topics."""
    if self.config.get("allow.auto.create.topics", True):
        topics_creation_result = await run_in_executor(
            self._thread_pool,
            self.admin_client.create_topics,
            self.topics_to_create,
        )

        for create_result in topics_creation_result:
            if create_result.error:
                self.logger_state.log(
                    log_level=logging.WARNING,
                    message=f"Failed to create topic {create_result.topic}: {create_result.error}",
                )

    else:
        self.logger_state.log(
            log_level=logging.WARNING,
            message="Auto create topics is disabled. Make sure the topics exist.",
        )

    if self.topics:
        subscribe_kwargs: dict[str, Any] = {"topics": [t.name for t in self.topics]}
        if self._on_assign is not None:
            subscribe_kwargs["on_assign"] = self._on_assign
        if self._on_revoke is not None:
            subscribe_kwargs["on_revoke"] = self._on_revoke
        if self._on_lost is not None:
            subscribe_kwargs["on_lost"] = self._on_lost
        await run_in_executor(
            self._thread_pool,
            self.consumer.subscribe,
            **subscribe_kwargs,
        )

    elif self.partitions:
        await run_in_executor(
            self._thread_pool,
            self.consumer.assign,
            [p.to_confluent() for p in self.partitions],
        )

    else:
        msg = "You must provide either `topics` or `partitions` option."
        raise SetupError(msg)

commit async #

commit(asynchronous: bool = True) -> None

Commits the offsets of all messages returned by the last poll operation.

Source code in faststream/confluent/helpers/client.py
372
373
374
375
376
377
async def commit(self, asynchronous: bool = True) -> None:
    """Commits the offsets of all messages returned by the last poll operation."""
    await run_in_executor(
        self._thread_pool,
        lambda: self.consumer.commit(asynchronous=asynchronous),  # type: ignore[call-overload]
    )

stop async #

stop() -> None

Stops the Kafka consumer and releases all resources.

Source code in faststream/confluent/helpers/client.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
async def stop(self) -> None:
    """Stops the Kafka consumer and releases all resources."""
    # NOTE: If we don't explicitly call commit and then close the consumer, the confluent consumer gets stuck.
    # We are doing this to avoid the issue.
    enable_auto_commit = self.config.get("enable.auto.commit", True)

    try:
        if enable_auto_commit:
            await self.commit(asynchronous=False)

    except Exception as e:
        # No offset stored issue is not a problem - https://github.com/confluentinc/confluent-kafka-python/issues/295#issuecomment-355907183
        if "No offset stored" in str(e):
            pass
        else:
            self.logger_state.log(
                log_level=logging.ERROR,
                message="Consumer closing error occurred.",
                exc_info=e,
            )

    # Wrap calls to async to make method cancelable by timeout
    # We shouldn't read messages and close consumer concurrently
    # https://github.com/ag2ai/faststream/issues/1904#issuecomment-2506990895
    # Now it works without lock due `ThreadPoolExecutor(max_workers=1)`
    # that makes all calls to consumer sequential
    await run_in_executor(self._thread_pool, self.consumer.close)

    self._thread_pool.shutdown(wait=False)

getone async #

getone(timeout: float = 0.1) -> Message | None

Consumes a single message from Kafka.

Source code in faststream/confluent/helpers/client.py
409
410
411
412
async def getone(self, timeout: float = 0.1) -> Message | None:
    """Consumes a single message from Kafka."""
    msg = await run_in_executor(self._thread_pool, self.consumer.poll, timeout)
    return check_msg_error(msg)

getmany async #

getmany(
    timeout: float = 0.1, max_records: int | None = 10
) -> tuple[Message, ...]

Consumes a batch of messages from Kafka and groups them by topic and partition.

Source code in faststream/confluent/helpers/client.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
async def getmany(
    self,
    timeout: float = 0.1,
    max_records: int | None = 10,
) -> tuple[Message, ...]:
    """Consumes a batch of messages from Kafka and groups them by topic and partition."""
    raw_messages: list[Message | None] = await run_in_executor(
        self._thread_pool,
        cast(
            "Callable[..., list[Message | None]]",
            lambda: self.consumer.consume(
                num_messages=max_records or 10,
                timeout=timeout,
            ),
        ),
    )
    return tuple(x for x in map(check_msg_error, raw_messages) if x is not None)

seek async #

seek(topic: str, partition: int, offset: int) -> None

Seeks to the specified offset in the specified topic and partition.

Source code in faststream/confluent/helpers/client.py
432
433
434
435
436
437
438
439
440
441
442
443
async def seek(self, topic: str, partition: int, offset: int) -> None:
    """Seeks to the specified offset in the specified topic and partition."""
    topic_partition = TopicPartition(
        topic=topic,
        partition=partition,
        offset=offset,
    )
    await run_in_executor(
        self._thread_pool,
        self.consumer.seek,
        topic_partition.to_confluent(),
    )