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

Single connection 이 종종 pool 이김

aiosqlite 가 single connection 의 연산을 백그라운드 thread 통해 serialize. WAL 모드면 많은 웹 앱에 충분 — SQLite 레벨에서 reader/writer block 안 함, per-connection serialization 이 충분 빨라서 큐가 병목 거의 없음.

Pool 고려 시기:

  • Multiple writer + write 가 충분 long-running 해서 병렬화 이득 (SQLite single-writer-at-a-time 으로 드묾).
  • Multi-core 머신 + read 가 한 connection 의 serialization 포화.
  • 안전 위해 read-only + writer connection 분리 필요.

대부분 피파-shaped 앱 (그리고 대부분 local-first 제품) 엔 single shared connection 이 옳고 더 단순.

Tip: Pool 원하면 SQLAlchemy 손 뻗지 말고 asyncio.Queue 로 작은 거 직접 작성. SQLAlchemy 는 query builder 필요할 때 좋음; single-file SQLite 앱엔 보통 overkill.

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

위 tiny pool 구현 + 벤치마크: read-heavy 워크로드에서 4-connection pool 이 어느 동시성 레벨에서 single shared 이기기 시작? Write-heavy 에선? Pool 이 도움 vs latency 만 추가하는 시점.

Progress

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

댓글 0

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

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