MagicStack / MagicStack/asyncpg

Feature Request: Retry on failed acquires (timeouterror/connectionerror)

Aperta
#620 0 commenti 10 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
Python
Stelle
8.1k
Fork
469
Merge medio
18m
PR unite (30g)
4

Descrizione

  • asyncpg version: 0.21.0
  • PostgreSQL version: any
  • Do you use a PostgreSQL SaaS? If so, which? Can you reproduce
    the issue with a local PostgreSQL install?
    : -- dont use it
  • Python version: any
  • Platform: any
  • Do you use pgbouncer?: no
  • Did you install asyncpg with pip?: yes
  • If you built asyncpg locally, which version of Cython did you use?: not built locally
  • Can the issue be reproduced under both asyncio and
    uvloop?
    : yes

Would you accept a contribution to asyncpg's Pool in which we can retry failed acquires (timeouterrors/connectionresetbypeer/...) which are caused by network issues?
The default behaviour wouldn't retry, as it's happening right now.

This is useful for data processing pipelines with multiple acquires in it's flow (distinct dbs): Being able to configure acquire_max_retries when creating the pool would help keeping the code simpler and not have to wrap all our 'acquires' with retries. The retry decorator logic on acquire can become non-trivial because of the contextmanager auto-releasing the connection after successful usage OR other errors (unrelated to asyncpg) that happen after acquiring a connection+exiting the context (this caused some pain for us).

If you are willing to accept this feature, I'm happy to implement it on my own and submit a PR.

Just to give you an idea, this is what we had to implement on our project in order to have pool acquires with retries:

async def retry(coro, exceptions=(Exception,), max_retries=3, retry_delay_seconds=0):
    for attempt in range(max_retries):
        try:
            return await coro()
        except exceptions:
            logger.exception(f"{coro} attempt failed. Attempt {attempt + 1}/{max_retries}")
            if attempt + 1 == max_retries:
                raise
        await asyncio.sleep(retry_delay_seconds)


class PoolWithRetries:
    def __init__(self, pool: asyncpg.pool.Pool, max_retries=3, retry_delay_seconds=0):
        self.pool = pool
        self.max_retries = max_retries
        self.retry_delay_seconds = retry_delay_seconds

    @asynccontextmanager
    async def acquire(self, *args, **kwargs):
        # Reimplementation of PoolAcquireContext with retries
        # Only supports `async with this.acquire() as con` syntax
        con = await retry(
            partial(self.pool.acquire, *args, **kwargs),
            exceptions=(asyncio.TimeoutError, ConnectionError),
            max_retries=self.max_retries,
            retry_delay_seconds=self.retry_delay_seconds,
        )
        try:
            yield con
        finally:
            await self.pool.release(con)

    async def release(self, *args, **kwargs):
        await self.pool.release(*args, **kwargs)

    async def close(self):
        await self.pool.close()

The implementation becomes much simpler if we can do it inside asyncpg.

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia dal punto di ingresso asyncpg Pool.acquire e dal comportamento di PoolAcquireContext descritto nell’issue. Definisci come i retry di acquire configurabili devono gestire gli errori di timeout e di connessione senza ripetere i tentativi per errori non correlati né interrompere il rilascio del context manager, quindi aggiungi la copertura per il comportamento di retry accettato prima di considerare completa la funzionalità.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
postgresql, python
Ambito
backend-api-design, database
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.