Skip to main content

Develop Pulsar Functions

This tutorial walks you through how to develop Pulsar Functions.

Available APIs​

In Java and Python, you have two options to write Pulsar Functions. In Go, you can use Pulsar Functions SDK for Go.

InterfaceDescriptionUse cases
Language-native interfaceNo Pulsar-specific libraries or special dependencies required (only core libraries from Java/Python).Functions that do not require access to the function context.
Pulsar Function SDK for Java/Python/GoPulsar-specific libraries that provide a range of functionality not provided by "native" interfaces.Functions that require access to the function context.

The language-native function, which adds an exclamation point to all incoming strings and publishes the resulting string to a topic, has no external dependencies. The following example is language-native function.


public class JavaNativeExclamationFunction implements Function<String, String> {
@Override
public String apply(String input) {
return String.format("%s!", input);
}
}

For complete code, see here.

The following example uses Pulsar Functions SDK.


public class ExclamationFunction implements Function<String, String> {
@Override
public String process(String input, Context context) {
return String.format("%s!", input);
}
}

For complete code, see here.

Schema registry​

Pulsar has a built in schema registry and comes bundled with a variety of popular schema types(avro, json and protobuf). Pulsar Functions can leverage existing schema information from input topics and derive the input type. The schema registry applies for output topic as well.

SerDe​

SerDe stands for Serialization and Deserialization. Pulsar Functions uses SerDe when publishing data to and consuming data from Pulsar topics. How SerDe works by default depends on the language you use for a particular function.

When you write Pulsar Functions in Java, the following basic Java types are built in and supported by default:

  • String
  • Double
  • Integer
  • Float
  • Long
  • Short
  • Byte

To customize Java types, you need to implement the following interface.


public interface SerDe<T> {
T deserialize(byte[] input);
byte[] serialize(T input);
}

Example​

Imagine that you're writing Pulsar Functions that are processing tweet objects, you can refer to the following example of Tweet class.


public class Tweet {
private String username;
private String tweetContent;

public Tweet(String username, String tweetContent) {
this.username = username;
this.tweetContent = tweetContent;
}

// Standard setters and getters
}

To pass Tweet objects directly between Pulsar Functions, you need to provide a custom SerDe class. In the example below, Tweet objects are basically strings in which the username and tweet content are separated by a |.


package com.example.serde;

import org.apache.pulsar.functions.api.SerDe;

import java.util.regex.Pattern;

public class TweetSerde implements SerDe<Tweet> {
public Tweet deserialize(byte[] input) {
String s = new String(input);
String[] fields = s.split(Pattern.quote("|"));
return new Tweet(fields[0], fields[1]);
}

public byte[] serialize(Tweet input) {
return "%s|%s".format(input.getUsername(), input.getTweetContent()).getBytes();
}
}

To apply this customized SerDe to a particular Pulsar Function, you need to:

  • Package the Tweet and TweetSerde classes into a JAR.
  • Specify a path to the JAR and SerDe class name when deploying the function.

The following is an example of create operation.


$ bin/pulsar-admin functions create \
--jar /path/to/your.jar \
--output-serde-classname com.example.serde.TweetSerde \
# Other function attributes

Custom SerDe classes must be packaged with your function JARs​

Pulsar does not store your custom SerDe classes separately from your Pulsar Functions. So you need to include your SerDe classes in your function JARs. If not, Pulsar returns an error.

In both languages, however, you can write custom SerDe logic for more complex, application-specific types.

Context​

Java, Python and Go SDKs provide access to a context object that can be used by a function. This context object provides a wide variety of information and functionality to the function.

  • The name and ID of a Pulsar Function.
  • The message ID of each message. Each Pulsar message is automatically assigned with an ID.
  • The key, event time, properties and partition key of each message.
  • The name of the topic to which the message is sent.
  • The names of all input topics as well as the output topic associated with the function.
  • The name of the class used for SerDe.
  • The tenant and namespace associated with the function.
  • The ID of the Pulsar Functions instance running the function.
  • The version of the function.
  • The logger object used by the function, which can be used to create function log messages.
  • Access to arbitrary user configuration values supplied via the CLI.
  • An interface for recording metrics.
  • An interface for storing and retrieving state in state storage.
  • A function to publish new messages onto arbitrary topics.
  • A function to ack the message being processed (if auto-ack is disabled).

The Context interface provides a number of methods that you can use to access the function context. The various method signatures for the Context interface are listed as follows.


public interface Context {
Record<?> getCurrentRecord();
Collection<String> getInputTopics();
String getOutputTopic();
String getOutputSchemaType();
String getTenant();
String getNamespace();
String getFunctionName();
String getFunctionId();
String getInstanceId();
String getFunctionVersion();
Logger getLogger();
void incrCounter(String key, long amount);
void incrCounterAsync(String key, long amount);
long getCounter(String key);
long getCounterAsync(String key);
void putState(String key, ByteBuffer value);
void putStateAsync(String key, ByteBuffer value);
void deleteState(String key);
ByteBuffer getState(String key);
ByteBuffer getStateAsync(String key);
Map<String, Object> getUserConfigMap();
Optional<Object> getUserConfigValue(String key);
Object getUserConfigValueOrDefault(String key, Object defaultValue);
void recordMetric(String metricName, double value);
<O> CompletableFuture<Void> publish(String topicName, O object, String schemaOrSerdeClassName);
<O> CompletableFuture<Void> publish(String topicName, O object);
<O> TypedMessageBuilder<O> newOutputMessage(String topicName, Schema<O> schema) throws PulsarClientException;
}

The following example uses several methods available via the Context object.


import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;
import org.slf4j.Logger;

import java.util.stream.Collectors;

public class ContextFunction implements Function<String, Void> {
public Void process(String input, Context context) {
Logger LOG = context.getLogger();
String inputTopics = context.getInputTopics().stream().collect(Collectors.joining(", "));
String functionName = context.getFunctionName();

String logMessage = String.format("A message with a value of \"%s\" has arrived on one of the following topics: %s\n",
input,
inputTopics);

LOG.info(logMessage);

String metricName = String.format("function-%s-messages-received", functionName);
context.recordMetric(metricName, 1);

return null;
}
}

User config​

When you run or update Pulsar Functions created using SDK, you can pass arbitrary key/values to them with the command line with the --userConfig flag. Key/values must be specified as JSON. The following function creation command passes a user configured key/value to a function.


$ bin/pulsar-admin functions create \
--name word-filter \
# Other function configs
--user-config '{"forbidden-word":"rosebud"}'

The Java SDK Context object enables you to access key/value pairs provided to Pulsar Functions via the command line (as JSON). The following example passes a key/value pair.


$ bin/pulsar-admin functions create \
# Other function configs
--user-config '{"word-of-the-day":"verdure"}'

To access that value in a Java function:


import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;
import org.slf4j.Logger;

import java.util.Optional;

public class UserConfigFunction implements Function<String, Void> {
@Override
public void apply(String input, Context context) {
Logger LOG = context.getLogger();
Optional<String> wotd = context.getUserConfigValue("word-of-the-day");
if (wotd.isPresent()) {
LOG.info("The word of the day is {}", wotd);
} else {
LOG.warn("No word of the day provided");
}
return null;
}
}

The UserConfigFunction function will log the string "The word of the day is verdure" every time the function is invoked (which means every time a message arrives). The word-of-the-day user config will be changed only when the function is updated with a new config value via the command line.

You can also access the entire user config map or set a default value in case no value is present:


// Get the whole config map
Map<String, String> allConfigs = context.getUserConfigMap();

// Get value or resort to default
String wotd = context.getUserConfigValueOrDefault("word-of-the-day", "perspicacious");

For all key/value pairs passed to Java functions, both the key and the value are String. To set the value to be a different type, you need to deserialize from the String type.

Logger​

Pulsar Functions that use the Java SDK have access to an SLF4j Logger object that can be used to produce logs at the chosen log level. The following example logs either a WARNING- or INFO-level log based on whether the incoming string contains the word danger.


import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;
import org.slf4j.Logger;

public class LoggingFunction implements Function<String, Void> {
@Override
public void apply(String input, Context context) {
Logger LOG = context.getLogger();
String messageId = new String(context.getMessageId());

if (input.contains("danger")) {
LOG.warn("A warning was received in message {}", messageId);
} else {
LOG.info("Message {} received\nContent: {}", messageId, input);
}

return null;
}
}

If you want your function to produce logs, you need to specify a log topic when creating or running the function. The following is an example.


$ bin/pulsar-admin functions create \
--jar my-functions.jar \
--classname my.package.LoggingFunction \
--log-topic persistent://public/default/logging-function-logs \
# Other function configs

All logs produced by LoggingFunction above can be accessed via the persistent://public/default/logging-function-logs topic.

Metrics​

Pulsar Functions can publish arbitrary metrics to the metrics interface which can be queried.

If a Pulsar Function uses the language-native interface for Java or Python, that function is not able to publish metrics and stats to Pulsar.

You can record metrics using the Context object on a per-key basis. For example, you can set a metric for the process-count key and a different metric for the elevens-count key every time the function processes a message.


import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;

public class MetricRecorderFunction implements Function<Integer, Void> {
@Override
public void apply(Integer input, Context context) {
// Records the metric 1 every time a message arrives
context.recordMetric("hit-count", 1);

// Records the metric only if the arriving number equals 11
if (input == 11) {
context.recordMetric("elevens-count", 1);
}

return null;
}
}

For instructions on reading and using metrics, see the Monitoring guide.

Access metrics​

To access metrics created by Pulsar Functions, refer to Monitoring in Pulsar.

State storage​

Pulsar Functions use Apache BookKeeper as a state storage interface. Pulsar installation, including the local standalone installation, includes deployment of BookKeeper bookies.

Since Pulsar 2.1.0 release, Pulsar integrates with Apache BookKeeper table service to store the State for functions. For example, a WordCount function can store its counters state into BookKeeper table service via Pulsar Functions State API.

States are key-value pairs, where the key is a string and the value is arbitrary binary data - counters are stored as 64-bit big-endian binary values. Keys are scoped to an individual Pulsar Function, and shared between instances of that function.

You can access states within Pulsar Java Functions using the putState, putStateAsync, getState, getStateAsync, incrCounter, incrCounterAsync, getCounter, getCounterAsync and deleteState calls on the context object. You can access states within Pulsar Python Functions using the putState, getState, incrCounter, getCounter and deleteState calls on the context object. You can also manage states using the querystate and putstate options to pulsar-admin functions.

API​

Currently Pulsar Functions expose the following APIs for mutating and accessing State. These APIs are available in the Context object when you are using Java SDK functions.

incrCounter​


/**
* Increment the builtin distributed counter referred by key
* @param key The name of the key
* @param amount The amount to be incremented
*/
void incrCounter(String key, long amount);

The application can use incrCounter to change the counter of a given key by the given amount.

incrCounterAsync​


/**
* Increment the builtin distributed counter referred by key
* but dont wait for the completion of the increment operation
*
* @param key The name of the key
* @param amount The amount to be incremented
*/
CompletableFuture<Void> incrCounterAsync(String key, long amount);

The application can use incrCounterAsync to asynchronously change the counter of a given key by the given amount.

getCounter​


/**
* Retrieve the counter value for the key.
*
* @param key name of the key
* @return the amount of the counter value for this key
*/
long getCounter(String key);

The pplication can use getCounter to retrieve the counter of a given key mutated by incrCounter.

Except the counter API, Pulsar also exposes a general key/value API for functions to store general key/value state.

getCounterAsync​


/**
* Retrieve the counter value for the key, but don't wait
* for the operation to be completed
*
* @param key name of the key
* @return the amount of the counter value for this key
*/
CompletableFuture<Long> getCounterAsync(String key);

The application can use getCounterAsync to asynchronously retrieve the counter of a given key mutated by incrCounterAsync.

putState​


/**
* Update the state value for the key.
*
* @param key name of the key
* @param value state value of the key
*/
void putState(String key, ByteBuffer value);

putStateAsync​


/**
* Update the state value for the key, but don't wait for the operation to be completed
*
* @param key name of the key
* @param value state value of the key
*/
CompletableFuture<Void> putStateAsync(String key, ByteBuffer value);

The application can use putStateAsync to asynchronously update the state of a given key.

getState​


/**
* Retrieve the state value for the key.
*
* @param key name of the key
* @return the state value for the key.
*/
ByteBuffer getState(String key);

getStateAsync​


/**
* Retrieve the state value for the key, but don't wait for the operation to be completed
*
* @param key name of the key
* @return the state value for the key.
*/
CompletableFuture<ByteBuffer> getStateAsync(String key);

The application can use getStateAsync to asynchronously retrieve the state of a given key.

deleteState​


/**
* Delete the state value for the key.
*
* @param key name of the key
*/

Counters and binary values share the same keyspace, so this deletes either type.

Query State​

A Pulsar Function can use the State API for storing state into Pulsar's state storage and retrieving state back from Pulsar's state storage. Additionally Pulsar also provides CLI commands for querying its state.


$ bin/pulsar-admin functions querystate \
--tenant <tenant> \
--namespace <namespace> \
--name <function-name> \
--state-storage-url <bookkeeper-service-url> \
--key <state-key> \
[---watch]

If --watch is specified, the CLI will watch the value of the provided state-key.

Example​

WordCountFunction is a very good example demonstrating on how Application can easily store state in Pulsar Functions.


public class WordCountFunction implements Function<String, Void> {
@Override
public Void process(String input, Context context) throws Exception {
Arrays.asList(input.split("\\.")).forEach(word -> context.incrCounter(word, 1));
return null;
}
}

The logic of this WordCount function is pretty simple and straightforward:

  1. The function first splits the received String into multiple words using regex \\..
  2. For each word, the function increments the corresponding counter by 1 (via incrCounter(key, amount)).