SQLAlchemy QueuePool 에러 해결하기 (sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00)

2025. 3. 20. 15:49·Minding's Programming/에러 코드
728x90
반응형

외주 프로젝트 중 백엔드 서버로부터 SQLAlchemy TimeoutError가 지속적으로 발견되는 것을 확인했다. 에러 코드를 읽어보면, QueuePool의 limit이 5(overflow 허용치는 10)인데, 한계값에 도달했으며, timeout 30초에 도달하여 연결이 끊겼다는 설명이다.

 

이 경우 원인은 크게 2가지일 수 있다.

1. 비동기 처리 코드 처리 중 DB 트랜잭션이 열린 채로 방지되어 커넥션이 해제되지 않는 경우

2. SQLAlchemy의 커넥션 풀 크기가 너무 작게 설정되어 있는 경우

 

위 2가지 원인에 대한 해결 방법을 찾아보니, 아래와 같은 결과가 나왔다.

 

1. 비동기 처리 코드 처리 중 DB 트랜잭션이 열린 채로 방지되어 커넥션이 해제되지 않는 경우

# 이전 코드
async def get_db():
    db = database.AsyncSessionLocal()

# DB 세션 의존성 수정
async def get_db():
    db = database.AsyncSessionLocal()
    try:
        yield db
    finally:
        await db.close()

수정 전의 코드는 db를 호출하기만 한 뒤, 아무 동작도 하지 않아 DB 트랜잭션이 열린 채로 유지되었다. 결국 API 호출이 쌓이다 보면 위와 같은 에러가 발생할 수밖에 없다.

코드에 try-finally를 추가해 DB 세션을 전달(try)한 뒤, 동작이 종료되면 db.close()가 되도록 설정했다.

 

2. SQLAlchemy의 커넥션 풀 크기가 너무 작게 설정되어 있는 경우

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "{DB_URL}"

# 비동기 엔진 생성
engine = create_async_engine(
    DATABASE_URL,
    echo=True,
    pool_size=20,
    max_overflow=30,
    pool_timeout=60,
    pool_recycle=1800,
)

# 비동기 세션 설정
AsyncSessionLocal = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
)

Base = declarative_base()

위 코드는 DB 엔진을 연결하는 비동기 세션을 만드는 코드다. 위 비동기 엔진(engine)을 선언할 때, pool_size, max_overflow, pool_timeout, pool_recycle 등의 파라미터를 활용해 세부 항목을 설정할 수 있다. 각 파라미터의 의미는 아래와 같다.

 

  • pool_size: 기본적으로 유지할 커넥션 개수(기본값: 5)
  • max_overflow: 추가로 허용할 커넥션 개수(기본값: 10)
  • pool_timeout: 커넥션을 기다릴 최대 시간(초 / 기본값: 30초)
  • pool_recycle: 커넥션을 재사용 가능하도록 설정할 시간(초)
728x90

'Minding's Programming > 에러 코드' 카테고리의 다른 글

[Python/FastAPI/ODMantic] TypeError: field Config is defined without type annotation  (0) 2024.06.19
Python 프로그래밍 중 가장 많이 발생하는 5가지 에러코드 정리  (0) 2023.08.08
ModuleNotFoundError: No module named 'sklearn.utils.linear_assignment_'  (0) 2021.04.01
[에러코드/DeepSort] KeyError: "The name 'net/images:0' refers to a Tensor which does not exist. The operation, 'net/images', does not exist in the graph."  (0) 2021.04.01
AttributeError: module 'tensorflow' has no attribute 'gfile'  (0) 2021.04.01
'Minding's Programming/에러 코드' 카테고리의 다른 글
  • [Python/FastAPI/ODMantic] TypeError: field Config is defined without type annotation
  • Python 프로그래밍 중 가장 많이 발생하는 5가지 에러코드 정리
  • ModuleNotFoundError: No module named 'sklearn.utils.linear_assignment_'
  • [에러코드/DeepSort] KeyError: "The name 'net/images:0' refers to a Tensor which does not exist. The operation, 'net/images', does not exist in the graph."
Minding
Minding
  • Minding
    Today's Minding
    Minding
  • 전체
    오늘
    어제
    • 울고넘는 딥러닝 (278)
      • Minding's Baseball (57)
        • MLB Statcast (29)
        • 머신러닝으로 홈런왕 예측하기 (3)
        • 야구칼럼 (12)
        • 야구 규칙, 용어 (1)
        • 2022-23 질롱 코리아 (8)
        • 류현진 등판경기 (4)
      • Minding's Programming (185)
        • 프로그래머스 코딩테스트 (21)
        • Knowledge (44)
        • Numpy & Pandas (6)
        • Excel (3)
        • Git (1)
        • Pygame (11)
        • CV (3)
        • Tensorflow tutorial (4)
        • Kaggle and Dacon (4)
        • 에러 코드 (8)
        • FastAPI (8)
        • Airflow (29)
        • Crawling (6)
        • Django (14)
        • AWS (18)
        • Spark (5)
      • Minding's Reading (30)
        • 머신러닝 딥러닝에 필요한 기초 수학 with 파이.. (2)
        • 칼만필터는 어렵지 않아 (11)
        • 밑바닥부터 시작하는 딥러닝 (6)
        • 메이저리그 야구 통계학 2e (8)
        • 논문읽기 (2)
        • 빅데이터를 지탱하는 기술 (1)
      • Minding's Life (5)
        • 주식 (4)
        • 각종 소식 (1)
  • 블로그 메뉴

    • 홈
    • Baseball
    • Programming
    • Reading
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    게임개발
    mlb stats api
    메이저리그
    pygame
    칼만필터
    MLB
    KBO
    django python
    코딩테스트
    야구
    FastAPI
    딥러닝
    칼만필터는어렵지않아
    머신러닝
    AWS
    칼만필터는어렵지않아python
    데이터분석
    Python
    파이썬
    프로그래머스
    칼만필터는어렵지않아파이썬
    django
    데이터 엔지니어
    에어플로우
    넘파이
    Airflow
    파이게임
    파이썬게임개발
    KalmanFilter
    질롱코리아
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Minding
SQLAlchemy QueuePool 에러 해결하기 (sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00)
상단으로

티스토리툴바