Hey all, I’m the developer for dgraph4j, the Java client for Dgraph. Here’s something to keep in mind when using the client library.
Dgraph clients communicate over GRPC with the Dgraph server. By default, there is no deadline set on the calls made by the client. GRPC deadlines work a bit differently from regular client deadlines, because they also control the timeout value on the server side. So, if the GRPC-specific deadline is not set by the client, the Dgraph server will continue to process the request, even if the client has timed out. This could lead to a wastage of resources.
The GRPC deadlines are set in the Java client using the withDeadlineAfter
method on the DgraphStub
object.
channel = ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
stub.withDeadlineAfter(500, TimeUnit.MILLISECONDS);
DgraphClient dgraphClient = new DgraphClient(stub);
However, there is a problem with the code above. It sets the deadline only once, starting at the point the code above is run. It cannot be used for making multiple calls, each one having a deadline of 500ms before timing out. To fix that, one needs to initialize a ClientInterceptor
that will run on every call and set a fresh deadline.
ClientInterceptor timeoutInterceptor = new ClientInterceptor(){
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return next.newCall(method, callOptions.withDeadlineAfter(500, TimeUnit.MILLISECONDS));
}
};
stub.withInterceptors(timeoutInterceptor);
This functionality could also be extracted out into a reusable class called TimeoutInterceptor
for example, and then used:
stub.withInterceptor(new TimeoutInterceptor(100, TimeUnit.MILLISECONDS));
References: