DB 레벨 분기 vs 애플리케이션 레벨 분기

송용진·2025년 6월 20일

Python / Django

목록 보기
8/23

DB 레벨 분기

(쿼리 분기 / Database-side Filtering)

# get_confirmed_chatrooms
schedule_queryset.filter(schedule_start__isnull=False)
# get_unconfirmed_chatrooms는
schedule_queryset.filter(schedule_start__isnull=True)

이 방식은 명확하지만,
쿼리를 두 번 날리기 때문에
성능 최적화를 위해 하나의 쿼리로 처리하고
이후 분기하는 방식으로 바꾸는 것이 가능함

특징

•	DB에서 조건 필터링을 수행 
→ 필요한 데이터만 가져오므로 전송량이 적음.
•	각 쿼리가 목적에 최적화되어 명확하고 유지보수에 유리함.
•	쿼리가 많아지면 DB 부하가 증가할 수 있음.

애플리케이션 레벨 분기

(코드 분기 / Application-side Filtering)

먼저 한 번의 쿼리로 모든 채팅방 정보를 가져오고,
이후 Python 코드로 분기할 수 있음

@staticmethod
def get_chatrooms_grouped_by_confirmation(user):
    schedule_queryset = ChatRoomQueryService.get_user_schedules(user)
    schedule_ids = schedule_queryset.values_list('schedule_id', flat=True)

    all_chatrooms = ChatRoom.objects.filter(schedule__schedule_id__in=schedule_ids)

    confirmed = []
    unconfirmed = []

    for chatroom in all_chatrooms:
        if chatroom.schedule.schedule_start is None:
            unconfirmed.append(chatroom)
        else:
            confirmed.append(chatroom)

    return {
        "confirmed": confirmed,
        "unconfirmed": unconfirmed
    }

이 함수는 ChatRoom 객체들을 한 번의 쿼리로 가져온 후 schedule.schedule_start가 None인지 여부로 분기

특징

•	DB에 대한 쿼리는 단 한 번 
→ 응답 시간은 짧을 수 있음.
•	단점은 불필요한 데이터까지 가져올 수 있음 (필터링은 Python에서 이루어짐).
•	채팅방 수가 많을수록 메모리 사용량이 늘고 성능 저하 가능.

어떤 방식이 더 나은가?

•	애플리케이션(Python) 분기 방식은 채팅방 수가 많지 않거나, schedule.schedule_start 필드만으로 분기할 수 있는 
간단한 상황일 때 효과적
•	반면, DB에서 직접 분기하는 쿼리 두 번이 
쿼리 캐시 효과나 병렬 실행 가능성 때문에 더 나을 수도 있으므로, 
사용 환경에 따라 벤치마킹이 필요함

•	성능이 중요하거나 데이터 양이 많다면 → “DB 분기 방식” 적용
•	쿼리 수를 줄이고 간단한 분기를 원한다면 → “Python 분기 방식” 적용
profile
개발자

0개의 댓글