The client implementation for SkyWalking BanyanDB in Java

Clone this repo:
  1. 1e61a22 Add several functionalities to the BanyanDBClient (#49) by Gao Hongtao · 10 hours ago main
  2. 5548fea Add property's ttl (#48) by Gao Hongtao · 7 days ago
  3. 32eae17 Add mod revision check to write requests(measure/stream) (#46) by hailin0 · 7 days ago
  4. cd9c31f Release 0.4.0 (#44) by Jiajing LU · 3 months ago
  5. 649c3f4 Add stream create without timestamp (#43) by Jiajing LU · 3 months ago

BanyanDB Java Client

The client implement for SkyWalking BanyanDB in Java.

GitHub stars Twitter Follow

CI/IT Tests


Create a client

Create a BanyanDBClient with the server's several addresses and then use connect() to establish a connection.

// use `default` group
BanyanDBClient client = new BanyanDBClient("banyandb.svc:17912", "");
// to send any request, a connection to the server must be estabilished

These addresses are either IP addresses or DNS names. If DNS names are used, the client will resolve the DNS name to IP addresses and use them to connect to the server. The client will periodically refresh the IP addresses of the DNS name. The refresh interval can be configured by resolveDNSInterval option.

The client will try to connect to the server in a round-robin manner. The client will periodically refresh the server addresses. The refresh interval can be configured by refreshInterval option.

Besides, you may pass a customized options while building a BanyanDBClient. Supported options are listed below,

maxInboundMessageSizeMax inbound message size1024 * 1024 * 50 (~50MB)
deadlineThreshold of gRPC blocking query, unit is second30 (seconds)
refreshIntervalRefresh interval for the gRPC channel, unit is second30 (seconds)
resolveDNSIntervalDNS resolve interval, unit is second30 (minutes)
forceReconnectionThresholdThreshold of force gRPC reconnection if network issue is encountered1
forceTLSForce use TLS for gRPCfalse
sslTrustCAPathSSL: Trusted CA Path
sslCertChainPathSSL: Cert Chain Path
sslKeyPathSSL: Cert Key Path

Schema Management

Stream and index rules

Then we may define a stream with customized configurations. The following example uses SegmentRecord in SkyWalking OAP as an illustration,

// build a stream default(group)/sw(name) with 2 shards and ttl equals to 30 days
Stream s = Stream.create("default", "sw")
        // set entities
        .setEntityRelativeTags("service_id", "service_instance_id", "is_error")
        // add a tag family "data"
        // add a tag family "searchable"
            // create a string tag "trace_id"
             // service_id is not stored, but can be searched through the index

For the last line in the code block, a simple API (i.e. BanyanDBClient.define(Stream)) is used to define the schema of Stream. The same works for Measure which will be demonstrated later.

Measure and index rules

Measure can also be defined directly with BanyanDBClient,

// create a new measure schema with an additional interval
// the interval is used to specify how frequently to send a data point
Measure m = Measure.create("sw_metric", "service_cpm_minute", Duration.ofHours(1))
        // set entity
        // define a tag family "default"
        // define field specs
        // compressMethod and encodingMethod can be specified
// define a measure, as we've mentioned above

For more APIs usage, refer to test cases and API docs.



Construct a StreamQuery instance with given time-range and other conditions.

Note: time-range is left-inclusive and right-exclusive.

For example,

// [begin, end) = [ now - 15min, now )
Instant end =;
Instant begin = end.minus(15, ChronoUnit.MINUTES);
// with stream schema, group=default, name=sw
StreamQuery query = new StreamQuery("default", "sw",
        new TimestampRange(begin.toEpochMilli(), end.toEpochMilli()),
        // projection tags which are indexed
        ImmutableSet.of("state", "start_time", "duration", "trace_id"));
// search for all states
query.and(PairQueryCondition.LongQueryCondition.eq("searchable", "state" , 0L));
// set order by condition
query.setOrderBy(new StreamQuery.OrderBy("duration", StreamQuery.OrderBy.Type.DESC));
// set projection for un-indexed tags
// send the query request

After response is returned, elements can be fetched,

StreamQueryResponse resp = client.queryStreams(query);
List<RowEntity> entities = resp.getElements();

Every item RowEntity in the list contains elementId, timestamp and tag families requested.

The StreamQueryResponse, RowEntity, TagFamily and Tag (i.e. TagAndValue) forms a hierarchical structure, where the order of the tag families and containing tags, i.e. indexes of these objects in the List, follow the order specified in the projection condition we've used in the request.


For Measure, it is similar to the Stream,

// [begin, end) = [ now - 15min, now )
Instant end =;
Instant begin = end.minus(15, ChronoUnit.MINUTES);
// with stream schema, group=sw_metrics, name=service_instance_cpm_day
MeasureQuery query = new MeasureQuery("sw_metrics", "service_instance_cpm_day",
    new TimestampRange(begin.toEpochMilli(), end.toEpochMilli()),
    ImmutableSet.of("id", "scope", "service_id"),
// query max "total" with group by tag "service_id"
query.maxBy("total", ImmutableSet.of("service_id"));
// use conditions
query.and(PairQueryCondition.StringQueryCondition.eq("default", "service_id", "abc"));
// send the query request

After response is returned, dataPoints can be extracted,

MeasureQueryResponse resp = client.query(query);
List<DataPoint> dataPointList = resp.getDataPoints();

Measure API supports TopN/BottomN search. The results or (grouped-)results are ordered by the given field,

MeasureQuery query = new MeasureQuery("sw_metrics", "service_instance_cpm_day",
        new TimestampRange(begin.toEpochMilli(), end.toEpochMilli()),
        ImmutableSet.of("id", "scope", "service_id"),
query.topN(5, "total"); // bottomN

Besides, limit and offset are used to support pagination. Tag-based sort can also be done to the final results,

query.orderBy("service_id", Sort.DESC);


Both StreamQuery and MeausreQuery support the criteria flag to filter data. criteria supports logical expressions and binary condition operations.

Example of criteria

The expression (a=1 and b = 2) or (a=4 and b=5) could use below operations to support.

                        PairQueryCondition.LongQueryCondition.eq("a", 1L),
                        PairQueryCondition.LongQueryCondition.eq("b", 1L)),
                        PairQueryCondition.LongQueryCondition.eq("a", 4L),
                        PairQueryCondition.LongQueryCondition.eq("b", 5L)

The execution order of conditions is from the inside to outside. The deepest condition will get executed first.

The client also provides syntactic sugar for using and or or methods. The criteria method has a higher priority, overwriting these sugar methods.

Caveat: Sugar methods CAN NOT handle nested query. criteria is the canonical method to take such tasks as above example shows.

Example of and

When filtering data matches all the conditions, the query can append several and:

query.and(PairQueryCondition.LongQueryCondition.eq("state", 1L))
        .and(PairQueryCondition.StringQueryCondition.eq("service_id", serviceId))
        .and(PairQueryCondition.StringQueryCondition.eq("service_instance_id", serviceInstanceId))
        .and(PairQueryCondition.StringQueryCondition.match("endpoint_id", endpointId))
        .and("duration", minDuration))
        .and(PairQueryCondition.LongQueryCondition.le("duration", maxDuration))

Example of or

When gathering all data matches any of the conditions, the query can combine a series of or:

segmentIds.forEach(id -> query.or(PairQueryCondition.LongQueryCondition.eq("segment_id", id)))



Since grpc bidi streaming is used for write protocol, build a StreamBulkWriteProcessor which would handle back-pressure for you. Adjust maxBulkSize, flushInterval and concurrency of the consumer in different scenarios to meet requirements.

// build a StreamBulkWriteProcessor from client
StreamBulkWriteProcessor streamBulkWriteProcessor = client.buildStreamWriteProcessor(maxBulkSize, flushInterval, concurrency);

The StreamBulkWriteProcessor is thread-safe and thus can be used across threads. We highly recommend you to reuse it.

The procedure of constructing StreamWrite entity must comply with the schema of the stream, e.g. the order of tags must exactly be the same with that defined in the schema. And the non-existing tags must be fulfilled (with NullValue) instead of compacting all non-null tag values.

StreamWrite streamWrite = client.createStreamWrite("default", "sw", segmentId, now.toEpochMilli())
    .tag("data_binary", Value.binaryTagValue(byteData))
    .tag("trace_id", Value.stringTagValue(traceId)) // 0
    .tag("state", Value.longTagValue(state)) // 1
    .tag("service_id", Value.stringTagValue(serviceId)) // 2
    .tag("service_instance_id", Value.stringTagValue(serviceInstanceId)) // 3
    .tag("endpoint_id", Value.stringTagValue(endpointId)) // 4
    .tag("duration", Value.longTagValue(latency)) // 5
    .tag("http.method", Value.stringTagValue(null)) // 6
    .tag("status_code", Value.stringTagValue(httpStatusCode)) // 7
    .tag("db.type", Value.stringTagValue(dbType)) // 8
    .tag("db.instance", Value.stringTagValue(dbInstance)) // 9
    .tag("", Value.stringTagValue(broker)) // 10
    .tag("mq.topic", Value.stringTagValue(topic)) // 11
    .tag("mq.queue", Value.stringTagValue(queue)); // 12

CompletableFuture<Void> f = streamBulkWriteProcessor.add(streamWrite);
f.get(10, TimeUnit.SECONDS);


The writing procedure for Measure is similar to the above described process and leverages the bidirectional streaming of gRPC,

// build a MeasureBulkWriteProcessor from client
MeasureBulkWriteProcessor measureBulkWriteProcessor = client.buildMeasureWriteProcessor(maxBulkSize, flushInterval, concurrency);

A BulkWriteProcessor is created by calling buildMeasureWriteProcessor. Then build the MeasureWrite object and send with bulk processor,

Instant now =;
MeasureWrite measureWrite = client.createMeasureWrite("sw_metric", "service_cpm_minute", now.toEpochMilli());
    measureWrite.tag("id", TagAndValue.stringTagValue("1"))
    .tag("entity_id", TagAndValue.stringTagValue("entity_1"))
    .field("total", TagAndValue.longFieldValue(100))
    .field("value", TagAndValue.longFieldValue(1));

CompletableFuture<Void> f = measureBulkWriteProcessor.add(measureWrite);
f.get(10, TimeUnit.SECONDS);

Property APIs

Property APIs are used to store key-value pairs.


apply will always succeed whenever the property exists or not. The old value will be overwritten if already existed, otherwise a new value will be set.

Property property = Property.create("default", "sw", "ui_template")
    .addTag(TagAndValue.newStringTag("name", "hello"))
    .addTag(TagAndValue.newStringTag("state", "successd"))
this.client.apply(property); //created:true tagsNum:2

The operation supports updating partial tags.

Property property = Property.create("default", "sw", "ui_template")
    .addTag(TagAndValue.newStringTag("state", "failed"))
this.client.apply(property); //created:false tagsNum:1

The property supports setting TTL.

Property property = Property.create("default", "sw", "temp_date")
    .addTag(TagAndValue.newStringTag("state", "failed"))
this.client.apply(property); //created:false tagsNum:1 lease_id:1

The property's TTL can be extended by calling Client.keepAliveProperty,

this.client.keepAliveProperty(1); //lease_id:1

The property's live time is reset to 30 minutes.


Property can be queried via Client.findProperty,

Property gotProperty = this.client.findProperty("default", "sw", "ui_template");

The query operation could filter tags,

Property gotProperty = this.client.findProperty("default", "sw", "ui_template", "state");


Property can be deleted by calling Client.deleteProperty,

this.client.deleteProperty("default", "sw", "ui_template"); //deleted:true tagsNum:2

The delete operation could remove specific tags instead of the whole property.

this.client.deleteProperty("default", "sw", "ui_template", "state"); //deleted:true tagsNum:1

Compiling project

./mvnw clean package

Code of conduct

This project adheres to the Contributor Covenant code of conduct. By participating, you are expected to uphold this code. Please follow the REPORTING GUIDELINES to report unacceptable behavior.

Contact Us

  • Mail list: Mail to, follow the reply to subscribe the mail list.
  • Send Request to join SkyWalking slack mail to the mail list(, we will invite you in.
  • Twitter, ASFSkyWalking
  • QQ Group: 901167865(Recommended), 392443393
  • bilibili B站 视频


Apache 2.0 License.