From bf5788d41b8d81ee894d73552978c4a72f16ad43 Mon Sep 17 00:00:00 2001 From: Paul Kuruvilla Date: Wed, 10 Jan 2018 14:39:55 +0530 Subject: [PATCH] Reuse TCP connections --- lib/segment/analytics/request.rb | 5 +++++ lib/segment/analytics/worker.rb | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/segment/analytics/request.rb b/lib/segment/analytics/request.rb index d077a3a..fa3e299 100644 --- a/lib/segment/analytics/request.rb +++ b/lib/segment/analytics/request.rb @@ -112,6 +112,11 @@ def send_request(write_key, batch) [200, '{}'] else + # If `start` is not called, Ruby adds a 'Connection: close' header + # too all requests, preventing us from reusing a connection for multiple + # HTTP requests + @http.start unless @http.started? + response = @http.request(request, payload) [response.code.to_i, response.body] end diff --git a/lib/segment/analytics/worker.rb b/lib/segment/analytics/worker.rb index f619a1b..646c5e8 100644 --- a/lib/segment/analytics/worker.rb +++ b/lib/segment/analytics/worker.rb @@ -28,6 +28,7 @@ def initialize(queue, write_key, options = {}) @on_error = options[:on_error] || proc { |status, error| } @batch = [] @lock = Mutex.new + @request = Request.new end # public: Continuously runs the loop to check for new events @@ -42,8 +43,7 @@ def run end end - res = Request.new.post @write_key, @batch - + res = @request.post(@write_key, @batch) @on_error.call(res.status, res.error) unless res.status == 200 @lock.synchronize { @batch.clear }