Video in progress

Strong Middle ⚡ Redis and caching

If you route reads to replicas in Lettuce (`ReadFrom.REPLICA_PREFERRED`), what problems do you run into?

Because replication is asynchronous, a replica lags by a few milliseconds, sometimes seconds. As a result read-your-writes breaks: a user doesn't see what they just wrote, and reading locks and counters from a replica leads to wrong decisions.

📖 Answer

Turning it on in Spring Boot is easy:

@Bean
LettuceClientConfigurationBuilderCustomizer readFromReplica() {
    return builder -> builder.readFrom(ReadFrom.REPLICA_PREFERRED);
}

This works with Sentinel, Cluster and a static master/replica setup. After that, all reads that go through this RedisConnectionFactory go to the replica. The problem is exactly in that "all".

Typical mistakes:

  • the user changed their profile and the page refreshed, still showing the old name. The write is on the master, the read is from a lagging replica;
  • the rate limiter does INCR on the master but checks the limit with GET from a replica, so under load it goes over the limit;
  • checking whether a lock exists from a replica is completely wrong;
  • during a replica's full sync, with replica-serve-stale-data yes (the default), it returns stale data.

What I do: I give replica reads only to places that can tolerate a stale answer, such as a catalog, statistics, reports. For that I make two separate RedisTemplate beans (one for the master, one for the replica) and make it explicit in the code which one is used where.

To watch the lag, compare the master's master_repl_offset with the replica's offset in INFO replication.