import random


def backoff(retries: int, jitter: bool = True) -> int:
    """
    Compute duration (seconds) to wait before retrying using exponential backoff with
    jitter based on the number of retries a message has already experienced.

    The minimum returned value is 1s
    The maximum returned value is 604800s (7 days)

    With max_retries=9, you will have roughly 30 days to fix and redeploy the the task
    code.

    Parameters
    ----------
    retries : int
        How many retries have already been attemped.
    jitter : bool
        Whether to add random noise to the return value (recommended).

    Notes
    -----
    https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
    """
    x = 6**(retries + 1)
    if jitter:
        x = random.randrange(x // 3, x * 2)
    return min(604_800, x)