Skip to main content
Version: 3.0.x

Work with producer

After setting up your clients, you can explore more to start working with producers.

Create the producer

This example shows how to create a producer.

Producer<String> producer = pulsarClient.newProducer(Schema.STRING)

Send messages

This example shows how to send messages using producers.


You can terminate the builder chain with sendAsync() and get a future return.

Send messages with customized metadata

  • Send messages with customized metadata by using the builder.

    var messageId = await producer.NewMessage()
    .Property("SomeKey", "SomeValue")

Async send messages

You can publish messages asynchronously using the Java client. With async send, the producer puts the message in a blocking queue and returns it immediately. Then the client library sends the message to the broker in the background. If the queue is full (max size configurable), the producer is blocked or fails immediately when calling the API, depending on arguments passed to the producer.

The following is an example.

producer.sendAsync("my-async-message".getBytes()).thenAccept(msgId -> {
System.out.println("Message with ID " + msgId + " successfully sent");

As you can see from the example above, async send operations return a MessageId wrapped in a CompletableFuture.

Publish messages to partitioned topics

By default, Pulsar topics are served by a single broker, which limits the maximum throughput of a topic. Partitioned topics can span multiple brokers and thus allow for higher throughput.

You can publish messages to partitioned topics using Pulsar client libraries. When publishing messages to partitioned topics, you must specify a routing mode. If you do not specify any routing mode when you create a new producer, the round-robin routing mode is used.

Use built-in message router

You can specify the routing mode in the ProducerConfiguration object to configure your producer. The routing mode determines which partition (internal topic) each message should be published to.

The following is an example:

String pulsarBrokerRootUrl = "pulsar://localhost:6650";
String topic = "persistent://my-tenant/my-namespace/my-topic";

PulsarClient pulsarClient = PulsarClient.builder().serviceUrl(pulsarBrokerRootUrl).build();
Producer<byte[]> producer = pulsarClient.newProducer()
producer.send("Partitioned topic message".getBytes());

Customize message router

To use a custom message router, you need to provide an implementation of the MessageRouter interface, which has just one choosePartition method:

public interface MessageRouter extends Serializable {
int choosePartition(Message msg);

The following router routes every message to partition 10:

public class AlwaysTenRouter implements MessageRouter {
public int choosePartition(Message msg) {
return 10;

With that implementation, you can send messages to partitioned topics as below.

String pulsarBrokerRootUrl = "pulsar://localhost:6650";
String topic = "persistent://my-tenant/my-cluster-my-namespace/my-topic";

PulsarClient pulsarClient = PulsarClient.builder().serviceUrl(pulsarBrokerRootUrl).build();
Producer<byte[]> producer = pulsarClient.newProducer()
.messageRouter(new AlwaysTenRouter())
producer.send("Partitioned topic message".getBytes());

Choose partitions when using a key

If a message has a key, it supersedes the round robin routing policy. The following java example code illustrates how to choose the partition when using a key.

// If the message has a key, it supersedes the round robin routing policy
if (msg.hasKey()) {
return signSafeMod(hash.makeHash(msg.getKey()), topicMetadata.numPartitions());

if (isBatchingEnabled) { // if batching is enabled, choose partition on `partitionSwitchMs` boundary.
long currentMs = clock.millis();
return signSafeMod(currentMs / partitionSwitchMs + startPtnIdx, topicMetadata.numPartitions());
} else {
return signSafeMod(PARTITION_INDEX_UPDATER.getAndIncrement(this), topicMetadata.numPartitions());

Enable chunking

Message chunking enables Pulsar to process large payload messages by splitting the message into chunks at the producer side and aggregating chunked messages on the consumer side.

The message chunking feature is OFF by default. The following is an example of how to enable message chunking when creating a producer.

  Producer<byte[]> producer = client.newProducer()

By default, producer chunks the large message based on max message size (maxMessageSize) configured at broker (eg: 5MB). However, client can also configure max chunked size using producer configuration chunkMaxMessageSize.


To enable chunking, you need to disable batching (enableBatching=false) concurrently.

Configure delayed message delivery

The following is an example of how to configure delayed message delivery for a producer.

// message to be delivered at the configured delay interval
producer.newMessage().deliverAfter(3L, TimeUnit.Minute).value("Hello Pulsar!").send();

Intercept messages

ProducerInterceptor intercepts and possibly mutates messages received by the producer before they are published to the brokers.

The interface has three main events:

  • eligible checks if the interceptor can be applied to the message.
  • beforeSend is triggered before the producer sends the message to the broker. You can modify messages within this event.
  • onSendAcknowledgement is triggered when the message is acknowledged by the broker or the sending failed.

To intercept messages, you can add a ProducerInterceptor or multiple ones when creating a Producer as follows.

Producer<byte[]> producer = client.newProducer()
.intercept(new ProducerInterceptor {
boolean eligible(Message message) {
return true; // process all messages

Message beforeSend(Producer producer, Message message) {
// user-defined processing logic

void onSendAcknowledgement(Producer producer, Message message, MessageId msgId, Throwable exception) {
// user-defined processing logic

Multiple interceptors apply in the order they are passed to the intercept method.

Configure encryption policies

The Pulsar C# client supports four kinds of encryption policies:

  • EnforceUnencrypted: always use unencrypted connections.
  • EnforceEncrypted: always use encrypted connections)
  • PreferUnencrypted: use unencrypted connections, if possible.
  • PreferEncrypted: use encrypted connections, if possible.

This example shows how to set the EnforceUnencrypted encryption policy.

using DotPulsar;

var client = PulsarClient.Builder()

Configure access mode

Access mode allows applications to require exclusive producer access on a topic to achieve a "single-writer" situation.

This example shows how to set producer access mode.


This feature is supported in Java client 2.8.0 or later versions.

Producer<byte[]> producer = client.newProducer()