Skip to content

Module 07 · Lesson 7.4

Failure Modes, Timeouts and Retries

40 minUpdated 19 Nov 2026Part of Performance and Reliability Investigation · Existing Project Engineering
On this page
  1. What you will learn
  2. What goes wrong when a partner system is slow or down
  3. Worked scenario: the importer that waited forever
  4. Add a timeout, then retry only what is safe
  5. Make the import safe to run twice: idempotency and unique constraints
  6. Step-by-step workflow
  7. Using an AI assistant to review failure handling
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

You phone a shop to ask if your order is ready. Nobody answers, but you keep holding the line. An hour later you are still listening to the ring. A sensible person hangs up after a minute, and tries again later. Then they check that they do not order the same goods twice.

A program that calls another company's system needs the same habits. In this lesson you will study a different kind of problem from the slow page: what happens when something the system depends on is slow or down. The example is the fictional Tidewell Wholesale order importer. All people, partners and data are invented, and the code is a simplified version you can run.

What you will learn

  • List the ways a call to another system can fail, and what each does to your system.
  • Add a timeout, and retry only the errors that are safe to retry, with backoff and jitter.
  • Make an import safe to run twice, using idempotency and a unique constraint.
  • Test failure behaviour with a fake partner and a fake clock, so tests never wait.

Before you start

What goes wrong when a partner system is slow or down

A failure mode is a way something can go wrong. You list them before they happen, the way you check a car for flat tyre, empty tank and dead battery. Calls to other systems have a short, predictable list.

Failure modeWhat it looks likePlain picture
Cannot connectNo answer when you try to open the connectionThe phone does not ring at all
Slow replyConnected, but the answer takes minutes, or never comesSomeone picks up and then goes quiet
Error replyA reply that says 'busy' (503) or 'too many requests' (429)'Please call back later'
Wrong requestA reply that says your request is bad (400) or not allowed (401)'You dialled the wrong department'
Partial workThe call works for the first part, then failsHalf the parcels arrive
Five failure modes of a call to another system.

Each mode needs its own response. Waiting too long is bad. Retrying is good for some and harmful for others. So you need a few precise tools. Here they are in plain words.

Timeout
A limit on how long you will wait for an answer. When time is up, you stop waiting and treat it as a failure. It is hanging up after a minute of silence.
Retry
Trying the same call again after a failure. It helps when the failure was brief, such as a busy moment. It is calling back later.
Backoff (exponential backoff)
Waiting longer before each new try: for example 1 second, then 2, then 4. It gives a struggling system room to recover. Think of knocking at a door: you do not hammer every second, you wait a little longer each time.
Jitter
A bit of randomness added to the wait. If 100 workers all wait exactly 2 seconds, they all knock together again. Random waits spread them out, like people leaving a stadium by different gates.
Idempotency
An action is idempotent when doing it twice has the same result as doing it once. Pressing a lift button twice is the same as pressing it once. Importing the same partner order twice should not create two orders.
Circuit breaker
A guard that stops calling a system that keeps failing, for a while, and then tests it again. It is the fuse in your fuse box: it trips so that one fault does not burn the house down.

Worked scenario: the importer that waited forever

Some larger customers send orders through their own systems. This is called EDI (electronic data interchange): computers exchanging orders instead of people typing them. In tidewell-orders, a Celery task import_partner_orders(partner) in dispatch/importers.py calls the partner's API and creates orders. Celery is the tool that runs background jobs.

Support tells you what happened last month. A partner's system was slow. Importer workers hung for hours. Confirmation emails waited in the queue behind them. Then Celery's automatic retry ran the whole import again, and orders were created twice. There was no unique reference to stop it. Here is the line that started it, as an excerpt.

Pythondispatch/importers.py (excerpt)
def fetch_page(partner, page):
    response = requests.get(
        partner.orders_url,
        params={"page": page},
        headers={"Authorization": f"Bearer {settings.EDI_API_TOKEN}"},
    )                      # no timeout: Requests may wait forever
    response.raise_for_status()
    return response.json()

The call that has no timeout. An excerpt of the real service, not runnable on its own.

The Requests documentation (opens in a new tab) warns that a call with no timeout can hang for minutes or longer. This is a classic cause of workers stuck for hours. A stuck worker holds its place, so other jobs, such as confirmation emails, wait behind it.

To study this safely, you need a pretend partner and a small database. They are in the file below. The partner returns six orders, two per page. The database has an orders table. You can switch its unique rule on or off.

Pythonedi_support.py
import sqlite3


class ConnectTimeout(Exception): ...      # could not reach the partner in time
class ReadTimeout(Exception): ...         # connected, but no reply in time
class ServerBusy(Exception): ...          # HTTP 503: try again later
class BadRequest(Exception): ...          # HTTP 400: our request is wrong


ORDERS = [{"ref": f"EDI-{1000 + i}", "total_pence": 2500 + 100 * i} for i in range(1, 7)]


def make_partner(failures=None):
    """A pretend partner API. failures maps a call number to the error to raise."""
    failures = failures or {}

    def get(page, timeout=None):
        get.calls += 1
        get.timeouts.append(timeout)
        if get.calls in failures:
            raise failures[get.calls]
        return ORDERS[(page - 1) * 2 : page * 2]  # two orders per page

    get.calls, get.timeouts = 0, []
    return get


def new_db(unique):
    conn = sqlite3.connect(":memory:")
    rule = ", UNIQUE (partner_code, edi_reference)" if unique else ""
    conn.execute(
        "CREATE TABLE orders (id INTEGER PRIMARY KEY, partner_code TEXT NOT NULL, "
        "edi_reference TEXT NOT NULL, total_pence INTEGER NOT NULL" + rule + ")"
    )
    return conn

A pretend partner API and a small orders table, simplified so you can run them. 'failures' says which call number should fail.

What each part does

  • The four error classes stand for what a real HTTP library raises: a connect timeout, a read timeout, a 503 and a 400.
  • make_partner returns a function get(page, timeout=None). It counts its calls and records the timeouts it was given.
  • failures={3: ReadTimeout(...)} means 'the third call fails'. Everything else works.
  • new_db(unique) makes the orders table. With unique=True it adds UNIQUE (partner_code, edi_reference).

Now the old importer. It saves each order as it arrives. The partner times out on the third call, so page 3 never arrives. A retry runs the whole import again, as the task runner did last month.

Pythonedi_before.py
from edi_support import ReadTimeout, make_partner, new_db


def import_partner_orders(conn, partner_code, get):
    """The old importer: no timeout, and no check for orders it already has."""
    page = 1
    while True:
        orders = get(page)  # real code: requests.get(url, headers=...), no timeout
        if not orders:
            return
        for order in orders:
            conn.execute(
                "INSERT INTO orders (partner_code, edi_reference, total_pence) "
                "VALUES (?, ?, ?)",
                (partner_code, order["ref"], order["total_pence"]),
            )
            conn.commit()  # each order is saved on its own
        page += 1


conn = new_db(unique=False)
get = make_partner(failures={3: ReadTimeout("no reply")})

for attempt in (1, 2):  # the task runner retries the WHOLE import
    try:
        import_partner_orders(conn, "ACME", get)
        print(f"attempt {attempt}: finished")
        break
    except ReadTimeout:
        saved = conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
        print(f"attempt {attempt}: partner timed out after {saved} orders were saved")

rows = conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
distinct = conn.execute("SELECT COUNT(DISTINCT edi_reference) FROM orders").fetchone()[0]
print(f"rows in orders: {rows}")
print(f"different partner references: {distinct}")

The old behaviour in miniature: no timeout, and no check for orders it already has.

Real output (run twice, identical)Captured from a real run
attempt 1: partner timed out after 4 orders were saved
attempt 2: finished
rows in orders: 10
different partner references: 6

Six different orders, ten rows. The first four were saved before the timeout, then saved again on the retry. That is how a retry made duplicates. Customers would have been charged and sent goods twice, and confirmation emails would have gone out twice.

Three separate faults combined here. The missing timeout let workers hang. The blind retry repeated work that had already been done. And nothing stopped a duplicate. Fix each one.

Add a timeout, then retry only what is safe

Fix 1: set a timeout

Requests accepts a timeout. You can give two numbers: how long to wait to connect, and how long to wait for the partner to send data. A common choice for the connect value is just over a multiple of 3 seconds, such as 3.05. The Requests documentation explains why.

Pythondispatch/importers.py (excerpt)
TIMEOUT = (3.05, 10)  # seconds to connect, seconds to wait for data

response = requests.get(
    partner.orders_url,
    params={"page": page},
    headers={"Authorization": f"Bearer {settings.EDI_API_TOKEN}"},
    timeout=TIMEOUT,
)

The same call with a timeout of (3.05 s to connect, 10 s to wait for data). An excerpt.

The read timeout is how long Requests waits between bytes from the partner. It is not a limit on the whole job. Choose values from what the partner normally takes, and write down why.

Fix 2: retry only the errors that are safe to retry

A retry is a bet that the failure was brief. It is a good bet for a timeout or a busy answer. It is a bad bet for a wrong request: asking the same wrong thing again will fail again. So the rule is to name what you retry.

ErrorRetry?Why
Connect timeout, read timeoutYes, a few timesOften brief. Reading data is safe to repeat.
503 busy, 429 too many requestsYes, with backoffThe partner is asking you to wait.
400 bad request, 401 not allowed, 404 not foundNoThe same call will fail the same way. Report it.
Any error on an action that changes dataOnly if it is idempotentA repeat could do the action twice.
Which failures to retry. Reading a partner's order list is safe to repeat. Creating something may not be.

Here is a small retry helper. It retries only the error types you pass in, at most three times. Between tries it waits with exponential backoff and jitter. The sleep function and the random source are passed in, so a test can control them.

Pythonretrying.py
import random


def backoff_delay(attempt, base, cap, rng):
    """Exponential backoff with full jitter: a random wait up to a growing limit."""
    limit = min(cap, base * 2**attempt)
    return rng.uniform(0, limit)


def call_with_retries(fn, retry_on, max_retries=3, base=1.0, cap=30.0,
                      sleep=None, rng=random):
    """Call fn. Retry only the errors in retry_on, at most max_retries times."""
    attempt = 0
    while True:
        try:
            return fn()
        except retry_on:
            if attempt >= max_retries:
                raise  # out of retries: let the caller see the failure
            sleep(backoff_delay(attempt, base, cap, rng))
            attempt += 1

At most 3 retries, only for the errors you name, with exponential backoff and full jitter.

What each part does

  • base * 2**attempt doubles the limit each time: 1 s, 2 s, 4 s, and so on.
  • min(cap, ...) stops the limit growing past a ceiling, 30 s here.
  • rng.uniform(0, limit) picks a random wait between zero and the limit. That is the jitter.
  • except retry_on catches only the named errors. Any other error leaves the function at once.
  • if attempt >= max_retries: raise gives up after the last retry and lets the caller see the failure. Silent failure is the worst result.

In Celery

Celery can retry a task by itself. This is the setting that caused the duplicates last month, so read it carefully. Celery runs the whole task again. That is why the next fix is needed.

Pythondispatch/importers.py (excerpt)
@shared_task(
    autoretry_for=(requests.exceptions.Timeout,),  # only timeouts
    retry_backoff=True,      # wait 1 s, 2 s, 4 s ... between tries
    retry_jitter=True,       # add randomness to each wait
    max_retries=3,
)
def import_partner_orders(partner_code):
    ...

Celery's automatic retry with backoff and jitter. An excerpt; check the Celery docs for your version.

See the Celery documentation on tasks (opens in a new tab) for retry options and time limits, which stop a task that runs too long. A time limit is a second guard, not a replacement for a timeout on the call itself.

Circuit breakers, as an idea

Retries help with brief problems. If a partner is down for an hour, retrying every few seconds only adds load. A circuit breaker keeps count of failures. After a number of them, it stops calling for a set time, then lets one call through to test. This lesson does not build one, but you should know the idea. See the Google SRE chapter on addressing cascading failures (opens in a new tab) for the thinking behind it.

Make the import safe to run twice: idempotency and unique constraints

Even with careful retries, a job can still run twice: a retry, a restart, or someone pressing the button again. The real fix is to make running twice harmless. For orders, the partner gives each order a reference. You store it, and refuse a second copy.

A unique constraint is a rule inside the database: 'no two rows may share these values'. The database enforces it for everyone, even a bug in your code. Here the pair (partner_code, edi_reference) must be unique. The check cannot be skipped.

Pythonorders/models.py (excerpt)
class Order(models.Model):
    partner_code = models.CharField(max_length=20, blank=True)
    edi_reference = models.CharField(max_length=60, blank=True)
    # ... other fields ...

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["partner_code", "edi_reference"],
                name="orders_partner_ref_uniq",
                condition=~models.Q(edi_reference=""),   # only EDI orders
            )
        ]

The Django version of the rule. An excerpt; it needs a migration, and old duplicate rows must be dealt with first.

Now the repaired importer. It sends a timeout on every call, retries only safe errors, and skips orders it already has. The skip happens before any later steps, so no second confirmation email is sent.

Pythonedi_after.py
from edi_support import ConnectTimeout, ReadTimeout, ServerBusy
from retrying import call_with_retries

TIMEOUT = (3.05, 10)  # seconds to connect, seconds to wait for a reply
RETRYABLE = (ConnectTimeout, ReadTimeout, ServerBusy)


def import_partner_orders(conn, partner_code, get, sleep, rng):
    """Returns (imported, skipped). Safe to run twice."""
    imported = skipped = 0
    page = 1
    while True:
        orders = call_with_retries(
            lambda: get(page, timeout=TIMEOUT), RETRYABLE, sleep=sleep, rng=rng
        )
        if not orders:
            return imported, skipped
        for order in orders:
            cursor = conn.execute(
                "INSERT OR IGNORE INTO orders (partner_code, edi_reference, total_pence) "
                "VALUES (?, ?, ?)",  # PostgreSQL: INSERT ... ON CONFLICT DO NOTHING
                (partner_code, order["ref"], order["total_pence"]),
            )
            imported += cursor.rowcount
            skipped += 1 - cursor.rowcount
        conn.commit()
        page += 1

The repaired importer in miniature. In PostgreSQL the insert would be INSERT ... ON CONFLICT DO NOTHING.

What each part does

  • TIMEOUT is passed to every call. RETRYABLE lists the safe errors.
  • Each page is fetched through call_with_retries, so a slow page is retried on its own, not the whole import.
  • INSERT OR IGNORE adds the order unless the unique rule says it exists. cursor.rowcount is 1 if the row was added and 0 if it was skipped.
  • The function returns how many orders were imported and how many were skipped.

The next script runs the new importer through several situations. The random source is seeded and the sleep function only records the waits, so nothing really waits and the output never changes.

Pythonedi_after_demo.py
import random
import sqlite3

from edi_after import import_partner_orders
from edi_support import BadRequest, ReadTimeout, make_partner, new_db

conn = new_db(unique=True)
waits = []
get = make_partner(failures={3: ReadTimeout("no reply")})
rng = random.Random(7)

print("run 1:", import_partner_orders(conn, "ACME", get, waits.append, rng))
print("  waits (s):", [round(w, 2) for w in waits])
print("  timeout used on every call:", set(get.timeouts))
print("run 2:", import_partner_orders(conn, "ACME", get, waits.append, rng))
print("  rows in orders:", conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0])

try:
    conn.execute("INSERT INTO orders (partner_code, edi_reference, total_pence) "
                 "VALUES ('ACME', 'EDI-1001', 2600)")
except sqlite3.IntegrityError as error:
    print("duplicate stopped:", error)

waits.clear()
always_down = make_partner({n: ReadTimeout("no reply") for n in range(1, 20)})
try:
    import_partner_orders(new_db(True), "ACME", always_down, waits.append, random.Random(7))
except ReadTimeout:
    print(f"partner down: gave up after {always_down.calls} tries, waits {[round(w, 2) for w in waits]}")

bad = make_partner({1: BadRequest("400")})
try:
    import_partner_orders(new_db(True), "ACME", bad, waits.append, random.Random(7))
except BadRequest:
    print(f"bad request: {bad.calls} try, no retry")

Runs the new importer: a slow page, a second run, a raw duplicate, a partner that stays down and a bad request.

Real output (run twice, identical)Captured from a real run
run 1: (6, 0)
  waits (s): [0.32]
  timeout used on every call: {(3.05, 10)}
run 2: (0, 6)
  rows in orders: 6
duplicate stopped: UNIQUE constraint failed: orders.partner_code, orders.edi_reference
partner down: gave up after 4 tries, waits [0.32, 0.3, 2.6]
bad request: 1 try, no retry

Read the lines one by one. Run 1 hit one slow page, waited 0.32 seconds and still imported all six orders. Run 2 imported none and skipped six, so running twice changed nothing. The database itself refused the raw duplicate. When the partner stayed down, the importer gave up after four tries (the first plus three retries) with growing waits, and then raised the error. And a bad request was tried only once.

Pin it down with tests

A failure that you can only cause on a bad day is hard to trust. The fake partner and the fake sleep let you test it at any time, in a fraction of a second.

Pythontest_edi_after.py
import random

import pytest

from edi_after import TIMEOUT, import_partner_orders
from edi_support import BadRequest, ReadTimeout, make_partner, new_db
from retrying import backoff_delay


def run(conn, get):
    waits = []
    result = import_partner_orders(conn, "ACME", get, waits.append, random.Random(7))
    return result, waits


def test_every_call_has_a_timeout():
    get = make_partner()
    run(new_db(unique=True), get)
    assert set(get.timeouts) == {TIMEOUT}


def test_a_slow_page_is_retried_after_a_wait():
    get = make_partner({3: ReadTimeout("no reply")})
    (imported, skipped), waits = run(new_db(unique=True), get)
    assert (imported, skipped) == (6, 0)
    assert len(waits) == 1


def test_running_the_import_twice_creates_no_duplicates():
    conn = new_db(unique=True)
    run(conn, make_partner())
    (imported, skipped), _ = run(conn, make_partner())
    assert (imported, skipped) == (0, 6)
    assert conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0] == 6


def test_gives_up_after_three_retries():
    get = make_partner({n: ReadTimeout("no reply") for n in range(1, 20)})
    with pytest.raises(ReadTimeout):
        run(new_db(unique=True), get)
    assert get.calls == 4  # the first try plus three retries


def test_a_bad_request_is_not_retried():
    get = make_partner({1: BadRequest("400")})
    with pytest.raises(BadRequest):
        run(new_db(unique=True), get)
    assert get.calls == 1


def test_waits_never_pass_the_cap():
    rng = random.Random(1)
    assert all(backoff_delay(9, base=1.0, cap=30.0, rng=rng) <= 30.0 for _ in range(100))

Six tests that pin the failure behaviour: timeout, retry, no duplicates, giving up, no retry on bad requests and a capped wait.

Real pytest output (timings vary from run to run)Captured from a real run
============================= test session starts =============================
collecting ... collected 6 items

test_edi_after.py::test_every_call_has_a_timeout PASSED                  [ 16%]
test_edi_after.py::test_a_slow_page_is_retried_after_a_wait PASSED       [ 33%]
test_edi_after.py::test_running_the_import_twice_creates_no_duplicates PASSED [ 50%]
test_edi_after.py::test_gives_up_after_three_retries PASSED              [ 66%]
test_edi_after.py::test_a_bad_request_is_not_retried PASSED              [ 83%]
test_edi_after.py::test_waits_never_pass_the_cap PASSED                  [100%]

============================== 6 passed in 0.02s ==============================

The shown result is the real output of one run. Test names and results were the same in a second run. Only the time at the end changes.

Step-by-step workflow

  1. Step 1: List every call that leaves your system

    Search the code for HTTP clients, database drivers, queue publishers and email senders. Write one line for each: where it is, what it calls, what happens if it is slow.

    What you should see: A table of outside calls.

  2. Step 2: Check each call for a timeout

    Look for an explicit timeout. In Requests, the default is no timeout. Add one where it is missing, and write down why you chose the numbers.

    What you should see: Every outside call has a limit on waiting.

  3. Step 3: Write the failure modes

    For the important calls, list what happens for each failure: cannot connect, slow reply, error reply, wrong request and partial work.

    What you should see: A short failure-mode table.

  4. Step 4: Decide what may be retried

    Name the safe errors. Set a maximum number of tries, a backoff with jitter and a cap on the wait. Do not retry errors that will repeat.

    What you should see: A retry rule written in one sentence.

  5. Step 5: Make repeating harmless

    Find the natural unique key, such as the partner's order reference. Add a unique constraint and skip what you already have.

    What you should see: Running the job twice changes nothing.

  6. Step 6: Test with fakes

    Write tests with a fake partner and a fake sleep for: slow, down, bad request and run-twice. Keep them in the suite.

    What you should see: Failure behaviour that stays checked.

From a hanging job to a safe one
  1. List outside calls

    Where it can hang

  2. Add timeouts

    Connect and read

  3. Failure modes

    What each failure does

  4. Safe retries

    Backoff, jitter, cap

  5. Idempotency

    Unique reference

  6. Fake-partner tests

    Slow, down, twice

Each stage guards against one of the three faults: waiting forever, blind retries and duplicates.

Using an AI assistant to review failure handling

An assistant is useful for walking through a function and listing what could go wrong. It is a patient reviewer of error paths, which people often skip. It will also, by default, suggest the simple answer: wrap the call in a retry loop.

  • Give it: the function, how it is called (a Celery task?), and what the partner's API returns. Remove tokens and real URLs.
  • Ask it for: a failure-mode table, the questions you should ask about timeouts and retries, and where repeating the action would do harm.
  • Watch for: retry of everything, no wait between tries, no maximum, retry of a 400, and no mention of duplicates.
  • Then check: each suggested fix against a test with a fake partner. If it cannot be tested, say so in the review.

Conclusion and your next step

You can now ask 'what happens when this is slow or down?' about any outside call. You added a timeout, retried only safe errors with backoff and jitter, and made the import safe to run twice with a unique reference. You also tested it with a fake partner and a fake clock.

Your next step: show that the changes helped. Continue with Proving an Improvement and compare the before and after measurements for the "My orders" fix.

For more, read Debugging Deadlocks and Race Conditions with AI and the module overview Performance and Reliability Investigation. Another course, Integrating an External Service, covers the same ideas for new code.

Reusable prompt

Failure-mode review of an outside call

Asks an assistant to list the failure modes of a call to another system, and to check timeouts, retries and idempotency, with questions rather than a rewrite.

I am reviewing a Celery task in a Python and Django service called tidewell-orders (fictional). It imports orders from a partner's API. Use ONLY the code below. Do not rewrite it yet.

Context:
- The task is dispatch/importers.py import_partner_orders(partner). Celery retries it automatically on any exception.
- Last month the partner was slow: workers hung for hours, confirmation emails queued behind them, and the retry created duplicate orders. EDI orders have no unique reference today.

Code (token removed):
def fetch_page(partner, page):
    response = requests.get(
        partner.orders_url,
        params={"page": page},
        headers={"Authorization": "Bearer <redacted>"},
    )
    response.raise_for_status()
    return response.json()

Please give me:
1. A table of failure modes for this call (cannot connect, slow reply, error reply, wrong request, partial work) and what each does to this system.
2. Whether a timeout is set, and what could happen without one.
3. Which errors are safe to retry here and which are not, with reasons.
4. How a retry could create duplicates, and what would make the task idempotent.
5. The questions I should ask the partner or the team before changing anything.
Mark any guess as (unverified).
Show the reusable template

Replace each {{placeholder}} with your own details.

I am reviewing {{task_or_function}} in {{system_description}}. Use ONLY the code below. Do not rewrite it yet.

Context:
{{what_happened_and_how_it_is_called}}

Code (secrets removed):
{{code}}

Please give me:
1. A table of failure modes for this call (cannot connect, slow reply, error reply, wrong request, partial work) and what each does to this system.
2. Whether a timeout is set, and what could happen without one.
3. Which errors are safe to retry here and which are not, with reasons.
4. How a retry could create duplicates, and what would make the task idempotent.
5. The questions I should ask the partner or the team before changing anything.
Mark any guess as (unverified).

Expected output and limitations

A failure-mode table, a statement about the missing timeout, a split of retryable and non-retryable errors, an explanation of how duplicates arise, and a list of questions. It should not hand you a rewritten task.

Sample responseIllustrative — your output will differ
1. Failure modes
| Mode | Effect here |
| Cannot connect | requests raises a connection error; Celery retries the whole task |
| Slow reply | no timeout is set, so the worker can wait without limit |
| Error reply (503, 429) | raise_for_status raises; the task retries |
| Wrong request (400, 401) | raises; a retry repeats the same mistake |
| Partial work | pages 1-2 saved, page 3 fails; the retry re-imports 1-2 |

2. Timeout
None is set. Requests waits as long as the partner takes, so a slow partner can hold a worker (unverified how long; the incident suggests hours).

3. Safe to retry: connect and read timeouts, 503, 429 (reading is repeatable). Not safe: 400, 401, 404.

4. Duplicates
The retry re-runs the whole import, and nothing records which partner references were already saved. A unique (partner_code, edi_reference) would make a repeat harmless.

5. Questions
- Does the partner's API guarantee stable order references?
- Is there a rate limit I should respect when backing off?
- Who handles orders that were already duplicated?

Limitations to keep in mind

  • The assistant has seen only the function. It does not know the partner's real limits or how Celery is configured in your project.
  • It may suggest a retry loop with no maximum, or one that retries every error. Reject both.
  • It may claim the API supports idempotency keys. Nothing in your evidence shows that, so mark it unverified.
  • It cannot decide what to do about orders already duplicated. That is for the finance systems contact.

Common errors and how to fix them

Calling an outside system with no timeout

Why it happens: The default of the HTTP library is to wait, and everything works until the day the partner is slow.

Fix: Set an explicit connect and read timeout on every outside call, and check for any call that has none.

Retrying everything, immediately, forever

Why it happens: A retry loop is the quickest answer, and it works in a quick test.

Fix: Retry only named, safe errors, a few times, with exponential backoff and jitter. Let the failure show after the last try.

Retrying an action that is not idempotent

Why it happens: The retry looks harmless, but the first try may already have done the work.

Fix: Add a unique reference and skip what you already have, so that a repeat does nothing. Do this before turning on automatic retries.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Review the failure handling of one outside call in your repository

Pick one call to another system in a repository or sample application you may study. Review its timeout, retries and idempotency, and propose or test one improvement.

You will need

  • A repository you may study, with at least one HTTP client, queue or email call.
  • The retry helper and fake-partner idea from this lesson, or an equivalent test double in your language.
  • Your notes on how the call is run (web request, scheduled job or background worker).

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • If you find no retries, you may still find a missing timeout. That is worth writing down.
  • If you have no outside calls, use a database call or a file read from a network drive.
  • If you ask an assistant, remove tokens and URLs first, and ask for questions rather than a rewrite.
Show a model answer

A strong answer lists the call, its timeout and its retry rule in a table. It names which errors are retried and why, and it says how a repeat is made harmless, for example a unique reference. It includes a test with a fake dependency that does not wait. A weak answer adds a retry loop with no limit and no test, or adds a timeout and never asks what a retry would repeat.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.A call returns a 400 bad request error. What is the best response?
    Show the answer and explanation

    Answer: B. A 400 means the request itself is wrong, so a retry repeats the mistake. Backoff helps with brief failures such as timeouts and busy answers, not wrong requests. Retrying forever also holds your worker.

  2. 2.Why add random jitter to the wait between retries?
    Show the answer and explanation

    Answer: B. Without jitter, workers that failed together retry together, which creates a new spike. Random waits spread them out. Jitter is about spreading retries out. It is not about making waits longer or hiding failures.

  3. 3.A job that creates orders is retried and creates duplicates. Which change fixes the cause?
    Show the answer and explanation

    Answer: B. The cause is that repeating the work is not harmless. A unique reference makes a repeat do nothing, however it happens. Removing retries hides one trigger but leaves restarts and manual re-runs. A longer timeout has nothing to do with duplicates.

Frequently asked questions

What is a timeout in programming?

A timeout is a limit on how long your program waits for another system to answer. When the time is up, the program stops waiting and treats it as a failure. Without one, a slow system can hold your program forever.

What are exponential backoff and jitter?

Exponential backoff means waiting longer before each retry, for example 1, 2 and then 4 seconds. Jitter adds a random amount to each wait. Together they give a struggling system time to recover, and they stop many clients from retrying all at once.

What does idempotent mean?

An action is idempotent if doing it twice has the same result as doing it once. Importing an order with a reference you already hold, and doing nothing, is idempotent. It makes retries and restarts safe.

Should I always retry a failed request?

No. Retry only errors that may be brief, such as timeouts and busy replies, and only if repeating the action is harmless. Do not retry errors that will repeat, such as a bad request. Always set a maximum number of tries.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.