Load balancing connection pool with database replication

And what if we want to keep the load balanced hosts in sync? We have several options, like to use some external process to do it, to use PostgreSQL builtin replication capabilities (AFAIK, limited to one-way, two hosts), or we can use the database replication option of DBBalancer.

First at all, we should be very conscient that this option is the most fragile feature of DBBalancer, so it shouldn't be used for anything even minimally serious without extensive testing.

With this in mind, I'll explain you the setup. This mode need two daemons running, and also some modifications to clients, basically that they will have to connect to differents ports to do SELECT statements or to do any other statement. The config file would be like this:

daemon.reader-port=6666
daemon.writer-port=6667
daemon.host=localhost

daemon.init-threads=5
daemon.min-threads=5
daemon.max-threads=30
daemon.init-db-connections=5
daemon.min-db-connections=5
daemon.max-db-connections=30
daemon.reaper-delay=1
daemon.user=daniel
daemon.password=daniel
daemon.auth-method=password

machine.host=localhost
machine.dbname=dbbalancer
machine.port=5432
machine.dbuser=daniel
machine.dbpassword=daniel

machine.host=localhost
machine.dbname=dbbalancer
machine.port=5433
machine.dbuser=daniel
machine.dbpassword=daniel

We can see that it's exactly the same that in the last mode (LoadBalancer). In fact, we'll share the config file between the two daemons. We only have to make sure that the ports for reading and writing are not the same (6666 and 6667 in this example).

This type of configuration consists in two processes. The first process, which will be in charge of SELECTS, should be started with this command ./DBBalancerDaemon -rf test/config_examples/WriteReplicatorExample.conf. The writer process, in charge of modifications, is started with ./DBBalancerDaemon -wf test/config_examples/WriteReplicatorExample.conf. Please note the w flag in the second case, that tells the process to use writer mode.

The drawback of this approach will be that if in the same fragment of client code we need to make read and write operations, we may have to use two connections, one to port 6666 for reads and one to port 6667 for writes. Nothing stops us to issue SELECT sentences to the writer process, it's just that we'll loose some performance, as they will also be replicated to every host. Here we should have to study application by application which is the best configuration. What's absolutely forbidden and would lead to backend lost of synchronicity is to send write (UPDATE, DELETE, INSERT, sequence increasing, ALTER, etc) sentences to a reader DBBalancerProcess that uses more than one host. Nothing within DBBalancer will automatically keep you from doing this, so it's your work to assure the correctness of client code.