# Buggy code
def _cleanup(self) -> None:
    """Cleanup unused transports."""
    if self._cleanup_handle:
        self._cleanup_handle.cancel()

    now = self._loop.time()
    timeout = self._keepalive_timeout

    if self._conns:
        connections = {}
        deadline = now - timeout
        for key, conns in self._conns.items():
            alive = []
            for proto, use_time in conns:
                if proto.is_connected():
                    if use_time - deadline < 0:
                        transport = proto.transport
                        proto.close()
                        if key.is_ssl and not self._cleanup_closed_disabled:
                            self._cleanup_closed_transports.append(transport)
                    else:
                        alive.append((proto, use_time))

            if alive:
                connections[key] = alive

        self._conns = connections

    if self._conns:
        self._cleanup_handle = helpers.weakref_handle(
            self, "_cleanup", timeout, self._loop
        )


# 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 _cleanup(self) -> None:
    """Cleanup unused transports."""
    if self._cleanup_handle:
        self._cleanup_handle.cancel()

    now = self._loop.time()
    timeout = self._keepalive_timeout

    if self._conns:
        connections = {}
        deadline = now - timeout
        for key, conns in self._conns.items():
            alive = []
            for proto, use_time in conns:
                if proto.is_connected():
                    if use_time - deadline < 0:
                        transport = proto.transport
                        proto.close()
                        if key.is_ssl and not self._cleanup_closed_disabled:
                            self._cleanup_closed_transports.append(transport)
                    else:
                        alive.append((proto, use_time))
                else:
                    transport = proto.transport
                    proto.close()
                    if key.is_ssl and not self._cleanup_closed_disabled:
                        self._cleanup_closed_transports.append(transport)

            if alive:
                connections[key] = alive

        self._conns = connections

    if self._conns:
        self._cleanup_handle = helpers.weakref_handle(
            self, "_cleanup", timeout, self._loop
        )