Order export retry: uncommitted code changes
Every night a small program sends the day's order summary to the accounting department's computer. Until now, if that computer happened to be busy for a moment, the summary was lost. After this change the program tries again a few times, waiting a little longer each time, and if it still cannot get through it keeps the summary in a folder so nothing is lost. This page shows the code function by function and explains every important line.
1. Why this change?
The company's online shop records every order. Once a night, a small program called the order exporter adds up the day's orders into a short summary — the daily report: the date, how many orders, and the total amount — and sends it to the accounting service, the program the finance team uses to book the day's income.
In March the finance team noticed that the reports for three days had never arrived. The program's logs told the story. At the exact moment the exporter ran, the accounting service was restarting for its nightly maintenance, which takes about 30 seconds. The exporter tried once, got no answer, and then tried its fallback: uploading a copy to an old file server (FTP). That server had been switched off in January, so the fallback failed as well, and the report was gone.
What the finance team noticed: missing days in their books. What they will notice after the change: nothing — the report arrives a few seconds later than usual on maintenance nights. Only if the accounting service is down for a long time does someone have to step in, and then the report is waiting for them in a folder.
The change in short:
- A failed send is repeated: up to 4 attempts in total. Between attempts the program pauses 2, then 4, then 8 seconds (14 seconds of pausing in all).
- If all four attempts fail, the report is saved as a file in a folder called
outbox, and one error line in the log says where the file is. - The FTP fallback, which could no longer work, 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 same thing your browser does when it loads a page. The exporter "posts" the report; the service answers with a status number. 201 means "created, all good".
- Timeout
- How long the exporter waits for an answer before it gives up on that attempt. Here 10 seconds.
- Function
- A named piece of code that does one job, written
def name(…):in Python. Other code "calls" it by its name followed by brackets, e.g.retry_delays(4, 2). - Parameter
- A value a function receives when it is called. In
retry_delays(attempts, first_s),attemptsandfirst_sare parameters; in the callretry_delays(4, 2)they become 4 and 2. A parameter writtenname=valuehas a default used when the caller gives none. - Return value
- The result a function hands back with
return. The function stops at that line. True/False- Python's yes and no. Here: "the report was delivered" or "it was not".
if- Runs the indented lines below it only when a condition holds, e.g.
if attempt < attempts:— "if this was not the last attempt". forloop- Repeats the indented lines below it once for each value in a series.
range(1, 5)is the series 1, 2, 3, 4. - List
- An ordered row of values in square brackets, e.g.
[2, 4, 8].delays[0]is the first value (Python counts from 0),delays[1]the second. - Exception
- Python's way of signalling "this went wrong". Normally it stops the program; code can catch it with
try/exceptand react instead. 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 folder where reports that could not be delivered are kept as files, like unsent mail in an e-mail program.
- JSON
- A simple text format for data, readable by people and programs:
{"date": "2026-03-14", "count": 2}. - 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 in this one.
3. The big picture
Two programs are involved. The exporter decides everything — when to send, when to wait, when to give up. The accounting service only answers. The same report travels from left to right up to four times:
export_daily()adds up the day's orders into the reportsend_with_retry()new: up to 4 attempts, pauses 2 · 4 · 8 sclient.post()one HTTP request, waits at most 10 s for an answersave_to_outbox()new, only when all 4 attempts failed: the report becomes a file in 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: first config.py, where the numbers live; then retry.py, the new "try again" rule, which knows nothing about reports; then export.py, the nightly job that uses the rule. Each section only builds on the ones before it, so you never meet something that is explained later.
4. config.py changed
The exporter's settings file. Keeping numbers here, instead of scattering them through the code, means they can be adjusted in one place. Three new settings; nothing else changed.
ACCOUNTING_URL = "https://accounting.example.com/api/reports"1 REQUEST_TIMEOUT_S = 102 MAX_ATTEMPTS = 43 FIRST_DELAY_S = 24 OUTBOX_DIR = "outbox"5
- 1Unchanged: the web address of the accounting service, where reports are sent.
- 2Unchanged, but it matters for the timing: one attempt can take up to 10 seconds before it counts as failed. The
_Sat the end of the name is a reminder that the unit is seconds. - 3At most 4 attempts: the first one plus three repeats. Worst case: 4 attempts × 10 s waiting for an answer + 2 + 4 + 8 s of pauses = 40 + 14 = 54 seconds. The nightly restart takes about 30 seconds, so even an attempt that starts just as the restart begins is followed by one after it has finished.
- 4The first pause is 2 seconds; each later pause doubles (see
retry_delays). Why not just 1 second, many times? Because a service that is struggling should get a moment to recover rather than a stream of requests. - 5The name of the folder for undelivered reports. It is a relative name: the folder is created inside the folder the exporter is started from.
5. retry.py new file
The "try again" rule, in a new small file of its own. It knows nothing about reports, orders or the accounting service: it repeats whatever send function it is given. That keeps it short and easy to test (see Tests), and the same rule could be reused for other deliveries later.
Imports and logger
import logging1 import time2 from .client import SendError3 log = logging.getLogger(__name__)4
- 1Python's standard library for writing log lines.
- 2Python's clock library. It provides
time.sleep, the real "wait this many seconds" function. - 3Brings in
SendErrorfrom the fileclient.pyin the same folder (the leading dot means "same folder"). It is the only kind of failure this file reacts to. Any other error — for example a bug elsewhere in the program — is not retried and shows up immediately, because repeating a bug would only repeat the failure. - 4Creates a logger named after this file (
exporter.retry), so each log line shows which part of the program wrote it.
retry_delays(): how long to pause
A new one-line function that works out the pauses in advance.
def retry_delays(attempts, first_s):1 return [first_s * 2 ** i for i in range(attempts - 1)]2
- 1Takes two values: how many attempts there will be, and the first pause in seconds.
- 2Builds a list with one pause for each gap between attempts. Read it from the right:
range(attempts - 1)countsi= 0, 1, 2 (three gaps between four attempts); for eachi, the pause isfirst_s * 2 ** i, where2 ** imeans "2 to the power i" (1, 2, 4). Worked example with the settings,retry_delays(4, 2): 2 × 1 = 2, 2 × 2 = 4, 2 × 4 = 8, so the result is [2, 4, 8]. There is no pause after the last attempt, so the list has one entry fewer than there are attempts.
send_with_retry(): try, wait, try again
The heart of the change: the loop that makes the attempts.
def send_with_retry(send, payload, attempts, first_s, sleep=time.sleep):1 delays = retry_delays(attempts, first_s)2 for attempt in range(1, attempts + 1):3 try:4 send(payload) return True5 except SendError as err:6 log.warning("attempt %d of %d failed: %s", attempt, attempts, err)7 if attempt < attempts:8 sleep(delays[attempt - 1])9 return False10
- 1Five inputs:
sendis the function that does the actual sending;payloadis what to send (here, the report);attemptsandfirst_scome from the settings (4 and 2).sleepis the waiting function: by default the real clock, but a test can pass a stand-in that only writes down the pauses, so tests finish instantly instead of waiting 14 seconds. - 2Works out the pauses once, before the first attempt: [2, 4, 8].
- 3Repeats the lines below once per attempt.
range(1, attempts + 1)is 1, 2, 3, 4 — numbered from 1 so the log can say "attempt 1 of 4" the way people count. - 4"Try the next lines; if a
SendErrorhappens, jump to theexceptpart instead of stopping the program." - 5Reached only if
sendfinished without an error, i.e. the service took the report. The function returnsTrueand ends at once: no further attempts, no further pauses. Example: if attempt 1 works, there is no waiting at all — exactly like before the change. - 6The failure path.
errholds the reason, e.g. "HTTP 503" (service unavailable) or "timed out". - 7Writes one warning line, for example
attempt 2 of 4 failed: HTTP 503. A warning, not an error: one failed attempt is expected now and then and is usually followed by a success. - 8Only pause if another attempt follows. After attempt 4 there is nothing left to wait for.
- 9Pauses before the next attempt.
delays[attempt - 1]picks the right pause: after attempt 1 →delays[0]= 2 s, after attempt 2 →delays[1]= 4 s, after attempt 3 →delays[2]= 8 s. (The- 1is there because lists count from 0 and attempts from 1.) - 10Reached only when all four attempts failed. The function just reports
False; 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_retry5 log = logging.getLogger(__name__)
- 1The library for writing JSON, the text format of the outbox files.
- 2The library for folders and file paths, needed to create the outbox folder and build the file name.
- 3The FTP fallback is no longer used; its file is deleted (see Not explained line by line).
- 4Same line as before, minus
SendError: catching failures moved intoretry.py, so this file no longer needs it. - 5Brings in the new retry loop.
export_daily(): the nightly job
The scheduler starts this function once a night. The first three lines are unchanged; the part that sends the report is replaced.
def export_daily(orders, client=None):1 client = client or AccountingClient(config.ACCOUNTING_URL, config.REQUEST_TIMEOUT_S) report = build_report(orders)2 try: client.post(report)3 except SendError as err: log.error("export failed: %s", err) upload_backup(report)4 return False return True if send_with_retry(client.post, report, config.MAX_ATTEMPTS, config.FIRST_DELAY_S):5 return True6 path = save_to_outbox(report)7 log.error("export failed after %d attempts; report saved to %s", config.MAX_ATTEMPTS, path)8 return False9
- 1Receives the day's orders.
client=Nonelets a test pass in a fake connection; normally the next line creates the real one with the address and the 10-second timeout from the settings. - 2Builds the report, e.g.
{"date": "2026-03-14", "count": 2, "total": 59.9}. - 3Before: exactly one attempt. A 30-second restart of the service at the wrong moment was enough to lose the night's report.
- 4Before: the fallback was the FTP upload — to a server that no longer exists, so the fallback failed too.
- 5Now:
client.post— the sending function itself, without brackets, so it is handed over rather than called here — goes tosend_with_retrytogether with the report and the settings (4 attempts, first pause 2 s). Theifasks: did it come backTrue? - 6Delivered: the job ends here with success, as before the change.
- 7Reached only after the fourth failure. The report is written to a file;
pathreceives the file's location, e.g.outbox/report-2026-03-14.json. - 8One error line that says what happened and where the report is:
export failed after 4 attempts; report saved to outbox/report-2026-03-14.json. The%dand%sare placeholders filled with the number 4 and the path. This is the line an operator searches for. - 9The job still reports failure to the scheduler that started it, so the night's run is marked as failed in its overview and does not look like a success.
save_to_outbox(): keep the report as a file
A new function that writes one report into the outbox folder.
def save_to_outbox(report, outbox_dir=None):1 outbox_dir = outbox_dir or config.OUTBOX_DIR2 os.makedirs(outbox_dir, exist_ok=True)3 path = os.path.join(outbox_dir, f"report-{report['date']}.json")4 with open(path, "w", encoding="utf-8") as f:5 json.dump(report, f, indent=2)6 return path7
- 1Takes the report and, optionally, a folder. Without a folder (
None) the next line uses the one from the settings. - 2"Use the folder the caller gave, or else
outbox." The tests use this to write into a temporary folder instead of the real one. - 3Creates the folder the first time it is needed.
exist_ok=True: if it already exists, carry on without complaint. - 4Builds the file name from the report's date. The
f"…{…}…"form fills the date into the text: for the report of 14 March 2026 the result isoutbox/report-2026-03-14.json. Several failed nights give several files side by side. A second failure on the same day overwrites the first file, which is harmless because it holds the same day's report. - 5Opens the file for writing (
"w") as UTF-8 text. Thewithblock makes sure the file is closed properly afterwards, even if writing fails. - 6Writes the report as JSON, indented by 2 spaces so a person can read it. The content is exactly what the service would have received.
- 7Hands the file's location back to
export_dailyfor the error line.
7. Tests new files
Tests are small programs that check the real code automatically; they are run with a tool called pytest. They do not contact the accounting service. Instead, a 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 the tests check the exact pauses without actually waiting.
| 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 | The stand-in fails twice ("HTTP 503"), then succeeds: the result is True, and exactly the pauses [2, 4] were taken — no pause after the success. |
test_all_attempts_fail | The stand-in always fails ("timed out"): the result is False, and the pauses were [2, 4, 8] — no pause after the last attempt. |
test_outbox_file_holds_the_report | For the report {"date": "2026-03-14", "count": 2, "total": 59.9} the file is named report-2026-03-14.json and reading it back gives exactly the same report. |
8. Not explained line by line
| File | Why | What changed |
|---|---|---|
exporter/legacy_ftp.py | deleted | Uploaded a copy of the report to the file server backup.example.com by FTP. That server was switched off in January, so the upload could only fail; 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. A normal night: the service answers at once
- At 01:00 the scheduler calls
export_dailywith 2 orders of 19.90 and 40.00;build_reportgives count 2, total 59.9. send_with_retryprepares the pauses [2, 4, 8] withretry_delays; attempt 1 callsclient.post, and the service answers 201 within half a second.send_with_retryreturnsTrue,export_dailyreturnsTrue. No pause, no log line about failures — exactly as before the change.
B. The service is restarting (the March problem)
- Attempt 1 at 01:00:00 gets no answer; after the 10-second timeout it fails. Warning:
attempt 1 of 4 failed: timed out. Pause 2 s. - Attempt 2 at 01:00:12 is refused at once:
attempt 2 of 4 failed: HTTP 503. Pause 4 s. - Attempt 3 at 01:00:16: the restart is over, the service answers 201.
send_with_retryreturnsTrue. - The report is delivered 16 seconds later than usual. The log shows two warnings and no error; nobody has to do anything.
C. The service is down all night
- All four attempts time out after 10 s each; the loop pauses 2, 4 and 8 s in between. After about 54 seconds
send_with_retryreturnsFalse. export_dailycallssave_to_outbox, which createsoutbox/if needed and writesoutbox/report-2026-03-14.json.- Error line:
export failed after 4 attempts; report saved to outbox/report-2026-03-14.json.export_dailyreturnsFalse; the scheduler shows the run as failed. - In the morning an operator sees the failed run, finds the file named in the error line and sends it once the service is back.
D. A different kind of error
- Suppose an order has no amount and
build_reportraises an error while adding up. This happens before any sending, sosend_with_retryis never reached. - The error is not a
SendError, so nothing catches it: the job stops and the scheduler logs the error. That is deliberate — repeating a bug would not help, and hiding it would.
E. The outbox cannot be written
- As in C, all four attempts fail; then
save_to_outboxtries to write the file, but the disk is full. openraises an error that nothing catches; the job stops, the scheduler logs it, and that night's report is lost — the one case the change does not cover (see Known limits).
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 (scenario E). The scheduler's own failure log will show it.
The job can now take up to about a minute (54 s) 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.