Terminate backend fetch when client disconnects from varnish

82 Views Asked by At

I'm using varnish as a caching layer and I have a question: When a client closes connection to varnish early (before receiving the response) then is it possible to close the backend fetch? So that underlying backend can notice that the connection was closed and stop utilizing resorces when browser aborts the request?

When my page is slowing down and users click on various links or close the page, then my backend has to process all those already-aborted requests, so it slows down even more.

I tried varnish 6.5 and 7.4.2. After I terminate the curl request varnish still waits for the response from backend to potentially cache it, then it increases sc_rem_close metric

1

There are 1 best solutions below

4
VonC On

Varnish HTTP Cache, by default, does not terminate backend requests immediately when a client connection is closed. That behavior is to potentially cache the response for future requests.
But you can customize this behavior by implementing a vcl_backend_response or vcl_backend_error in your VCL (Varnish Configuration Language) file.

sub vcl_backend_response {
    if (bereq.is_bgfetch) {
        // That is a background fetch (client has gone)
        // Implement logic here to handle the scenario
    }
}

bereq.is_bgfetch is true if the backend request is a background fetch, meaning the client has already disconnected.

But is_bgfetch is only related to the grace period mechanism and does not control the actual sending of requests to the backend, so relying on it to stop requests may not be the right approach.

In that case, check if the Adjust SDK offers any server-side control that can stop or modify requests after they are sent. That can be more effective than trying to control it from the client-side.

If not, you may need to implement a client-side solution.
For example, you could manage a flag in your app's state that determines whether or not to send events to Adjust.

if (shouldTrackEvents()) {
  var adjustEvent = new AdjustEvent("xyzabc");
  Adjust.trackEvent(adjustEvent);
  Adjust.updateConversionValue(6);
} else {
  console.log("Tracking is disabled under current conditions.");
}

function shouldTrackEvents() {
  // Your logic to determine whether to track events or not
  return true; // or false based on certain conditions
}