AIOProducer.produce execution order and flush() best practices for batching
Hi everyone, I am using the new confluent_kafka.aio.AIOProducer and trying to find the most efficient way to batch-produce around 1,800 messages at once.
- OS: Debian 13.3
- Python version: 3.12
- confluent-kafka version: 2.14.2
- Kafka Broker: locally via Docker Compose
Looking at the official example provided in the documentation:
import asyncio
async def batch_produce(producer, topic):
# Create multiple produce futures
futures = [
await producer.produce(topic=topic, key=f'key{i}', value=f'value{i}')
for i in range(100)
]
# Flush to ensure messages are in flight
await producer.flush()
# Wait for all deliveries
messages = await asyncio.gather(*futures)
print(f'Delivered {len(messages)} messages')
asyncio.run(batch_produce())
I implemented a similar approach in my production code to collect and send financial contracts.
class KafkaProducer:
def __init__(self, bootstrap_servers: str):
self._producer = AIOProducer({
"bootstrap.servers": bootstrap_servers,
"acks": 1,
"client.id": "producer-1",
"linger.ms": 30,
"batch.num.messages": 2000,
"compression.type": "lz4"
})
async def produce_message(self, topic: str, encoded_payload: bytes, key: str | None = None) -> asyncio.Future:
encoded_key = key.encode("utf-8") if key else None
return await self._producer.produce(
topic=topic,
key=encoded_key,
value=encoded_payload
)
async def flush(self):
await self._producer.flush()
async def close(self):
await self._producer.flush()
await self._producer.close()
logger.info("[Kafka] AIOProducer closed.")
class ContractCollector:
def __init__(self, name: str, contract_provider: ContractProvider, kafka_config: KafkaConfig, kafka_producer: KafkaProducer):
self._name = name
self._contract_provider = contract_provider
self._kafka_topic = kafka_config.kafka_contracts_topic
self._kafka_producer = kafka_producer
async def collect(self) -> list[Contract]:
contracts = await self._contract_provider.get_contracts()
logger.info(f"[{self._name}] Collected {len(contracts)} contracts.")
delivery_futures = []
for contract in contracts:
key = f"{contract.cex_id.id}_{contract.chain_id.id}_{contract.symbol}"
encoded_payload = contract.model_dump_json().encode('utf-8')
future = await self._kafka_producer.produce_message(
topic=self._kafka_topic,
key=key,
encoded_payload=encoded_payload,
)
delivery_futures.append(future)
# await self._kafka_producer.flush()
messages = await asyncio.gather(*delivery_futures)
logger.info(f'Delivered {len(messages)} messages')
return contracts
I have two questions regarding performance and best practices here:
1. Is await producer.produce() inside a loop blocking concurrent execution?
Since produce is an async def method, using await inside the list comprehension (or a for loop) sequentially waits for each message registration.
- If we await it inside the loop, doesn't it defeat the purpose of asyncio.gather(*futures) later?
- Should we instead use asyncio.gather(*[producer.produce(...) for ...]) to schedule all internal queue enqueueing concurrently, and then get the delivery futures also using asyncio.gather(*delivery_futures)?
2. Is explicit await producer.flush() a good practice before asyncio.gather(*futures)?
I noticed a massive difference in behavior when benchmarking ~1,800 messages:
- Without flush(): Iterating and getting futures takes 15–30 ms, but awaiting asyncio.gather(*delivery_futures) blocks for 2.0–2.5 seconds before resolving.
- With flush(): The total execution time drops significantly.
Is calling flush() explicitly the recommended way to force the underlying C-library to trigger queue polling and network delivery immediately in batch scenarios, or is it considered an anti-pattern for high-throughput async pipelines?
Thank you for your help!
Hi, I am really interested in your second question, too! Let's hope we will get a reply soon :)
I hit the same thing and traced it in the source. Short version: awaiting delivery futures without flush() can wait until traffic pauses, because the timeout that drains AIOProducer's buffer measures inactivity rather than message age.
Repro (single-node Kafka in Docker; confluent-kafka 2.16.1, librdkafka 2.16.0, Python 3.12): https://gist.github.com/kethoo/5c29abbba5d16d5b9d9bcd4ba957bca0
| Scenario | median | max |
|---|---|---|
| 1 message, await the future only | 2006 ms | 2006 ms |
1 message, flush() then the future |
19 ms | 19 ms |
| 1 msg every 200 ms for 6 s, await futures only | 5105 ms | 8020 ms |
same, flush() after each produce |
6 ms | 24 ms |
plain Producer + background poll() thread |
10 ms | 24 ms |
What happens (v2.16.1, unchanged on master):
- Every
produce()callsmark_activity()(aio/producer/_AIOProducer.py:215), andBufferTimeoutManagerdrains the buffer only whentime.time() - _last_activity >= timeout(_buffer_timeout_manager.py:117-118). With messages arriving faster thanbuffer_timeout(default 1.0 s) and fewer thanbatch_size(default 1000) buffered, the buffer is not sent until traffic pauses. - After a drain, delivery reports are served once, by
poll(0)(_kafka_batch_executor.py:93) and a non-blockingflush(0)(_buffer_timeout_manager.py:143), before the broker can have acked. So the ack is only seen on a later timeout check, which is why a single message takes ~2 s.
That also explains your numbers: with ~1,800 messages, the first 1,000 go out when batch_size is reached, and the remaining 800 wait for the ~1 s timeout plus ~1 s to see the acks. On your first question: produce() only awaits when the buffer reaches batch_size; otherwise it returns the future right away, so awaiting it in a loop doesn't serialize delivery. On the second: with the current code, flush() (or a full batch) is what bounds latency. Note that flush() waits for every outstanding message in the producer, not just yours.
Maintainers, would you take a PR that makes the timeout age-based (drain once the oldest buffered message is buffer_timeout old, like librdkafka's linger.ms), with tests in tests/test_buffer_timeout_manager.py? I could also document buffer_timeout/batch_size either way.