# Buggy code
def _process_queue(self):
    def init_buffer():
        buffer = gzip.GzipFile(
            fileobj=compat.BytesIO(), mode="w", compresslevel=self._compress_level
        )
        data = (self._json_serializer({"metadata": self._metadata}) + "\n").encode(
            "utf-8"
        )
        buffer.write(data)
        return buffer

    buffer = init_buffer()
    buffer_written = False

    while True:
        since_last_flush = timeit.default_timer() - self._last_flush
        # take max flush time into account to calculate timeout
        timeout = (
            max(0, self._max_flush_time - since_last_flush)
            if self._max_flush_time
            else None
        )
        timed_out = False
        try:
            event_type, data, flush = self._event_queue.get(block=True, timeout=timeout)
        except compat.queue.Empty:
            event_type, data, flush = None, None, None
            timed_out = True

        if event_type == "close":
            if buffer_written:
                self._flush(buffer)
            self._flushed.set()
            return  # time to go home!

        if data is not None:
            buffer.write(
                (self._json_serializer({event_type: data}) + "\n").encode("utf-8")
            )
            buffer_written = True
            self._counts[event_type] += 1

        queue_size = 0 if buffer.fileobj is None else buffer.fileobj.tell()

        if flush:
            logger.debug("forced flush")
        elif timed_out or timeout == 0:
            # update last flush time, as we might have waited for a non trivial amount of time in
            # _event_queue.get()
            since_last_flush = timeit.default_timer() - self._last_flush
            logger.debug(
                "flushing due to time since last flush %.3fs > max_flush_time %.3fs",
                since_last_flush,
                self._max_flush_time,
            )
            flush = True
        elif self._max_buffer_size and queue_size > self._max_buffer_size:
            logger.debug(
                "flushing since queue size %d bytes > max_queue_size %d bytes",
                queue_size,
                self._max_buffer_size,
            )
            flush = True
        if flush:
            if buffer_written:
                self._flush(buffer)
            self._last_flush = timeit.default_timer()
            buffer = init_buffer()
            buffer_written = False
            self._flushed.set()


# Traceback (urllib3.exceptions.ProtocolError)
web_1      | Failed to submit message: "Unable to reach APM Server: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) (url: http://192.168.16.100:8200/intake/v2/events)"
web_1      | Traceback (most recent call last):
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
web_1      |     chunked=chunked)
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
web_1      |     six.raise_from(e, None)
web_1      |   File "<string>", line 2, in raise_from
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
web_1      |     httplib_response = conn.getresponse()
web_1      |   File "/usr/local/lib/python3.7/site-packages/sentry_sdk/integrations/stdlib.py", line 48, in getresponse
web_1      |     rv = real_getresponse(self, *args, **kwargs)
web_1      |   File "/usr/local/lib/python3.7/http/client.py", line 1321, in getresponse
web_1      |     response.begin()
web_1      |   File "/usr/local/lib/python3.7/http/client.py", line 296, in begin
web_1      |     version, status, reason = self._read_status()
web_1      |   File "/usr/local/lib/python3.7/http/client.py", line 265, in _read_status
web_1      |     raise RemoteDisconnected("Remote end closed connection without"
web_1      | http.client.RemoteDisconnected: Remote end closed connection without response
web_1      |
web_1      | During handling of the above exception, another exception occurred:
web_1      |
web_1      | Traceback (most recent call last):
web_1      |   File "/usr/local/lib/python3.7/site-packages/elasticapm/transport/http.py", line 40, in send
web_1      |     "POST", url, body=data, headers=self._headers, timeout=self._timeout, preload_content=False
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/poolmanager.py", line 323, in urlopen
web_1      |     response = conn.urlopen(method, u.request_uri, **kw)
web_1      |   File "/usr/local/lib/python3.7/site-packages/elasticapm/instrumentation/packages/base.py", line 106, in call_if_sampling
web_1      |     return wrapped(*args, **kwargs)
web_1      |   File "/usr/local/lib/python3.7/site-packages/elasticapm/instrumentation/packages/base.py", line 106, in call_if_sampling
web_1      |     return wrapped(*args, **kwargs)
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 638, in urlopen
web_1      |     _stacktrace=sys.exc_info()[2])
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/util/retry.py", line 367, in increment
web_1      |     raise six.reraise(type(error), error, _stacktrace)
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/packages/six.py", line 685, in reraise
web_1      |     raise value.with_traceback(tb)
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
web_1      |     chunked=chunked)
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
web_1      |     six.raise_from(e, None)
web_1      |   File "<string>", line 2, in raise_from
web_1      |   File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
web_1      |     httplib_response = conn.getresponse()
web_1      |   File "/usr/local/lib/python3.7/site-packages/sentry_sdk/integrations/stdlib.py", line 48, in getresponse
web_1      |     rv = real_getresponse(self, *args, **kwargs)
web_1      |   File "/usr/local/lib/python3.7/http/client.py", line 1321, in getresponse
web_1      |     response.begin()
web_1      |   File "/usr/local/lib/python3.7/http/client.py", line 296, in begin
web_1      |     version, status, reason = self._read_status()
web_1      |   File "/usr/local/lib/python3.7/http/client.py", line 265, in _read_status
web_1      |     raise RemoteDisconnected("Remote end closed connection without"
web_1      | urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
web_1      |
web_1      | During handling of the above exception, another exception occurred:
web_1      |
web_1      | Traceback (most recent call last):
web_1      |   File "/usr/local/lib/python3.7/site-packages/elasticapm/transport/base.py", line 184, in send_sync
web_1      |     self.sync_transport.send(self, data)
web_1      |   File "/usr/local/lib/python3.7/site-packages/elasticapm/transport/http.py", line 53, in send
web_1      |     raise TransportException(message, data, print_trace=print_trace)
web_1      | elasticapm.transport.base.TransportException: Unable to reach APM Server: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) (url: http://192.168.16.100:8200/intake/v2/events)

# Fixed code
def _process_queue(self):
    def init_buffer():
        buffer = gzip.GzipFile(
            fileobj=compat.BytesIO(), mode="w", compresslevel=self._compress_level
        )
        data = (self._json_serializer({"metadata": self._metadata}) + "\n").encode(
            "utf-8"
        )
        buffer.write(data)
        return buffer

    buffer = init_buffer()
    buffer_written = False
    # add some randomness to timeout to avoid stampedes of several workers that are booted at the same time
    max_flush_time = (
        self._max_flush_time * random.uniform(0.9, 1.1)
        if self._max_flush_time
        else None
    )

    while True:
        since_last_flush = timeit.default_timer() - self._last_flush
        # take max flush time into account to calculate timeout
        timeout = max(0, max_flush_time - since_last_flush) if max_flush_time else None
        timed_out = False
        try:
            event_type, data, flush = self._event_queue.get(block=True, timeout=timeout)
        except compat.queue.Empty:
            event_type, data, flush = None, None, None
            timed_out = True

        if event_type == "close":
            if buffer_written:
                self._flush(buffer)
            self._flushed.set()
            return  # time to go home!

        if data is not None:
            buffer.write(
                (self._json_serializer({event_type: data}) + "\n").encode("utf-8")
            )
            buffer_written = True
            self._counts[event_type] += 1

        queue_size = 0 if buffer.fileobj is None else buffer.fileobj.tell()

        if flush:
            logger.debug("forced flush")
        elif timed_out or timeout == 0:
            # update last flush time, as we might have waited for a non trivial amount of time in
            # _event_queue.get()
            since_last_flush = timeit.default_timer() - self._last_flush
            logger.debug(
                "flushing due to time since last flush %.3fs > max_flush_time %.3fs",
                since_last_flush,
                max_flush_time,
            )
            flush = True
        elif self._max_buffer_size and queue_size > self._max_buffer_size:
            logger.debug(
                "flushing since queue size %d bytes > max_queue_size %d bytes",
                queue_size,
                self._max_buffer_size,
            )
            flush = True
        if flush:
            if buffer_written:
                self._flush(buffer)
            self._last_flush = timeit.default_timer()
            buffer = init_buffer()
            buffer_written = False
            max_flush_time = (
                self._max_flush_time * random.uniform(0.9, 1.1)
                if self._max_flush_time
                else None
            )
            self._flushed.set()