title: HAProxy close front-end connection after N HTTP requests
body: <p>I'm attempting to configure HAProxy to close a client TCP connection after it has been used to process N requests. My goal is to have our long-lived clients occasionally re-establish connections that are otherwise kept-alive by HTTP Keep-Alive.</p>
  
  <p>Basically I'm trying to implement the equivalent of nginx's keepalive_requests (<a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_requests" rel="nofollow noreferrer">http://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_requests</a>).</p>
  
  <p>I currently have something like:</p>
  
  <pre><code>frontend https-in
    bind *:443 ssl crt /etc/ssl/private/cert.pem
  
    stick-table type binary len 32 size 1000 expire 75s store gpc0
  
    acl close_connection sc0_get_gpc0 gt 3
    acl exceeded_connection sc0_get_gpc0 gt 4
  
    http-response set-header Connection Keep-Alive unless close_connection
    http-response set-header Keep-Alive timeout=75\ max=3 unless close_connection
    http-response set-header Connection Close if close_connection
    timeout http-keep-alive 75s
    timeout client 75s
  
    tcp-request content track-sc0 ssl_fc_session_id
    tcp-request content reject if exceeded_connection
  
    http-request sc-inc-gpc0
  
    default_backend https
  
  backend https
    option httpchk GET /health
  
    server localhost 127.0.0.1:8080 maxconn 1000
  </code></pre>
  
  <p>But some problems with this include:</p>
  
  <ul>
  <li>The SSL session ID may be re-used across connections</li>
  <li>This ends abruptly closing a connection from a client when they've exceeded the threshold (assuming they ignore the <code>Connection: Close</code>)</li>
  </ul>
  
  <p>Are there any recommended approaches for something like this? Ideally I would like to:</p>
  
  <ul>
  <li>Track the counter based on individual TCP connection (not <code>src</code> to avoid the case where the same IP has multiple connections established)</li>
  <li>Close the connection on the final response (at the same time I send <code>Connection: Close</code>)</li>
  </ul>
  
  <p>But I haven't been able to track down ways to do either of those.</p>
  
  <p>Thanks!</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I was able to devise a better way to track unique TCP connections by creating hashing a tuple of the src,src_port,dst,dst_port:</p>
  
  <pre><code>  http-request set-header X-Unique-Id %[src]:%[src_port]:%[dst]:%[dst_port]
    http-request set-header X-Unique-Id-SHA %[req.fhdr(X-Unique-Id),sha1]
    http-request track-sc0 req.fhdr(X-Unique-Id-SHA)
  </code></pre>
  
  <p>I'm not crazy about having to create the dummy headers, but this seems to work.</p>