Issue #142 · branch fix/export-retry

Order export retry: uncommitted code changes

When the accounting service is briefly unavailable, the nightly order export now tries again up to three more times instead of giving up, and if the service stays down it keeps the report in a local folder so nothing is lost. This page shows the code function by function and explains every important line.

+ code added line: + in front, solid bar on the left − code removed line: − in front, dashed bar on the left, struck through 1 line explained below Uncoloured lines are unchanged context. Doc comments and long comments inside functions were removed to save space; long lines continue slightly indented on the next line. The code itself is identical to the repository. Explanation level: medium

1. Why this change?

Every night the order exporter sends a summary of the day's orders (the "daily report") to the accounting service. In March the finance team found three days with no report. The logs showed why: at the moment of the export the accounting service was restarting for its nightly maintenance, which takes about 30 seconds. The exporter tried exactly once, failed, and then tried to upload a backup copy to an old FTP server — which had been switched off in January. The report was simply gone.

The change:

2. A few concepts first

Accounting service
Another program, run by the finance team on its own server. The exporter talks to it over the network.
HTTP request
The standard way programs send data to each other over the web. The exporter "posts" the report; the service answers with a status number, 201 meaning "created, all good".
Timeout
How long the exporter waits for an answer before it treats the attempt as failed. Here 10 seconds.
Exception
Python's way of signalling "this went wrong". Code can catch it with try / except and react, instead of stopping.
SendError
The project's own exception for "the accounting service did not take the report" — unreachable, too slow or refusing.
Retry with backoff
Trying again after a failure, waiting a little longer each time (here twice as long). Short outages are bridged quickly, and a struggling service is not flooded with requests.
Outbox
A local folder where reports that could not be delivered are kept as files, like unsent mail.
Log
The program's diary: lines written to a file that operators read when something goes wrong. A warning is less serious than an error.
import
A line at the top of a Python file that makes code from another file or library available.

3. The big picture

The exporter decides what to do; the accounting service only answers. One report crosses between them, up to four times:

Exporter · once a night
export_daily()builds the report
↓
send_with_retry()up to 4 attempts, pauses 2 · 4 · 8 s
↓
client.post()one HTTP request, waits at most 10 s
save_to_outbox()only when all 4 attempts failed: the report is written to outbox/
→POST reportanswer: 201, an error, or silence
Accounting service
201 Createdreport stored; the exporter stops trying
or
error / no answerrestarting, overloaded or offline; the exporter waits and tries again
try 1try 2try 3try 4 2 s4 s8 s 0 s2 s6 s14 s time since the first attempt (ignoring the time each attempt takes) outbox
The worst case, when every attempt fails. The numbers between the dots are the pauses; the numbers below them are the moments of the attempts. As soon as one attempt succeeds, the exporter stops; the outbox is used only after the fourth failure.

The files are explained in this order: config.py sets the limits, retry.py defines the new "try again" rule, and export.py uses it in the nightly job.

4. config.py changed

exporter/config.py

The exporter's settings. Three new values; nothing else changed.

config.pylines 3–7
ACCOUNTING_URL = "https://accounting.example.com/api/reports"
REQUEST_TIMEOUT_S = 101
MAX_ATTEMPTS = 42
FIRST_DELAY_S = 23
OUTBOX_DIR = "outbox"4
  1. 1
    Unchanged, but it matters for the timing: one attempt can take up to 10 seconds before it counts as failed.
  2. 2
    At most 4 attempts: the first one plus three repeats. With the timeout above, the worst case is 4 × 10 s of waiting for answers plus 14 s of pauses, about 54 seconds — long enough to ride out the 30-second nightly restart.
  3. 3
    The first pause is 2 seconds; each later pause doubles (see retry_delays).
  4. 4
    Folder for undelivered reports. A relative name: it is created next to wherever the exporter runs.

5. retry.py new file

exporter/retry.py

The "try again" rule, kept in its own small file. It knows nothing about reports or HTTP: it repeats any send function it is given. That keeps it easy to test (see Tests).

Imports and logger

retry.pylines 2–7, new
import logging
import time1

from .client import SendError2

log = logging.getLogger(__name__)3
  1. 1
    Python's clock library; it provides the real "wait N seconds" function.
  2. 2
    The only failure this file reacts to. Any other error — for example a bug elsewhere in the program — is not retried and surfaces immediately, because repeating it would not help.
  3. 3
    A logger named after this file, so log lines show where they came from.

retry_delays(): how long to pause

retry.pyline 10, new
def retry_delays(attempts, first_s):
    return [first_s * 2 ** i for i in range(attempts - 1)]1
  1. 1
    Builds the list of pauses: first_s times 1, 2, 4, … (2 ** i is "2 to the power i"). There is one pause fewer than attempts, because nobody waits after the last one. With the settings, retry_delays(4, 2) gives [2, 4, 8].

send_with_retry(): try, wait, try again

retry.pyline 15, new
def send_with_retry(send, payload, attempts, first_s, sleep=time.sleep):1
    delays = retry_delays(attempts, first_s)
    for attempt in range(1, attempts + 1):2
        try:
            send(payload)
            return True3
        except SendError as err:
            log.warning("attempt %d of %d failed: %s", attempt, attempts, err)4
            if attempt < attempts:
                sleep(delays[attempt - 1])5
    return False6
  1. 1
    send is the function that does the actual sending, payload what to send. sleep is the waiting function: normally the real clock, but a test can pass a stand-in that only records the pauses, so tests run instantly.
  2. 2
    Counts attempts 1, 2, 3, 4.
  3. 3
    If send returns without an exception, the service took the report: stop at once and report success. No further attempts, no further waiting.
  4. 4
    A failed attempt is a warning, not an error: it is expected now and then and usually followed by a success. The line names the attempt number and the reason, e.g. attempt 2 of 4 failed: HTTP 503.
  5. 5
    Pause before the next attempt — 2, 4, then 8 seconds — but not after the last attempt, when there is nothing left to wait for.
  6. 6
    All attempts failed. The function only reports this; deciding what happens to the report is the caller's job (export_daily).

6. export.py changed

exporter/export.py

The nightly job itself. It now hands the sending to send_with_retry and gets a new helper, save_to_outbox, for the case where every attempt fails.

Imports

export.pylines 2–9
import json1
import logging
import os2

from . import config
from .client import AccountingClient, SendError
from .legacy_ftp import upload_backup3
from .client import AccountingClient4
from .report import build_report
from .retry import send_with_retry
  1. 1
    JSON is the text format the outbox files are written in; it is readable by people and by the accounting service.
  2. 2
    Access to folders and file paths, needed to create the outbox folder.
  3. 3
    The FTP backup is no longer used; its file is deleted (see Not explained line by line).
  4. 4
    SendError is no longer needed here: catching failures moved into retry.py.

export_daily(): the nightly job

export.pylines 14–22
def export_daily(orders, client=None):
    client = client or AccountingClient(config.ACCOUNTING_URL, config.REQUEST_TIMEOUT_S)
    report = build_report(orders)
    try:
        client.post(report)1
    except SendError as err:
        log.error("export failed: %s", err)
        upload_backup(report)2
        return False
    return True
    if send_with_retry(client.post, report, config.MAX_ATTEMPTS, config.FIRST_DELAY_S):3
        return True
    path = save_to_outbox(report)4
    log.error("export failed after %d attempts; report saved to %s", config.MAX_ATTEMPTS, path)5
    return False6
  1. 1
    Before: exactly one attempt. A 30-second restart of the service at the wrong moment was enough to lose the night's report.
  2. 2
    Before: the fallback was the FTP upload — to a server that no longer exists, so the fallback failed too.
  3. 3
    Now: client.post (the function, not a call of it) is handed to send_with_retry together with the settings, 4 attempts starting with a 2-second pause. On success the job ends here, exactly as before.
  4. 4
    Reached only after the fourth failure: the report is kept as a file instead of being dropped.
  5. 5
    One error line in the log that says what happened and where the report is, e.g. export failed after 4 attempts; report saved to outbox/report-2026-03-14.json. This is the line an operator searches for.
  6. 6
    The job still reports failure to whoever started it (the nightly scheduler), so the run shows as failed in its overview.

save_to_outbox(): keep the report as a file

export.pyline 25, new
def save_to_outbox(report, outbox_dir=None):
    outbox_dir = outbox_dir or config.OUTBOX_DIR1
    os.makedirs(outbox_dir, exist_ok=True)2
    path = os.path.join(outbox_dir, f"report-{report['date']}.json")3
    with open(path, "w", encoding="utf-8") as f:
        json.dump(report, f, indent=2)4
    return path
  1. 1
    Uses the folder from the settings unless a caller names another one. The tests use this to write into a temporary folder.
  2. 2
    Creates the folder the first time it is needed; if it already exists, nothing happens.
  3. 3
    The file is named after the report's date, e.g. report-2026-03-14.json, so the files of several failed nights sit side by side and are easy to tell apart. A second failure on the same day would overwrite the first file — harmless, since it holds the same day's report.
  4. 4
    Writes the report as indented JSON, the same content the service would have received.

7. Tests new files

tests/test_retry.py · tests/test_export.py

The tests run the real retry.py and export.py code with pytest. They do not contact the accounting service: a small stand-in send function fails on purpose a chosen number of times, and the waiting is replaced by a list that records the pauses, so no test actually waits.

TestWhat it proves
test_delays_double_each_time4 attempts starting at 2 s give the pauses [2, 4, 8].
test_success_on_third_attemptTwo failures, then success: the result is True and exactly the pauses [2, 4] were taken — no waiting after the success.
test_all_attempts_failFour failures: the result is False and the pauses were [2, 4, 8] — no pause after the last attempt.
test_outbox_file_holds_the_reportThe outbox file is named report-2026-03-14.json and contains exactly the report that was passed in.

8. Not explained line by line

FileWhyWhat changed
exporter/legacy_ftp.pydeletedUploaded a copy of the report to backup.example.com by FTP. That server was switched off in January; the outbox replaces it.
tests/test_retry.py, tests/test_export.pytestsNew; summarised in Tests.

9. Scenarios: which lines run, in order?

A. Normal night: the service answers at once

  1. export_daily builds the report and calls send_with_retry.
  2. retry_delays prepares [2, 4, 8]; attempt 1 calls client.post, the service answers 201.
  3. send_with_retry returns True straight away; export_daily returns True. No pause, no extra log line — the same as before the change.

B. The service is restarting

  1. Attempts 1 and 2 fail with SendError; each writes a warning, then the loop pauses 2 s and 4 s.
  2. About 6 seconds (plus the time of the failed attempts) after the first try, attempt 3 reaches the restarted service and succeeds.
  3. send_with_retry returns True; the report is delivered, the log shows two warnings and no error.

C. The service is down all night

  1. All four attempts fail; the loop pauses 2, 4 and 8 s in between (at most about 54 s in total).
  2. send_with_retry returns False; export_daily calls save_to_outbox, which writes outbox/report-2026-03-14.json.
  3. One error line names the file; export_daily returns False and the scheduler marks the run as failed.

10. Known limits

Outbox files are not re-sent automatically. Someone has to notice the error line and send the file by hand. The change keeps reports from being lost; it does not deliver them later on its own.

If the outbox cannot be written, for example because the disk is full, save_to_outbox raises an error and that night's report is lost as before. The scheduler's own failure log will show it.

The job can now take up to about a minute instead of at most 10 seconds when the service is unreachable. The scheduler allows 15 minutes per job, so this does not collide with anything.

11. Verification status

Unit tests: 4/4 passedpytest; retry rule 3/3, outbox 1/1.
Lint: no findingsruff on exporter/ and tests/.
Test system: openNot yet run against the accounting service's test instance during its restart window.

This is the example page of the explain-changes skill. The project, the issue and the results are invented; the code is in tests/fixtures/reference-example.