Redis is an open-source NoSQL database working on a key/value model. One interesting feature in Redis is that it is able to write data to disk as well as a master can synchronize many slaves.

HAProxy can load-balance Redis servers with no issues at all. There is even a built-in health check for Redis in HAProxy. Unfortunately, there was no easy way for HAProxy to detect the status of a Redis server: master or slave node. Hence people usually hack this part of the architecture.

As written in the title of this post, we’ll learn today how to make a simple Redis infrastructure thanks to the newest HAProxy advanced send/expect health checks.
This feature is available in HAProxy 1.5-dev20 and above.

The purpose is to make the Redis infrastructure as simple as possible and ease failover for the web servers. HAProxy will have to detect which node is MASTER and route all the connections to it.

Redis High Availability Diagram with HAProxy

Below, is an ASCII art diagram of HAProxy load-balancing Redis servers:

+----+ +----+ +----+ +----+
| W1 | | W2 | | W3 | | W4 |   Web application servers
+----+ +----+ +----+ +----+
          |   |     /
          |   |    /
          |   |   /
        +---------+
        | HAProxy |
        +---------+
           /   
       +----+ +----+
       | R1 | | R2 |           Redis servers
       +----+ +----+

The scenario is simple:

  • 4 web application servers need to store and retrieve data to/from a Redis database

  • one (better using 2) HAProxy servers that load-balance Redis connections

  • 2 (at least) Redis servers in an active/standby mode with replication

Configuration

Below, is the HAProxy configuration for the

defaults REDIS
 mode tcp
 timeout connect  4s
 timeout server  30s
 timeout client  30s
frontend ft_redis
 bind 10.0.0.1:6379 name redis
 default_backend bk_redis
backend bk_redis
 option tcp-check
 tcp-check send PING\r\n
 tcp-check expect string +PONG
 tcp-check send info replication\r\n
 tcp-check expect string role:master
 tcp-check send QUIT\r\n
 tcp-check expect string +OK
 server R1 10.0.0.11:6379 check inter 1s
 server R2 10.0.0.12:6379 check inter 1s

The HAProxy health check sequence above allows us to consider the Redis master server as UP in the farm and redirect connections to it.
When the Redis master server fails, the remaining nodes elect a new one. HAProxy will detect it thanks to its health check sequence.

It does not require third-party tools and makes failover transparent.

Subscribe to our blog. Get the latest release updates, tutorials, and deep-dives from HAProxy experts.