Best strategy to add a Unique-ID header?

Hi,

I have found 2 differents ways to manage a unique ID header.

Firts one, with manually storing the value of uuid() in a transaction variable and adding in the request headers, then adding it back to the response if not already returned by the origin server :

frontend foo
    acl xid_req_exists req.hdr(x-request-id) -m found
    acl xid_res_exists res.hdr(x-request-id) -m found
    http-request set-var(txn.xid) uuid()
    http-request set-header x-request-id %[var(txn.xid)]        unless xid_req_exists
    http-after-response add-header x-request-id %[var(txn.xid)] unless xid_res_exists

Second one, with unique-id-format and unique-id-header :

frontend foo
    unique-id-format %{+X}o\ %ci:%cp_%fi:%fp_%Ts_%rt:%pid
    unique-id-header x-request-id

    acl xid_req_exists req.hdr(x-request-id) -m found
    http-request set-header x-request-id %[unique-id] unless xid_req_exists

    acl xid_res_exists res.hdr(x-request-id) -m found
    http-response set-header x-request-id %[unique-id] unless xid_res_exists

I’m wondering which way is the preferred one, and why.

On a different but related topic, I want to have the unique ID in HAProxy logs.
Should I use a “capture” (to put it automatically in the {} section), or change the log format to add a specific field ?

Thanks

Digging a little more on this, I find that using the “native” feature, make hardr to keep an existing header (either on the request or the response).

The best way seems to be this one :

frontend foo
    acl xid_req_exists req.hdr(x-request-id) -m found
    http-request set-var(txn.xid) req.hdr(x-request-id)  if     xid_req_exists
    http-request set-var(txn.xid) uuid()                 unless xid_req_exists
    http-request capture var(txn.xid) len 64
    http-request set-header x-request-id %[var(txn.xid)] unless xid_req_exists
    
    acl xid_res_exists res.hdr(x-request-id) -m found
    http-after-response set-header x-request-id %[var(txn.xid)] unless xid_res_exists

If HAProxy sees a x-request-id header, it is logged, passed to the origine server and added on the response if not already there.

If there is no x-request-id header, HAProxy uses the uuid() function to create one. Then it is logged, added to the request and added on the response if not already there.

The remaining doubt I have is if is better to use the unique-id-format or not.

1 Like