TTL on RawKV

Time to Live

We are currently refactoring our documentation. Please excuse any problems you may find and report them here.

This page walks you through a simple demonstration of how to use TTL on RawKV.


Please install TiUP, jshell and download tikv-client jars according to TiKV in 5 Minutes.

Step 1. Config TiKV to enable TTL

TTL is disabled by default. Create a file tikv.yaml using the following content to enable TTL.

enable-ttl = true

Step 2: Start TiKV Cluster

For the purpose of this tutorial, you need only one TiKV node, so use the tiup playground command.

Show TiUP version:

tiup -v

version >= 1.5.0:

tiup playground --mode tikv-slim  --kv.config tikv.yaml

version < 1.5.0:

tiup playground --kv.config tikv.yaml

Step 3: Write the code to test TTL

Let’s write an example to verify that TTL works.

Save the following script to file

import java.util.*;
import org.tikv.common.TiConfiguration;
import org.tikv.common.TiSession;
import org.tikv.raw.RawKVClient;

TiConfiguration conf = TiConfiguration.createRawDefault("");
TiSession session = TiSession.create(conf);
RawKVClient client = session.createRawClient();

// write (k1, v1) with ttl=30 seconds
client.put(ByteString.copyFromUtf8("k1"), ByteString.copyFromUtf8("v1"), 30);

// write (k2, v2) without ttl
client.put(ByteString.copyFromUtf8("k2"), ByteString.copyFromUtf8("v2"));

// get k1 & k2 resturns v1 & v2
System.out.println(client.batchGet(new ArrayList<ByteString>() {{

// sleep 30 seconds
System.out.println("Sleep 30 seconds.")

// get k1 & k2 returns v2
// k1's ttl is expired
System.out.println(client.batchGet(new ArrayList<ByteString>() {{

Step 4: Run the code

jshell --class-path tikv-client-java.jar:slf4j-api.jar --startup

[key: "k1"
value: "v1"
, key: "k2"
value: "v2"
Sleep 30 seconds.
[key: "k2"
value: "v2"

As we can see, k1 is automatically deleted after it’s TTL is expired.