Haproxy Balancing. How to find the minimum value in a haproxy checker?

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:

  1. How do I pass a replica name to a custom haproxy_checker?
  2. How do I compare the values ​​obtained?
  3. How to specify haproxy based on the given values ​​to which of the replicas to switch requests to?

This is not up to HAProxy to do this. You should have a third party monitoring your postgres and then pushing configuration changes accordingly.
You can use the runtime API or the dataplane API for performing those changes.