Issue #142 · branch fix/export-retry

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.

+ 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: high (for readers with no programming background)

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:

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), attempts and first_s are parameters; in the call retry_delays(4, 2) they become 4 and 2. A parameter written name=value has 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".
for loop
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 / except and 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:

Exporter · once a night
export_daily()adds up the day's orders into the report
↓
send_with_retry()new: up to 4 attempts, pauses 2 · 4 · 8 s
↓ each attempt
client.post()one HTTP request, waits at most 10 s for an answer
save_to_outbox()new, only when all 4 attempts failed: the report becomes a file in 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 under the line 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: 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

exporter/config.py

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.

config.pylines 3–7
ACCOUNTING_URL = "https://accounting.example.com/api/reports"1
REQUEST_TIMEOUT_S = 102
MAX_ATTEMPTS = 43
FIRST_DELAY_S = 24
OUTBOX_DIR = "outbox"5
  1. 1
    Unchanged: the web address of the accounting service, where reports are sent.
  2. 2
    Unchanged, but it matters for the timing: one attempt can take up to 10 seconds before it counts as failed. The _S at the end of the name is a reminder that the unit is seconds.
  3. 3
    At 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.
  4. 4
    The 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.
  5. 5
    The 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

exporter/retry.py

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

retry.pylines 2–7, new
import logging1
import time2

from .client import SendError3

log = logging.getLogger(__name__)4
  1. 1
    Python's standard library for writing log lines.
  2. 2
    Python's clock library. It provides time.sleep, the real "wait this many seconds" function.
  3. 3
    Brings in SendError from the file client.py in 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.
  4. 4
    Creates 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.

retry.pyline 10, new
def retry_delays(attempts, first_s):1
    return [first_s * 2 ** i for i in range(attempts - 1)]2
  1. 1
    Takes two values: how many attempts there will be, and the first pause in seconds.
  2. 2
    Builds a list with one pause for each gap between attempts. Read it from the right: range(attempts - 1) counts i = 0, 1, 2 (three gaps between four attempts); for each i, the pause is first_s * 2 ** i, where 2 ** i means "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.

retry.pyline 15, new
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
  1. 1
    Five inputs: send is the function that does the actual sending; payload is what to send (here, the report); attempts and first_s come from the settings (4 and 2). sleep is 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.
  2. 2
    Works out the pauses once, before the first attempt: [2, 4, 8].
  3. 3
    Repeats 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. 4
    "Try the next lines; if a SendError happens, jump to the except part instead of stopping the program."
  5. 5
    Reached only if send finished without an error, i.e. the service took the report. The function returns True and 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.
  6. 6
    The failure path. err holds the reason, e.g. "HTTP 503" (service unavailable) or "timed out".
  7. 7
    Writes 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.
  8. 8
    Only pause if another attempt follows. After attempt 4 there is nothing left to wait for.
  9. 9
    Pauses 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 - 1 is there because lists count from 0 and attempts from 1.)
  10. 10
    Reached 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

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–11
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__)
  1. 1
    The library for writing JSON, the text format of the outbox files.
  2. 2
    The library for folders and file paths, needed to create the outbox folder and build the file name.
  3. 3
    The FTP fallback is no longer used; its file is deleted (see Not explained line by line).
  4. 4
    Same line as before, minus SendError: catching failures moved into retry.py, so this file no longer needs it.
  5. 5
    Brings 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.

export.pylines 14–22
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
  1. 1
    Receives the day's orders. client=None lets 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.
  2. 2
    Builds the report, e.g. {"date": "2026-03-14", "count": 2, "total": 59.9}.
  3. 3
    Before: exactly one attempt. A 30-second restart of the service at the wrong moment was enough to lose the night's report.
  4. 4
    Before: the fallback was the FTP upload — to a server that no longer exists, so the fallback failed too.
  5. 5
    Now: client.post — the sending function itself, without brackets, so it is handed over rather than called here — goes to send_with_retry together with the report and the settings (4 attempts, first pause 2 s). The if asks: did it come back True?
  6. 6
    Delivered: the job ends here with success, as before the change.
  7. 7
    Reached only after the fourth failure. The report is written to a file; path receives the file's location, e.g. outbox/report-2026-03-14.json.
  8. 8
    One 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 %d and %s are placeholders filled with the number 4 and the path. This is the line an operator searches for.
  9. 9
    The 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.

export.pyline 25, new
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
  1. 1
    Takes the report and, optionally, a folder. Without a folder (None) the next line uses the one from the settings.
  2. 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.
  3. 3
    Creates the folder the first time it is needed. exist_ok=True: if it already exists, carry on without complaint.
  4. 4
    Builds 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 is outbox/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.
  5. 5
    Opens the file for writing ("w") as UTF-8 text. The with block makes sure the file is closed properly afterwards, even if writing fails.
  6. 6
    Writes the report as JSON, indented by 2 spaces so a person can read it. The content is exactly what the service would have received.
  7. 7
    Hands the file's location back to export_daily for the error line.

7. Tests new files

tests/test_retry.py · tests/test_export.py

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.

TestWhat it proves
test_delays_double_each_time4 attempts starting at 2 s give the pauses [2, 4, 8].
test_success_on_third_attemptThe 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_failThe 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_reportFor 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

FileWhyWhat changed
exporter/legacy_ftp.pydeletedUploaded 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.pytestsNew; summarised in Tests.

9. Scenarios: which lines run, in order?

A. A normal night: the service answers at once

  1. At 01:00 the scheduler calls export_daily with 2 orders of 19.90 and 40.00; build_report gives count 2, total 59.9.
  2. send_with_retry prepares the pauses [2, 4, 8] with retry_delays; attempt 1 calls client.post, and the service answers 201 within half a second.
  3. send_with_retry returns True, export_daily returns True. No pause, no log line about failures — exactly as before the change.

B. The service is restarting (the March problem)

  1. 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.
  2. Attempt 2 at 01:00:12 is refused at once: attempt 2 of 4 failed: HTTP 503. Pause 4 s.
  3. Attempt 3 at 01:00:16: the restart is over, the service answers 201. send_with_retry returns True.
  4. 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

  1. 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_retry returns False.
  2. export_daily calls save_to_outbox, which creates outbox/ if needed and writes outbox/report-2026-03-14.json.
  3. Error line: export failed after 4 attempts; report saved to outbox/report-2026-03-14.json. export_daily returns False; the scheduler shows the run as failed.
  4. 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

  1. Suppose an order has no amount and build_report raises an error while adding up. This happens before any sending, so send_with_retry is never reached.
  2. 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

  1. As in C, all four attempts fail; then save_to_outbox tries to write the file, but the disk is full.
  2. open raises 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

Unit tests: 4/4 passedpytest; retry rule 3/3, outbox 1/1.
Lint: no findingsruff (a tool that checks code style and common mistakes) on exporter/ and tests/.
Test system: openNot yet run against the accounting service's test instance during its restart window — the real-world version of scenario B.

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.