Git Product home page Git Product logo

highlights-myself's Issues

컬렉션 목록 가져오기 N+1 문제

계층적인 컬렉션을 구상하였을 때 '아... N+1 문제 어떻게 해결하지' 라는 생각이 먼저 들었습니다.
물론, Spring Boot JPAFetch Join이나 EntityGraph 등 여러 방법이 있고 적용한 경험이 있지만
Ktor Framework에서 해결할 수 있는지 알 수 없었기 때문에 걱정이 있었습니다.

✏️ 일단 부딪쳐보자~

여러 API를 완성하고 컬렉션 목록 가져오기 API를 만들어야 할 때가 왔습니다.

첫 번째로, 조인을 사용하는 방법을 구상했습니다.

  • 조인된 Row를 가져올 수 있지만, 데이터 가공이 어려웠기 때문에 다른 방법을 찾아야 했습니다.

두 번째로, Kotlin Exposed DAO를 사용했습니다.

  • DAO는 유용한 메서드와 자동 매핑을 지원하기 때문에 가능하지 않을까 생각했습니다.
    DAO의 즉시 로딩을 사용해 같은 계층의 컬렉션을 한 번에 가져오는 쿼리를 사용할 수 있었습니다.
  • 하지만 DAO의 메서드를 사용하면 쿼리가 중복으로 요청되는 문제가 추가로 발생하였습니다.
    image

    중복된 IS NULL LIMIT 20 쿼리

세 번째로, Kotlin Exposed DSL을 사용했습니다.

  • DAO에서 IN 쿼리가 보내지는 걸 확인하고 DSL로 시도하게 되었습니다.
  • 컬렉션 뿐만 아니라 연관된 하이라이트까지 IN 쿼리로 요청하면서 N+1 문제를 해결할 수 있었습니다.
    image

    한 번만 수행되는 IS NULL LIMIT 20 쿼리

마지막으로, IN 쿼리의 성능을 확인했습니다.

  • EXPLAIN문 쿼리로 DB가 어떤 SCAN을 확인할 수 있습니다.
    image
    필터링된 100개의 row에 대해 최대 37개의 아이디로 조회했을 때, Index Range Scan을 통해 접근하였습니다.
EXPLAIN SELECT tbl_collection.id, tbl_collection.user_id, tbl_collection.`name`, tbl_collection.parent_id FROM tbl_collection WHERE tbl_collection.parent_id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 15, 16, 17, 18, 19, 21, 24, 28, 30, 50, 56, 58, 59, 60, 61, 62, 64, 68, 70, 71, 89, 90, 91, 97, 99, 100);

최적화하는 과정에서 데이터베이스와 Ktor에 대해 공부한 점이 많아 재미있었습니다.

Kotest "Please call Database.connect() before using this code" 에러

KotestMockk를 사용해 테스트 코드를 작성하려 했습니다.
빠르게 테스트 코드를 작성하고 실행을 해보았는데....

디스패처 에러와 데이터베이스와 연결이 안 되었다고 합니다.

문제의 원인은 UseCase를 호출할 때 사용된 dbQuery 함수때문이였습니다.

트랜잭션을 호출해 TransactionManager에 접근됩니다.

dbQuery 인자를 꺼내야 하는 상황에서 다행히 Mockk 함수인 firstArg로 가져올 수 있었습니다.

image

Transaction을 Mock으로 바꿔친 후 실행 로직을 dbQuery밖으로 꺼내오는 동작

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.