I am trying to configure Haproxy to balance between postgres replicas. The main task: the request should be redirected to the node with the most current data. Check data relevance runs on master_node:
select client_addr AS client, (pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn))::int / 1024 as total_lag from pg_stat_replication;
With this command, I get a list of hosts and replication_lag. For example:
111.111.111.111 | 152
222.222.222.222 | 9
333.333.333.333 | 4700
I need a host with a minimum value. I do not understand three things:
I applied these settings: haproxy.cfg
lua-load /etc/haproxy/scripts/choosebackend.lua
frontend psql-front
bind *:5432
mode tcp
use_backend %[lua.choose_backend]
backend backend1
mode tcp
balance roundrobin
server pg1 111.111.111.111:5432 check port 5432
backend backend2
mode tcp
balance roundrobin
server pg2 222.222.222.222:5432 check port 5432
choosebackend.lua
luasql = require "luasql.postgres"
env = luasql.postgres()
con = assert (env:connect('postgres', 'postgres', 'postgres','333.333.333.333','5432')) --master
backend = function(txn)
res = assert (con:execute('select client_addr from pg_stat_replication order by replay_lag asc limit 1'))
row = res:fetch ({}, "a")
while row do
ip = string.format("%-12s", row.client_addr)
row = res:fetch (row, "a")
end
result = "backend1"
if ip == '111.111.111.111' then
result = "backend1"
elseif ip == '222.222.222.222' then
result = "backend2"
end
return result
end
core.register_fetches("choose_backend", backend)
Haproxy must be compiled from source, because by default LUA support is disabled in it. Additionally, you need to install luarocks and luasql-postgres