# Buggy code
def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]:
    try:
        conns = self._conns[key]
    except KeyError:
        return None

    t1 = self._loop.time()
    while conns:
        proto, t0 = conns.pop()
        if proto.is_connected():
            if t1 - t0 > self._keepalive_timeout:
                transport = proto.transport
                proto.close()
                # only for SSL transports
                if key.is_ssl and not self._cleanup_closed_disabled:
                    self._cleanup_closed_transports.append(transport)
            else:
                if not conns:
                    # The very last connection was reclaimed: drop the key
                    del self._conns[key]
                return proto

    # No more connections: drop the key
    del self._conns[key]
    return None


# Traceback (ConnectionResetError)
Traceback (most recent call last):
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/aiohttp/client.py", line 502, in _request
resp = await req.send(conn)
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/aiohttp/client_reqrep.py", line 629, in send
await writer.write_headers(status_line, self.headers)
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/aiohttp/http_writer.py", line 112, in write_headers
self._write(buf)
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/aiohttp/http_writer.py", line 67, in _write
raise ConnectionResetError('Cannot write to closing transport')
ConnectionResetError: Cannot write to closing transport

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/hydra/base_api_request.py", line 75, in request
timeout=cls.request_timeout(timeout))
File "<string>", line 5, in wrapper
File "/home/ubuntu/.pyenv/versions/3.7.2/envs/gateway/lib/python3.7/site-packages/newrelic/hooks/framework_aiohttp.py", line 260, in _coro
response = yield from wrapped(*args, **kwargs)
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/aiohttp/client.py", line 514, in _request
raise ClientOSError(*exc.args) from exc
aiohttp.client_exceptions.ClientOSError: Cannot write to closing transport

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/hydra/decorators/http.py", line 41, in f
result = await wait_for(shield(wrapped_func(self, *args, **kwargs)), api_timeout)
File "/home/ubuntu/.pyenv/versions/3.7.2/lib/python3.7/asyncio/tasks.py", line 416, in wait_for
return fut.result()
File "/home/ubuntu/1mg/API-Gateway/gateway/utils.py", line 189, in wrapper
result = await func(*args, **kwargs)
File "/home/ubuntu/1mg/API-Gateway/gateway/managers/app_context_manager.py", line 98, in _build_shared_context
result = await func(*args, **kwargs)
File "/home/ubuntu/1mg/API-Gateway/gateway/handlers/mingler/service_handler.py", line 14, in services
response = await Services.get_services(params)
File "/home/ubuntu/1mg/API-Gateway/gateway/service_clients/mingler/services.py", line 13, in get_services
result = await cls.post(path, data=params, headers=headers)
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/hydra/base_api_request.py", line 144, in post
response_headers_list=response_headers_list)
File "/home/ubuntu/.pyenv/versions/gateway/lib/python3.7/site-packages/hydra/base_api_request.py", line 93, in request
raise HTTPRequestException(error={'message': exception_message})
hydra.exceptions.HTTPRequestException

# Fixed code
def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]:
    try:
        conns = self._conns[key]
    except KeyError:
        return None

    t1 = self._loop.time()
    while conns:
        proto, t0 = conns.pop()
        if proto.is_connected():
            if t1 - t0 > self._keepalive_timeout:
                transport = proto.transport
                proto.close()
                # only for SSL transports
                if key.is_ssl and not self._cleanup_closed_disabled:
                    self._cleanup_closed_transports.append(transport)
            else:
                if not conns:
                    # The very last connection was reclaimed: drop the key
                    del self._conns[key]
                return proto
        else:
            transport = proto.transport
            proto.close()
            if key.is_ssl and not self._cleanup_closed_disabled:
                self._cleanup_closed_transports.append(transport)

    # No more connections: drop the key
    del self._conns[key]
    return None