python runtime_error ai_generated true

asyncpg.exceptions.InterfaceError: cannot perform operation: another operation is in progress

ID: python/asyncpg-cannot-perform-operation-another-operation-in-progress

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-07-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8+ active
3.9+ active
3.10+ active
3.11+ active

Root Cause

Two coroutines used the same asyncpg connection concurrently. asyncpg connections are not concurrency-safe; each must be used by one coroutine at a time.

generic

中文

两个协程并发使用了同一个 asyncpg 连接。asyncpg 连接不是并发安全的,同一时间只能由一个协程使用。

Workarounds

  1. 95% success
    pool = await asyncpg.create_pool(dsn, min_size=1, max_size=10)
    async with pool.acquire() as conn:
        await conn.fetch('SELECT 1')
  2. 90% success
    lock = asyncio.Lock()
    async with lock:
        await conn.fetch(query)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Does not serialize access; race still occurs under load.

  2. 75% fail

    Retries can still collide with the same concurrent coroutine and corrupt protocol state.