Skip to main content

protocols.dao.race_condition_retries()

Yield attempts for an action that can lose a race condition.

Usage

Source

protocols.dao.race_condition_retries(
    *,
    description,
    error_on_failure,
    logger=None,
    max_tries=3,
    interval=0.5,
    jitter=0.3
)

Wrap the action in with attempt: for each yielded attempt. Retries it up to max_tries times, waiting interval seconds (plus jitter) after each PreconditionFailedError. That error means the precondition of a DAO update no longer matched because another write came first. A return inside the block ends the retries.

async for attempt in race_condition_retries(
    description=f"add pages to book {book_id}",
    error_on_failure=lambda: BookUpdateError(book_id),
):
    with attempt:  # <-- must use `with attempt:`
        book = await book_dao.get_by_id(book_id)
        extended = book.model_copy(update={"pages": book.pages + 16})
        await book_dao.update(extended, precondition={"pages": book.pages})

Leaving the loop early, by return, break or an exception, leaves the generator suspended until asyncio finalizes it. For deterministic cleanup, wrap it in contextlib.aclosing:

async with aclosing(race_condition_retries(...)) as attempts:
    async for attempt in attempts:
        with attempt:
            ...

Parameters

description: str

What the action does, phrased to follow “to”, e.g. “add pages to book ”. Used in log messages.

error_on_failure: Callable[[], BaseException]

Builds the error to raise once all tries have failed. Called at most once, after the last try.

logger: Logger | None = None

Logs a debug message for each conflict and an error once all tries have failed. Nothing is logged if omitted.

max_tries: int = 3

How many times to try the action. Values below 1 count as 1.

interval: float = 0.5

Seconds to wait between tries. Negative values count as 0.

jitter: float = 0.3
Upper bound, in seconds, of a random delay added to each wait, so callers that conflicted don’t retry at the same moment. Negative values count as 0.