You don’t need to close the producer after sending each message. You can close if when you no longer need to send any messages. By default, the producer sends messages asynchronously. So you’ll sometimes encounter delays in receiving messages. To overcome this, you can call the .get() method, something like this:
producer.send(new ProducerRecord<>(topic, payload)).get();
This will immediately send messages to the topic, synchronously. Please try this once. But because this doesn’t delegate the work to a background thread, this will be slower, as it is a blocking operation (if I’m not wrong and remember it properly). Please correct me if I’m wrong.