How do I delay all requests at the TCP layer?

Hi I’m trying to simulate latency between my application and my postgres database to test a scenario which may arise and see how my application deals with it.

I decided to use a HAProxy in the middle to insert some kind of a delay in the haproxy.cfg but I am getting stuck.

I tried it locally on the machine using the below config and a simple python based web app and it worked perfectly when I did a curl on localhost

global
 lua-load /etc/haproxy/delay.lua

defaults
 mode http
 timeout connect 10s
 timeout client 10s
 timeout server 10s

frontend fe
 bind 127.0.0.1:8001 name fe
 http-request lua.delay_request
 default_backend be

backend be
 server s 127.0.0.1:80

It loaded the below lua file

function delay_request(txn)
    core.msleep(1000 + math.random(1000))
end

core.register_action("delay_request", { "http-req" }, delay_request);

However then I had to edit the file to get it to connect to my database on port 5432 using TCP and that no longer works.

Below is my current config and it doesnt work either. it gives an error and wont start the service. I’m very new to haproxy so I’m not sure what I am doing wrong

global
#  lua-load /etc/haproxy/delay.lua
  log 127.0.0.1   local1
  maxconn 4096

defaults
  mode tcp
  maxconn 2048
  tcp-request inspect-delay 7000ms
  tcp-request content accept if WAIT_END

frontend postgresDB
  bind *:5000
  mode tcp
  timeout connect 10s
  timeout client 10s
  timeout server 10s
#  http-request lua.delay_request
  default_backend postgresDB

backend postgresDB
  mode tcp
  server pdb 172.18.29.132:5432  check inter 5s rise 2 fall 3

Move the tcp-request from the default section to the frontend section.

Thanks , I tried and it didnt work initially but then I tried after removing mode tcp from default and it works now . thanks