반응형
증상
Go 로 만든 서비스 운영 중 특정 서버에 HTTP Request 를 요청하는 Http Client 서비스를 구현하던 중 Client 객체를 매번 생성하는 방식으로 구현했더니 커널단에서 TIME_WAIT 인 socket이 쌓여 자원 고갈이 되는 증상이 발생
문제점
HTTP Client Request 시 마다 Client 객체를 생성하거나 Client pool 방식을 사용하지 않는 경우 매번 Client 소켓을 생성하고 TCP 생명 주기에 따라 Client 소켓 종료시 TIME_WAIT 상태에서 기다리게 되며 자원이 고갈된다.
조치
검색 결과 Go 의 HTTP Client 는 자체적으로 Client pool 을 제공하기 때문에 다음과 같이 적용하면 최대 connection pool 을 설정할 수 있다.
var defaultClient *http.Client
func init() {
defaultTransportPointer, ok := http.DefaultTransport.(*http.Transport)
if !ok {
panic(fmt.Sprintf("defaultRoundTripper not an *http.Transport"))
}
defaultTransport := *defaultTransportPointer // dereference it to get a copy of the struct that the pointer points to
defaultTransport.MaxIdleConns = 100
defaultTransport.MaxIdleConnsPerHost = 100
defaultClient = &http.Client{Transport: &defaultTransport}
}
// 실제 사용하는 코드에서는 다음과 같이 호출
resp, err := defaultClient.Do(httpReq)
참고 링크
반응형
'개발 노트 > Go' 카테고리의 다른 글
[Golang] go 1.18 Released (generics) (0) | 2022.03.28 |
---|