Set Key in Kafka Topic

I am using the kafka intetgration as demonstrated here. Unfortunately, the kafka integration does not utilize the Key field when sending state changes to kafka. Because the key is not utilized, it is not possible to use the compact strategy in kafka, nor is there any guarantee about order of events.

I would like the entity_id to be sent as the Key. Potentially this could be configurable, but I can’t think of any other field that would be 1) always available or 2) more useful.

By setting the key, the consumer could choose to use the compact strategy for retention policy and they would have some guarantees about message order.

I am not a python developer, but I believe this could be done by changing the last line of this file.

I think this page has the required documentation.

@bachya you are listed as the integration owner for Kafka. Any chance we could get this small change in?

Any feedback is much appreciated!

I have created a PR here Add entity_id as key for kafka message by leosperry · Pull Request #121519 · home-assistant/core (github.com)

While I am not a python developer, I have run all existing tests, followed the code styles of surrounding code, and verified changes work locally with Kafka.

This issue was fixed in 2024.8