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.
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:
- A failed send is repeated: up to 4 attempts in total, with pauses of 2, 4 and 8 seconds between them (14 seconds of waiting in all).
- If all four attempts fail, the report is saved as a file in the
outboxfolder, and an error is logged with the file's path, so someone can send it later. - The dead FTP backup is removed.
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/exceptand 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:
export_daily()builds the reportsend_with_retry()up to 4 attempts, pauses 2 · 4 · 8 sclient.post()one HTTP request, waits at most 10 ssave_to_outbox()only when all 4 attempts failed: the report is written to outbox/POST reportanswer: 201, an error, or silence201 Createdreport stored; the exporter stops tryingerror / no answerrestarting, overloaded or offline; the exporter waits and tries againThe 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
The exporter's settings. Three new values; nothing else changed.
ACCOUNTING_URL = "https://accounting.example.com/api/reports" REQUEST_TIMEOUT_S = 101 MAX_ATTEMPTS = 42 FIRST_DELAY_S = 23 OUTBOX_DIR = "outbox"4
- 1Unchanged, but it matters for the timing: one attempt can take up to 10 seconds before it counts as failed.
- 2At 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.
- 3The first pause is 2 seconds; each later pause doubles (see
retry_delays). - 4Folder for undelivered reports. A relative name: it is created next to wherever the exporter runs.
5. retry.py new file
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
import logging import time1 from .client import SendError2 log = logging.getLogger(__name__)3
- 1Python's clock library; it provides the real "wait N seconds" function.
- 2The 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.
- 3A logger named after this file, so log lines show where they came from.
retry_delays(): how long to pause
def retry_delays(attempts, first_s): return [first_s * 2 ** i for i in range(attempts - 1)]1
- 1Builds the list of pauses:
first_stimes 1, 2, 4, … (2 ** iis "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
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
sendis the function that does the actual sending,payloadwhat to send.sleepis the waiting function: normally the real clock, but a test can pass a stand-in that only records the pauses, so tests run instantly. - 2Counts attempts 1, 2, 3, 4.
- 3If
sendreturns without an exception, the service took the report: stop at once and report success. No further attempts, no further waiting. - 4A 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. - 5Pause before the next attempt — 2, 4, then 8 seconds — but not after the last attempt, when there is nothing left to wait for.
- 6All attempts failed. The function only reports this; deciding what happens to the report is the caller's job (
export_daily).
6. export.py changed
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
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
- 1JSON is the text format the outbox files are written in; it is readable by people and by the accounting service.
- 2Access to folders and file paths, needed to create the outbox folder.
- 3The FTP backup is no longer used; its file is deleted (see Not explained line by line).
- 4
SendErroris no longer needed here: catching failures moved intoretry.py.
export_daily(): the nightly job
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
- 1Before: exactly one attempt. A 30-second restart of the service at the wrong moment was enough to lose the night's report.
- 2Before: the fallback was the FTP upload — to a server that no longer exists, so the fallback failed too.
- 3Now:
client.post(the function, not a call of it) is handed tosend_with_retrytogether with the settings, 4 attempts starting with a 2-second pause. On success the job ends here, exactly as before. - 4Reached only after the fourth failure: the report is kept as a file instead of being dropped.
- 5One 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. - 6The 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
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
- 1Uses the folder from the settings unless a caller names another one. The tests use this to write into a temporary folder.
- 2Creates the folder the first time it is needed; if it already exists, nothing happens.
- 3The 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. - 4Writes the report as indented JSON, the same content the service would have received.
7. Tests new files
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.
| Test | What it proves |
|---|---|
test_delays_double_each_time | 4 attempts starting at 2 s give the pauses [2, 4, 8]. |
test_success_on_third_attempt | Two failures, then success: the result is True and exactly the pauses [2, 4] were taken — no waiting after the success. |
test_all_attempts_fail | Four failures: the result is False and the pauses were [2, 4, 8] — no pause after the last attempt. |
test_outbox_file_holds_the_report | The outbox file is named report-2026-03-14.json and contains exactly the report that was passed in. |
8. Not explained line by line
| File | Why | What changed |
|---|---|---|
exporter/legacy_ftp.py | deleted | Uploaded 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.py | tests | New; summarised in Tests. |
9. Scenarios: which lines run, in order?
A. Normal night: the service answers at once
export_dailybuilds the report and callssend_with_retry.retry_delaysprepares [2, 4, 8]; attempt 1 callsclient.post, the service answers 201.send_with_retryreturnsTruestraight away;export_dailyreturnsTrue. No pause, no extra log line — the same as before the change.
B. The service is restarting
- Attempts 1 and 2 fail with
SendError; each writes a warning, then the loop pauses 2 s and 4 s. - About 6 seconds (plus the time of the failed attempts) after the first try, attempt 3 reaches the restarted service and succeeds.
send_with_retryreturnsTrue; the report is delivered, the log shows two warnings and no error.
C. The service is down all night
- All four attempts fail; the loop pauses 2, 4 and 8 s in between (at most about 54 s in total).
send_with_retryreturnsFalse;export_dailycallssave_to_outbox, which writesoutbox/report-2026-03-14.json.- One error line names the file;
export_dailyreturnsFalseand 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
exporter/ and tests/.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.