본문 바로가기
C.W.K.
Stream
Lesson 05 of 10 · published

Single Connection vs Pool

~12 min · aiosqlite, connection-pool, concurrency

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

connection 하나가 pool을 이길 때가 많아

aiosqlite는 connection 하나에서 벌어지는 연산을 백그라운드 thread를 통해 한 줄로 세워. WAL 모드라면 이걸로 웬만한 웹 앱에는 충분해. SQLite 레벨에서 reader와 writer가 서로를 안 막고, connection 단위로 줄 세우는 것도 충분히 빨라서 그 줄이 병목이 되는 일이 거의 없거든.

pool을 고민할 때는 이럴 때야.

  • writer가 여럿이면서 write 하나하나가 충분히 오래 걸려서 병렬로 돌릴 이득이 있을 때. SQLite는 한 번에 writer 하나라 드문 경우지만.
  • 코어가 많은 머신에서 read가 connection 하나의 처리량을 다 채워버릴 때.
  • 안전을 위해 읽기 전용 connection과 쓰기용 connection을 갈라두고 싶을 때.

피파처럼 생긴 앱, 그리고 대부분의 local-first 제품에는 공유 connection 하나가 맞고 더 단순해.

Tip: pool이 정말 필요하면 SQLAlchemy까지 갈 것 없이 asyncio.Queue로 작은 걸 직접 만들어. SQLAlchemy는 query builder가 필요할 때 좋은 거고, 파일 하나짜리 SQLite 앱에는 대개 과해.

Code

Tiny async connection pool·python
import asyncio, aiosqlite
from contextlib import asynccontextmanager

class AioSqlitePool:
    def __init__(self, path: str, size: int = 4):
        self.path = path
        self._pool: asyncio.Queue = asyncio.Queue(maxsize=size)
        self._size = size

    async def setup(self):
        for _ in range(self._size):
            conn = await aiosqlite.connect(self.path)
            conn.row_factory = aiosqlite.Row
            await conn.execute('PRAGMA journal_mode = WAL')
            await self._pool.put(conn)

    @asynccontextmanager
    async def acquire(self):
        conn = await self._pool.get()
        try:
            yield conn
        finally:
            await self._pool.put(conn)

    async def close(self):
        while not self._pool.empty():
            conn = await self._pool.get()
            await conn.close()

External links

Exercise

위의 작은 pool을 직접 구현하고 벤치마크를 돌려봐. read가 많은 워크로드에서 connection 네 개짜리 pool이 공유 connection 하나를 이기기 시작하는 동시성 수준은 어디쯤일까? write가 많을 때는? pool이 도움이 되는 지점과 지연만 더 얹는 지점을 찾아봐.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.