[BrewBuds] 회원 게시글 조회 쿼리 개선

hwstar·2025년 2월 4일

BrewBuds

목록 보기
1/3
post-thumbnail

회원 게시글 조회시

  1. 팔로우 한 사람들의 게시글
  2. 팔로우 하지 않은 사람들의 게시글
    순서대로 나와야하는 요구사항
# 1 (팔로우한 사람들의 게시글)
following_posts = self.get_feed_by_follow_relation(user, True).filter(filters).order_by("-id")

# 2 (팔로우 하지 않은 사람들의 게시글)
unfollowing_posts = self.get_feed_by_follow_relation(user, False).filter(filters).order_by("-id")

현재

각각 쿼리(총 2번)해서 메모리에서 list, chain 으로 합치는 방법

Method: GET | Path: /records/post/ | Duration: 3.2465s | DB Queries: 16 | Status: 200

  • cpu time : 3227.14ms
  • sql time : 285.54ms
posts = list(chain(following_posts, unfollowing_posts))

개선 방법

db에서 union으로 합치고 중복확인 하지않고 한번의 쿼리로 가져오는 방법

Method: GET | Path: /records/post/ | Duration: 3.2377s | DB Queries: 15 | Status: 200

  • cpu time : 3179.88ms
  • sql time : 281.22 ms
posts = following_posts.union(unfollowing_posts, all=True)

응답시간 차이는 얼마 나지 않는다. 하지만 개선전에는 DB에 쿼리를 2번 실행하고 두 쿼리셋 데이터를 메모리에 모두 올려 어플리케이션 레벨에서 합치는 작업을 하고 개선 후에는 쿼리 수를 1번으로 줄이고 DB 레벨에서 union으로 합쳐서 사용하여 메모리 사용량을 줄일 수 있었다.

물론 쿼리 복잡도가 올라가 데이터의 크기가 크다면 DB 부하가 더 커질 여지가 있다.

결론

  • 쿼리 수(2->1) 및 메모리 사용량을 감소
  • Python 레벨에서의 불필요한 chain() 연산을 제거함 -> Union All로 해결

0개의 댓글