Redis

suggest change

Redis is an in-memory data store. It keeps keys and values in RAM, so reads and writes take well under a millisecond. Values can be plain strings, hashes, lists, sets, sorted sets, streams and more. Kotlin backends use Redis for:

This article uses Jedis, the official synchronous Java client. It is simple and works well from Kotlin. Since Jedis 7 the main entry point is RedisClient, a thread-safe client with a built-in connection pool. The older JedisPooled class was removed in Jedis 8.

// build.gradle.kts
dependencies {
    implementation("redis.clients:jedis:8.0.2")
    // only needed for the coroutines example
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}

To try the examples you need a Redis server. The quickest way is Docker:

docker run --rm -p 6379:6379 redis:8

All examples were run against Redis 8.

Connecting and working with strings

RedisClient.create() takes a redis:// URI. The client owns a connection pool, so create one per application, share it between threads, and close it on shutdown. It implements AutoCloseable, so use { } works.

import redis.clients.jedis.RedisClient
import redis.clients.jedis.params.SetParams

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        println("PING -> ${redis.ping()}")

        redis.set("greeting", "Hello, Redis")
        println("greeting = ${redis.get("greeting")}")
        println("missing  = ${redis.get("no-such-key")}")

        // counters are atomic, even with many clients
        redis.del("page:views")
        redis.incr("page:views")
        redis.incrBy("page:views", 10)
        println("views    = ${redis.get("page:views")}")

        // expiration: the key disappears after 60 seconds
        redis.setex("otp:alice", 60, "482913")
        println("ttl      = ${redis.ttl("otp:alice")}s")

        // SET with options: only if not exists (NX), expire in 30 s (EX)
        val first = redis.set("job:lock", "worker-1", SetParams().nx().ex(30))
        val second = redis.set("job:lock", "worker-2", SetParams().nx().ex(30))
        println("lock: first=$first second=$second owner=${redis.get("job:lock")}")

        redis.mset("color:1", "red", "color:2", "green", "color:3", "blue")
        println("mget     = ${redis.mget("color:1", "color:2", "color:4")}")

        println("exists   = ${redis.exists("greeting")}")
        println("deleted  = ${redis.del("greeting", "job:lock", "nope")}")
        println("exists   = ${redis.exists("greeting")}")
    }
}
PING -> PONG
greeting = Hello, Redis
missing  = null
views    = 11
ttl      = 60s
lock: first=OK second=null owner=worker-1
mget     = [red, green, null]
exists   = true
deleted  = 2
exists   = false

Things to notice:

Keys are just strings. The usual convention is type:id[:field], for example user:42 or rate:10.0.0.7:2026. That keeps keys readable and lets you find them by pattern.

Data structures: hashes, lists, sets and sorted sets

Redis values aren't limited to strings. Each type has its own commands, and Jedis maps the replies to Kotlin-friendly types like Map<String, String>, List<String> and Set<String>.

import redis.clients.jedis.RedisClient

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        redis.del("user:1", "queue:emails", "tags:post:1", "tags:post:2", "leaderboard")

        // Hash: a small record of field -> value
        redis.hset("user:1", mapOf("name" to "Alice", "email" to "alice@example.com", "logins" to "0"))
        redis.hincrBy("user:1", "logins", 1)
        println("name   = ${redis.hget("user:1", "name")}")
        println("user:1 = ${redis.hgetAll("user:1").toSortedMap()}")

        // List: a FIFO queue (push on the left, pop on the right)
        redis.lpush("queue:emails", "welcome:alice", "reset:bob", "invoice:carol")
        println("queue  = ${redis.lrange("queue:emails", 0, -1)}")
        println("next   = ${redis.rpop("queue:emails")}")
        println("length = ${redis.llen("queue:emails")}")

        // Set: unique, unordered members
        redis.sadd("tags:post:1", "kotlin", "redis", "jvm")
        redis.sadd("tags:post:2", "kotlin", "coroutines", "kotlin")
        println("tags   = ${redis.smembers("tags:post:2").sorted()}")
        println("common = ${redis.sinter("tags:post:1", "tags:post:2")}")
        println("redis? = ${redis.sismember("tags:post:1", "redis")}")

        // Sorted set: members ordered by score, perfect for leaderboards
        redis.zadd("leaderboard", mapOf("alice" to 120.0, "bob" to 95.0, "carol" to 150.0))
        redis.zincrby("leaderboard", 40.0, "bob")
        for ((i, t) in redis.zrevrangeWithScores("leaderboard", 0, 2).withIndex()) {
            println("#${i + 1} ${t.element} ${t.score.toInt()}")
        }
        println("alice rank = ${redis.zrevrank("leaderboard", "alice")}")
    }
}
name   = Alice
user:1 = {email=alice@example.com, logins=1, name=Alice}
queue  = [invoice:carol, reset:bob, welcome:alice]
next   = welcome:alice
length = 2
tags   = [coroutines, kotlin]
common = [kotlin]
redis? = true
#1 carol 150
#2 bob 135
#3 alice 120
alice rank = 2
Type Use it for Key commands
String cached values, counters, flags GET, SET, INCR, SETEX
Hash records with fields (user, product) HSET, HGET, HGETALL, HINCRBY
List queues, recent items LPUSH, RPOP, LRANGE, BRPOP
Set tags, unique visitors, membership SADD, SISMEMBER, SINTER
Sorted set leaderboards, priority queues, time indexes ZADD, ZINCRBY, ZREVRANGE

Ranks are zero-based, so zrevrank returns 2 for the third place. For a job queue that workers wait on, use brpop(timeoutSeconds, key). It blocks until an item arrives instead of polling in a loop.

Caching objects

The most common use of Redis is the cache-aside pattern: look in Redis first; on a miss, load from the database, store the result with a TTL and return it. When the data changes, delete the cache entry so the next read loads fresh data.

A small data class maps naturally onto a hash. For complex objects you can store a JSON string instead (see JSON).

import redis.clients.jedis.RedisClient
import redis.clients.jedis.UnifiedJedis
import redis.clients.jedis.params.SetParams

data class Product(val id: Int, val name: String, val priceCents: Long)

fun Product.toHash() = mapOf("id" to "$id", "name" to name, "priceCents" to "$priceCents")

fun Map<String, String>.toProduct() =
    Product(getValue("id").toInt(), getValue("name"), getValue("priceCents").toLong())

class ProductRepository(private val redis: UnifiedJedis) {
    var dbQueries = 0
        private set

    // pretend this is a slow SQL query
    private fun loadFromDatabase(id: Int): Product {
        dbQueries++
        Thread.sleep(200)
        return Product(id, "Keyboard #$id", 4999)
    }

    fun find(id: Int): Product {
        val key = "product:$id"
        val cached = redis.hgetAll(key)
        if (cached.isNotEmpty()) return cached.toProduct()

        val product = loadFromDatabase(id)
        redis.hset(key, product.toHash())
        redis.expire(key, 300) // keep it for 5 minutes
        return product
    }

    fun update(product: Product) {
        // ... write to the database first, then drop the stale cache entry
        redis.del("product:${product.id}")
    }
}

// a generic cache-aside helper for string values
fun UnifiedJedis.getOrPut(key: String, ttlSeconds: Long, compute: () -> String): String =
    get(key) ?: compute().also { set(key, it, SetParams().ex(ttlSeconds)) }

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        redis.del("product:7", "report:daily")
        val repo = ProductRepository(redis)

        repeat(3) {
            val p = repo.find(7)
            println("$p, db queries so far: ${repo.dbQueries}")
        }
        repo.update(Product(7, "Keyboard #7", 3999))
        repo.find(7)
        println("database queries: ${repo.dbQueries}")

        val report = redis.getOrPut("report:daily", 3600) { "42 orders, 3 refunds" }
        println("report = $report, ttl = ${redis.ttl("report:daily")}")
    }
}
Product(id=7, name=Keyboard #7, priceCents=4999), db queries so far: 1
Product(id=7, name=Keyboard #7, priceCents=4999), db queries so far: 1
Product(id=7, name=Keyboard #7, priceCents=4999), db queries so far: 1
database queries: 2
report = 42 orders, 3 refunds, ttl = 3600

The first call went to the "database"; the next two came from Redis. After update deleted the key, the next find hit the database again, so there were 2 queries in total.

Always set a TTL on cache entries. Without one, a missed invalidation leaves stale data around forever, and memory keeps growing. For an in-process alternative and more caching strategies see Caching.

Pipelining

Every command is a network round trip. Sending 10,000 commands one by one means waiting 10,000 times. A pipeline sends many commands at once and reads all the replies at the end:

import redis.clients.jedis.RedisClient
import redis.clients.jedis.Response
import kotlin.time.measureTime

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        redis.del("counter")

        val plain = measureTime {
            repeat(10_000) { redis.incr("counter") }
        }

        val pipelined = measureTime {
            redis.pipelined().use { p ->
                repeat(10_000) { p.incr("counter") }
                p.sync() // send everything, read all replies
            }
        }
        println("counter = ${redis.get("counter")}")
        println("one by one: ${plain.inWholeMilliseconds} ms")
        println("pipelined:  ${pipelined.inWholeMilliseconds} ms")

        // Response<T> is a placeholder that is filled in by sync()
        redis.pipelined().use { p ->
            p.set("a", "1")
            val a: Response<String?> = p.get("a")
            val n: Response<Long> = p.incrBy("a", 41)
            p.sync()
            println("a = ${a.get()}, after incrBy = ${n.get()}")
        }
    }
}
counter = 20000
one by one: 1264 ms
pipelined:  49 ms
a = 1, after incrBy = 42

That's about 25 times faster, even with Redis on the same machine. Over a real network the gap is much bigger. Inside a pipeline every command returns a Response<T>. Its value is only available after sync(). Calling get() earlier throws an exception.

A pipeline is not atomic: other clients' commands can run between yours. For that you need a transaction.

Transactions and optimistic locking

multi() starts a MULTI ... EXEC block. The commands are queued and then run as one unit, with no other client's commands in between.

When the transaction depends on a value you read first ("is the balance big enough?"), use WATCH. If a watched key changes before EXEC, Redis aborts the transaction and exec() returns null. Then you can retry or give up.

import redis.clients.jedis.RedisClient

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        redis.mset("account:alice", "100", "account:bob", "50")

        // MULTI/EXEC: all commands run together, no other client can interleave
        redis.multi().use { tx ->
            tx.decrBy("account:alice", 30)
            tx.incrBy("account:bob", 30)
            val results = tx.exec()
            println("exec results = $results")
        }
        println("alice=${redis.get("account:alice")} bob=${redis.get("account:bob")}")

        // Optimistic locking with WATCH: check-then-act safely
        fun transfer(from: String, to: String, amount: Long, beforeExec: () -> Unit = {}): Boolean {
            // transaction(false) gives a dedicated connection without sending MULTI yet
            redis.transaction(false).use { tx ->
                tx.watch(from)
                val balance = redis.get(from).toLong()
                if (balance < amount) {
                    tx.unwatch()
                    return false
                }
                tx.multi()
                tx.decrBy(from, amount)
                tx.incrBy(to, amount)
                beforeExec()
                // exec() returns null if 'from' was changed after WATCH
                return tx.exec() != null
            }
        }

        println("transfer 50: ${transfer("account:alice", "account:bob", 50)}")
        println("transfer 50: ${transfer("account:alice", "account:bob", 50)}")
        // simulate another client depositing money while we are in the middle
        val ok = transfer("account:bob", "account:alice", 10) {
            redis.incrBy("account:bob", 5)
        }
        println("transfer with conflict: $ok")
        println("alice=${redis.get("account:alice")} bob=${redis.get("account:bob")}")
    }
}
exec results = [70, 80]
alice=70 bob=80
transfer 50: true
transfer 50: false
transfer with conflict: false
alice=20 bob=135

Redis transactions don't roll back. If one command fails (for example INCR on a non-number), the others still run. For logic that must be fully atomic, use a Lua script.

Lua scripts and a distributed lock

eval runs a Lua script on the server, atomically. No other command runs while the script runs. A classic use is releasing a lock only if you still own it: "check the value, then delete" must happen in one step, or you could delete a lock that expired and was taken by someone else.

import redis.clients.jedis.RedisClient
import redis.clients.jedis.UnifiedJedis
import redis.clients.jedis.params.SetParams
import java.util.UUID
import kotlin.concurrent.thread

class RedisLock(private val redis: UnifiedJedis, private val name: String) {
    private val key = "lock:$name"
    private val token = UUID.randomUUID().toString()

    fun tryAcquire(ttlMillis: Long): Boolean =
        redis.set(key, token, SetParams().nx().px(ttlMillis)) == "OK"

    // Delete the key only if we still own it. Must be atomic, hence Lua.
    fun release(): Boolean {
        val script = """
            if redis.call('GET', KEYS[1]) == ARGV[1] then
                return redis.call('DEL', KEYS[1])
            end
            return 0
        """.trimIndent()
        return redis.eval(script, listOf(key), listOf(token)) == 1L
    }
}

inline fun <T> UnifiedJedis.withLock(name: String, ttlMillis: Long = 10_000, block: () -> T): T? {
    val lock = RedisLock(this, name)
    if (!lock.tryAcquire(ttlMillis)) return null
    try {
        return block()
    } finally {
        lock.release()
    }
}

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        redis.del("lock:nightly-report")
        val workers = (1..3).map { n ->
            thread {
                val result = redis.withLock("nightly-report") {
                    Thread.sleep(300) // only one worker gets here
                    "report built by worker $n"
                }
                if (result != null) println(result)
            }
        }
        workers.forEach { it.join() }

        val a = RedisLock(redis, "demo")
        val b = RedisLock(redis, "demo")
        println("a acquired: ${a.tryAcquire(5000)}")
        println("b acquired: ${b.tryAcquire(5000)}")
        println("b release:  ${b.release()}") // not the owner, does nothing
        println("a release:  ${a.release()}")
        println("b acquired: ${b.tryAcquire(5000)}")
        b.release()
    }
}
report built by worker 1
a acquired: true
b acquired: false
b release:  false
a release:  true
b acquired: true

Three threads raced for the lock and only one built the report. Which worker wins changes from run to run. The lock has a TTL (px), so a crashed process can't hold it forever. Pick a TTL that is longer than the work takes.

This simple lock is fine for avoiding duplicate work (cron jobs, cache refreshes). It's not a correctness guarantee in every failure scenario, such as a long GC pause that outlives the TTL. When a duplicate would corrupt data, protect the data itself too, for example with a database constraint.

Integer replies from Lua come back as Long. That's why the code compares with 1L.

Pub/Sub

With publish/subscribe, publishers send messages to a channel and every client subscribed at that moment receives them. Messages aren't stored: subscribers that are offline miss them. Use Redis Streams (XADD/XREADGROUP) when you need durability and consumer groups.

subscribe() blocks its thread until all channels are unsubscribed, so run it on a separate thread:

import redis.clients.jedis.JedisPubSub
import redis.clients.jedis.RedisClient
import java.util.concurrent.CountDownLatch
import kotlin.concurrent.thread

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        val ready = CountDownLatch(1)

        val listener = object : JedisPubSub() {
            override fun onSubscribe(channel: String, subscribedChannels: Int) {
                println("subscribed to $channel")
                ready.countDown()
            }

            override fun onMessage(channel: String, message: String) {
                println("[$channel] $message")
                if (message == "bye") unsubscribe()
            }

            override fun onPMessage(pattern: String, channel: String, message: String) {
                println("pattern $pattern matched [$channel] $message")
            }
        }

        // subscribe() blocks the calling thread, so run it on its own thread
        val subscriber = thread(name = "subscriber") {
            redis.subscribe(listener, "chat")
        }
        ready.await()
        listener.psubscribe("orders.*")
        Thread.sleep(100) // give PSUBSCRIBE time to be processed

        val receivers = redis.publish("chat", "hello")
        redis.publish("orders.created", "order 1001")
        redis.publish("news", "nobody listens here")
        redis.publish("chat", "bye")
        Thread.sleep(100)
        listener.punsubscribe()

        subscriber.join()
        println("subscriber finished, first message had $receivers receiver(s)")
    }
}
subscribed to chat
[chat] hello
pattern orders.* matched [orders.created] order 1001
[chat] bye
subscriber finished, first message had 1 receiver(s)

publish returns how many clients received the message. psubscribe subscribes to glob patterns like orders.*. Nobody was subscribed to news, so that message was simply dropped.

Iterating keys with SCAN

KEYS pattern walks the whole keyspace in one blocking call. On a production server with millions of keys it freezes Redis for everyone. Use SCAN instead: it returns keys in small batches using a cursor. A Kotlin sequence turns that into a lazy stream:

import redis.clients.jedis.RedisClient
import redis.clients.jedis.UnifiedJedis
import redis.clients.jedis.params.ScanParams

// Lazily walk all keys matching a pattern, a batch at a time
fun UnifiedJedis.scanKeys(pattern: String, batch: Int = 100): Sequence<String> = sequence {
    val params = ScanParams().match(pattern).count(batch)
    var cursor = ScanParams.SCAN_POINTER_START // "0"
    do {
        val page = scan(cursor, params)
        yieldAll(page.result)
        cursor = page.cursor
    } while (cursor != ScanParams.SCAN_POINTER_START)
}

fun main() {
    RedisClient.create("redis://localhost:6379").use { redis ->
        redis.pipelined().use { p ->
            for (i in 1..1000) p.set("session:$i", "data-$i")
            p.sync()
        }

        val keys = redis.scanKeys("session:*").toList()
        println("found ${keys.size} session keys, e.g. ${keys.sorted().take(3)}")

        // delete them in chunks instead of one giant DEL
        var deleted = 0L
        redis.scanKeys("session:*", batch = 500).chunked(200).forEach { chunk ->
            deleted += redis.del(*chunk.toTypedArray())
        }
        println("deleted $deleted keys")
    }
}
found 1000 session keys, e.g. [session:1, session:10, session:100]
deleted 1000 keys

SCAN may return the same key more than once if the keyspace changes during iteration, and count is a hint, not an exact batch size. Hashes, sets and sorted sets have their own versions: hscan, sscan and zscan.

Using Redis from coroutines

Jedis is a blocking client. In coroutine code (for example a Ktor handler) wrap calls in withContext(Dispatchers.IO) so they don't block the threads of Dispatchers.Default (see Dispatchers and threads). The client's pool gives each concurrent call its own connection.

This example also shows a fixed-window rate limiter, one of the most common Redis patterns:

import kotlinx.coroutines.*
import redis.clients.jedis.RedisClient
import redis.clients.jedis.UnifiedJedis

// Jedis is blocking, so run its calls on Dispatchers.IO
class RateLimiter(private val redis: UnifiedJedis, private val limit: Int, private val windowSeconds: Long) {
    suspend fun allow(clientId: String): Boolean = withContext(Dispatchers.IO) {
        val window = System.currentTimeMillis() / 1000 / windowSeconds
        val key = "rate:$clientId:$window"
        val count = redis.incr(key)
        if (count == 1L) redis.expire(key, windowSeconds)
        count <= limit
    }
}

fun main() = runBlocking {
    RedisClient.create("redis://localhost:6379").use { redis ->
        val limiter = RateLimiter(redis, limit = 5, windowSeconds = 60)

        // 8 concurrent requests from the same client
        val results = (1..8).map { async { limiter.allow("10.0.0.7") } }.awaitAll()
        println("allowed ${results.count { it }}, rejected ${results.count { !it }}")

        // fetch several keys in parallel; the client's pool provides the connections
        val ids = listOf(1, 2, 3)
        withContext(Dispatchers.IO) {
            ids.forEach { redis.set("profile:$it", "user-$it") }
        }
        val profiles = ids.map { id ->
            async(Dispatchers.IO) { redis.get("profile:$id") }
        }.awaitAll()
        println(profiles)
    }
}
allowed 5, rejected 3
[user-1, user-2, user-3]

INCR creates the key with value 1 on the first request in a window. That request also sets the expiry, so old windows clean themselves up. All 8 requests ran concurrently, and because INCR is atomic, exactly 5 were allowed.

If you want a natively non-blocking client, look at Lettuce. It is built on Netty and ships Kotlin coroutine extensions (connection.coroutines()). For most services Jedis on Dispatchers.IO is simpler and fast enough.

Configuration for production

Real deployments need a password, timeouts, sometimes TLS, and a tuned pool. Use RedisClient.builder():

import redis.clients.jedis.ConnectionPoolConfig
import redis.clients.jedis.DefaultJedisClientConfig
import redis.clients.jedis.HostAndPort
import redis.clients.jedis.RedisClient
import java.time.Duration

fun main() {
    val host = System.getenv("REDIS_HOST") ?: "localhost"
    val port = System.getenv("REDIS_PORT")?.toInt() ?: 6379

    val clientConfig = DefaultJedisClientConfig.builder()
        .password(System.getenv("REDIS_PASSWORD")) // null means no AUTH
        .database(0)
        .clientName("orders-service")
        .connectionTimeoutMillis(2_000)
        .socketTimeoutMillis(2_000)
        // .ssl(true) for TLS, e.g. managed Redis in the cloud
        .build()

    val poolConfig = ConnectionPoolConfig().apply {
        maxTotal = 32            // max connections in the pool
        maxIdle = 8
        minIdle = 2
        setMaxWait(Duration.ofSeconds(1)) // fail fast when the pool is exhausted
        testWhileIdle = true
    }

    val redis = RedisClient.builder()
        .hostAndPort(HostAndPort(host, port))
        .clientConfig(clientConfig)
        .poolConfig(poolConfig)
        .build()

    redis.use {
        println(it.ping())
        println(it.info("server").lines().first { line -> line.startsWith("redis_version") })
    }
}
PONG
redis_version:8.10.2

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents