

# PostgreSQL에서 연결 중단 처리
<a name="Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling"></a>

클라이언트 애플리케이션이 중단되거나 비정상적으로 종료된 경우에도 서버에서 데이터베이스 세션이 활성 상태로 유지될 때 연결 중단이 발생합니다. 이 상황은 일반적으로 클라이언트가 데이터베이스 연결을 제대로 닫거나 진행 중인 요청을 취소하지 않고 충돌을 처리하거나 예기치 않게 종료할 때 발생합니다.

PostgreSQL은 서버 프로세스가 유휴 상태이거나 클라이언트로 데이터를 전송하려고 할 때 연결 중단을 효율적으로 식별하고 정리합니다. 그러나 유휴 상태이거나 클라이언트 입력을 기다리거나 쿼리를 적극적으로 실행하는 세션의 경우 감지가 어렵습니다. 이러한 시나리오를 처리하기 위해 PostgreSQL은 `tcp_keepalives_*`, `tcp_user_timeout` 및 `client_connection_check_interval` 파라미터를 제공합니다.

**Topics**
+ [TCP 킵얼라이브 이해](#Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.Understanding)
+ [RDS for PostgreSQL의 주요 TCP 킵얼라이브 파라미터](#Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.Parameters)
+ [TCP 킵얼라이브 설정 사용 사례](#Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.UseCases)
+ [모범 사례](#Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.BestPractices)

## TCP 킵얼라이브 이해
<a name="Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.Understanding"></a>

TCP 킵얼라이브는 연결 무결성을 유지하고 확인하는 데 도움이 되는 프로토콜 수준 메커니즘입니다. 각 TCP 연결은 킵얼라이브 동작을 제어하는 커널 수준 설정을 유지 관리합니다. 킵얼라이브 타이머가 만료되면 시스템은 다음을 수행합니다.
+ 데이터 및 ACK 플래그 세트가 없는 프로브 패킷을 전송합니다.
+ TCP/IP 사양에 따라 원격 엔드포인트에서 응답을 예상합니다.
+ 응답 또는 응답 없음을 기반으로 연결 상태를 관리합니다.

## RDS for PostgreSQL의 주요 TCP 킵얼라이브 파라미터
<a name="Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.Parameters"></a>


| 파라미터 | 설명 | 기본값 | 
| --- |--- |--- |
| tcp\$1keepalives\$1idle | Specifies number of seconds of inactivity before sending keepalive message. | 300 | 
| tcp\$1keepalives\$1interval | Specifies number of seconds between retransmissions of unacknowledged keepalive messages. | 30 | 
| tcp\$1keepalives\$1count | Maximum lost keepalive messages before declaring connection dead | 2 | 
| tcp\$1user\$1timeout | Specifies how long (in Milliseconds) unacknowledged data can remain before forcibly closing the connection. | 0 | 
| client\$1connection\$1check\$1interval | Sets the interval (in Milliseconds) for checking client connection status during long-running queries. This ensures quicker detection of closed connections. | 0 | 

## TCP 킵얼라이브 설정 사용 사례
<a name="Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.UseCases"></a>

### 유휴 세션 연결 유지
<a name="Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.UseCases.KeepingAlive"></a>

활동이 없어 방화벽 또는 라우터에 의해 유휴 연결이 종료되지 않도록 하는 방법:
+ 정기적으로 킵얼라이브 패킷을 전송하도록 `tcp_keepalives_idle`을 구성합니다.

### 연결 중단 감지
<a name="Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.UseCases.DetectingDead"></a>

연결 중단을 즉시 감지하는 방법:
+ `tcp_keepalives_idle`, `tcp_keepalives_interval` 및 `tcp_keepalives_count`를 조정합니다. 예를 들어 Aurora PostgreSQL 기본값을 사용하면 연결 중단을 감지하는 데 약 1분(프로브 2개 × 30초)이 걸립니다. 이러한 값을 낮추면 감지 속도가 빨라질 수 있습니다.
+ `tcp_user_timeout`을 사용하여 확인의 최대 대기 시간을 지정합니다.

TCP 킵얼라이브 설정은 커널이 연결 중단을 감지하는 데 도움이 되지만 소켓을 사용할 때까지 PostgreSQL이 작동하지 않을 수 있습니다. 세션이 긴 쿼리를 실행하는 경우 쿼리가 완료된 후에야 연결 중단이 감지될 수 있습니다. PostgreSQL 14 이상 버전에서는 `client_connection_check_interval`이 쿼리 실행 중에 소켓을 주기적으로 폴링하여 연결 중단 감지를 가속화할 수 있습니다.

## 모범 사례
<a name="Appendix.PostgreSQL.CommonDBATasks.DeadConnectionHandling.BestPractices"></a>
+ **적절한 킵얼라이브 간격 설정:** `tcp_user_timeout`, `tcp_keepalives_idle`, `tcp_keepalives_count` 및 `tcp_keepalives_interval`을 조정하여 감지 속도와 리소스 사용의 균형을 맞춥니다.
+ **환경에 최적화:** 네트워크 동작, 방화벽 정책 및 세션 요구 사항에 맞게 설정을 조정합니다.
+ **PostgreSQL 기능 활용:** 효율적인 연결 확인을 위해 PostgreSQL 14 이상 버전에서 `client_connection_check_interval`을 사용합니다.