A payment that timed out
Dana's lamp arrived broken, and the shop owes her 40 dollars. You send the refund to the payment provider, and the request times out.
Did the money move? A timeout is your client giving up on waiting. It says nothing about what happened at the other end: the request may never have arrived, or the provider may have paid Dana and lost the answer on its way back. Your next line of code has to do something, and what it does decides whether Dana is paid once, twice or not at all.
Trying again
Here is the usual first answer, in Python. When the provider is slow, try again:
# Refund an order, and try again when the provider is slow to answer.import sysfrom provider import Timeout, refunddef refund_with_retries(order, dollars, attempts=3): for attempt in range(1, attempts + 1): try: return refund(order, dollars) except Timeout: print(f"attempt {attempt} timed out, trying again") raise RuntimeError(f"no answer after {attempts} attempts")print(refund_with_retries(sys.argv[1], int(sys.argv[2])))Show python/provider.py · 21 lines
# A stand-in for the payment provider's client. Nothing leaves this directory:# ledger.txt is the provider's record of money paid out, one line per refund.# The first refund of the day is slow: the provider pays, and its answer# arrives after the client has stopped waiting.from pathlib import PathLEDGER = Path("ledger.txt")class Timeout(Exception): passdef refund(order, dollars): first_of_the_day = not LEDGER.exists() refund_id = "re_" + order.removeprefix("A-") with LEDGER.open("a") as ledger: ledger.write(f"{order} {dollars} {refund_id}\n") if first_of_the_day: raise Timeout("no answer from the provider in 10s") return refund_idpython3 refund.py A-1042 40attempt 1 timed out, trying againre_1042cat ledger.txtA-1042 40 re_1042A-1042 40 re_1042The script reports one refund, and the provider's ledger has two. The first attempt paid Dana, and its answer arrived after the client had stopped listening. The second attempt paid her again.
The opposite answer has the opposite bug. Treat the timeout as a failure and tell Dana to wait, and on the days when the request never reached the provider, nobody pays her at all.
Both answers are reasonable, and plenty of code in production gives one or the other. What neither can do is tell the two kinds of timeout apart, because the client's exception doesn't say whether the request left. When the provider supports an idempotency key, the retry becomes safe: a second request with the same key is recognised and pays nothing. Writing the payments library uses one. Many services have no such key, though, and even with one, somebody has to know that this call needs it.
What a call can return
In Flow, the provider sits behind a Tool library, here a directory called payments with a little Python in it. You don't need to read the Python yet. What the program sees is the library's contract, which flow build writes from that code:
// Generated by flow build from python module payments. Do not edit.// from payments.py: Receiptpub type Receipt { pub refund_id: Text }// from payments.py: PayErrorpub type PayError { Declined { reason: Text }, RateLimited { seconds: Int } }/// Refund an order. A request sent again under the same key pays nothing more.// from payments.py: refundpub flow refund(order: Text, dollars: Int) -> Result<Receipt, PayError>/// The provider's refund for an order, if it has made one.// from payments.py: find_refundpub flow find_refund(order: Text) -> Option<Receipt>refund returns a Result: either Ok with a receipt, or Err with a PayError, the provider's own way of saying no. That much is the provider's answer.
A first try at the program, written as you might write it anywhere:
use "./payments"type Outcome { Refunded(payments.Receipt), Refused(payments.PayError) }pub flow main(order: Text, dollars: Int) -> Outcome = match payments.refund(order, dollars) { Ok(receipt) => Refunded(receipt), Err(error) => Refused(error),}flow check first-try.flowFound 2 errors error[type-mismatch] × expected Receipt, found Result<Receipt, PayError> ╭─[first-try.flow:6:29] 6 │ Ok(receipt) => Refunded(receipt), · ───┬─── · ╰── the payload of `Refunded` expects Receipt ╰──── = Flow constructor ╭─[first-try.flow:3:25] 3 │ type Outcome { Refunded(payments.Receipt), Refused(payments.PayError) } · ────────┬─────── · ╰── the payload of `Refunded` declared here ╰──── = `receipt` is bound here with type Result<Receipt, PayError> ╭─[first-try.flow:6:8] 6 │ Ok(receipt) => Refunded(receipt), · ───┬─── · ╰── bound by this pattern ╰──── Help Pass a value of type `Receipt` as the payload of `Refunded`; use an explicit conversion if needed. error[type-mismatch] × expected PayError, found ToolProblem ╭─[first-try.flow:7:27] 7 │ Err(error) => Refused(error), · ──┬── · ╰── the payload of `Refused` expects PayError ╰──── = Flow constructor ╭─[first-try.flow:3:52] 3 │ type Outcome { Refunded(payments.Receipt), Refused(payments.PayError) } · ────────┬──────── · ╰── the payload of `Refused` declared here ╰──── = `error` is bound here with type ToolProblem ╭─[first-try.flow:7:9] 7 │ Err(error) => Refused(error), · ──┬── · ╰── bound by this pattern ╰──── Help Pass a value of type `PayError` as the payload of `Refused`; use an explicit conversion if needed.The call has one more layer than the contract. Calling refund gives you Result<Result<Receipt, PayError>, ToolProblem>. The inner Result is what the provider said, and the outer one says whether the call got an answer from the provider at all. When it didn't, the Err holds a ToolProblem, which is one of three things:
| Case | What it says | Is sending the request again safe? |
|---|---|---|
NotStarted(reason) |
The Tool's code never started | Yes: nothing was done |
Interrupted(reason) |
The Tool's code started and stopped before it had a value | It may repeat whatever the code had done |
NetworkError { sent, reason } |
The network between the Tool and the service it calls failed | Yes when sent is false; when sent is true, it may repeat what the service did |
Every Tool call in Flow has this outer layer, whether it refunds money, asks a model or reads a file. Nobody added it for payments. The cases are sorted by the one question the retry loop couldn't answer, whether repeating the call could repeat its effect, and that is the question a program has to settle before it sends anything twice.
The cases come from the library, which knows things the program can't. The payments library raises NetworkError with sent set to true when its request went out and the answer never came back, and with sent false when it could not connect at all. Flow writes down whichever one it reports and checks that it is one of the three. It cannot check the report against the world.
Handing the problem back
The smallest change that gets past the checker is a ? after the call, as in Why Flow:
use "./payments"type Outcome { Refunded(payments.Receipt), Declined(payments.PayError) }pub flow main(order: Text, dollars: Int) -> Result<Outcome, ToolProblem> = match payments.refund(order, dollars)? { Ok(receipt) => Ok(Refunded(receipt)), Err(error) => Ok(Declined(error)),}? takes off the outer layer and returns any ToolProblem as main's result.? gives you the inner Result when the call was answered, and otherwise returns the ToolProblem from main straight away. main's own result type has to say so, which is why it is Result<Outcome, ToolProblem>.
PROVIDER tells the stand-in what to do. With nothing set, it does what the first Python attempt saw: it pays, and the answer is lost.
flow run hand-back.flow order=A-1042 dollars=40run 427ca18a0131Err(NetworkError { sent: true, reason: "no answer from the provider in 10s" })427ca18a0131 completed-errThe program returned a declared Err. Inspect its returned value and recorded Tool replies.next: flow replay 427ca18a0131cat payments/ledger.txtA-1042 40 re_1042Dana has been paid once, and the run says plainly that it doesn't know whether she was: the request went out, and nothing came back. Someone has to check with the provider before doing anything else. For the desk in Why Flow, where a failed email can wait for a person, ? is the right choice. For money, the program can do some of that checking itself.
Deciding each case
Here is the program that decides:
use "./payments"type Outcome { Refunded(payments.Receipt), Declined(payments.PayError), NotSent(Text), Unsettled(Text),}pub flow main(order: Text, dollars: Int) -> Outcome = match payments.refund(order, dollars) { Ok(Ok(receipt)) => Refunded(receipt), Ok(Err(error)) => Outcome.Declined(error), // The request never left, so nothing was paid. Err(NotStarted(reason)) | Err(NetworkError { sent: false, reason }) => NotSent(reason), // The money may have moved. Ask the provider; don't send it again. Err(Interrupted(reason)) | Err(NetworkError { sent: true, reason }) => match payments.find_refund(order) { Ok(Some(receipt)) => Refunded(receipt), Ok(None) => Unsettled("no refund on record after: ${reason}"), Err(problem) => Unsettled("the lookup failed too: ${problem}"), },}The outer match has an arm for each kind of outcome. Ok(Ok(receipt)) is a refund that worked and Ok(Err(error)) is one the provider refused. The two problems that promise nothing was sent share an arm, and the run ends NotSent; a person, or the next run, can send it again with nothing to lose. The two problems that might hide a payment share the last arm, which asks the provider with a second Tool, find_refund, instead of sending the refund again.
A few pieces of syntax are new. | lets one arm take two patterns, as long as both bind the same names. NetworkError { sent: false, reason } matches only when sent is false and names the reason. ${reason} puts a value into text. Outcome.Declined names the case by its type, because payments has a Declined too.
Leave out a case and the program doesn't run. The checker wants every case of both layers handled, so nothing in the program reaches the receipt without passing an arm for "the money may have moved".
You can try the program in the browser, where the menu plays the provider:
use "./payments"
type Outcome {
Refunded(payments.Receipt),
Declined(payments.PayError),
NotSent(Text),
Unsettled(Text),
}
pub flow main(order: Text, dollars: Int) -> Outcome = match payments.refund(order, dollars) {
Ok(Ok(receipt)) => Refunded(receipt),
Ok(Err(error)) => Outcome.Declined(error),
// The request never left, so nothing was paid.
Err(NotStarted(reason)) | Err(NetworkError { sent: false, reason }) => NotSent(reason),
// The money may have moved. Ask the provider; don't send it again.
Err(Interrupted(reason)) | Err(NetworkError { sent: true, reason }) => match payments.find_refund(order) {
Ok(Some(receipt)) => Refunded(receipt),
Ok(None) => Unsettled("no refund on record after: ${reason}"),
Err(problem) => Unsettled("the lookup failed too: ${problem}"),
},
}
payments/contract/lib.flow
// Generated by flow build from python module payments. Do not edit.
// from payments.py: Receipt
pub type Receipt { pub refund_id: Text }
// from payments.py: PayError
pub type PayError { Declined { reason: Text }, RateLimited { seconds: Int } }
/// Refund an order. A request sent again under the same key pays nothing more.
// from payments.py: refund
pub flow refund(order: Text, dollars: Int) -> Result<Receipt, PayError>
/// The provider's refund for an order, if it has made one.
// from payments.py: find_refund
pub flow find_refund(order: Text) -> Option<Receipt>
{"Refunded":{"refund_id":"re_1042"}}On your computer, in 1-refund-timed-out from the support-desk project, start the provider's ledger again, since the run above really did refund Dana:
rm payments/ledger.txtThen run the program twice. First with the provider down, so the request never leaves, and then with the lost answer:
PROVIDER=down flow run main.flow order=A-1042 dollars=40run fc3f6fd8dd64NotSent("could not connect to the provider")fc3f6fd8dd64 completednext: flow replay fc3f6fd8dd64flow run main.flow order=A-1042 dollars=40run d899a8bce5e7Refunded(Receipt { refund_id: "re_1042" })d899a8bce5e7 completednext: flow replay d899a8bce5e7cat payments/ledger.txtA-1042 40 re_1042The second run got the same kind of answer as the Python retry loop did, a request that went out and an answer that never came back. This time the program looked the refund up, found it, and ended Refunded with the ledger still at one line.
Why Flow doesn't retry for you
Flow never sends a call again on its own: not after a timeout, not after a crash, not when a run continues the next day. Temporal retries a failed activity by default and asks you to make activities safe to repeat, and a tenacity decorator retries every exception unless you narrow it. Both are reasonable defaults for work that repeats safely, which is most work.
A refund is in the rest. From inside the program the two timeouts in this chapter looked alike up to the moment someone checked, and only one of them had paid Dana. Since a default can't tell them apart either, Flow leaves the second attempt to the program, in an arm a reviewer can read. When you want retries, you write them: a call in a loop is an ordinary Flow function, and the case it matches on says whether trying again can hurt.
The cost is that you write that code even for the calls that would have been safe to repeat, and you write a match where another language would let an exception fly. In return, the next person to read main.flow can see what happens to Dana's money on every path, without running anything.
Keep runs and payments/ledger.txt. What the run was told reads them. To start this chapter again, delete both.
Exercises
- In
main.flow, delete| Err(NetworkError { sent: true, reason })from the last arm and runflow check main.flow. What does the checker ask for? Then put the pattern back as an arm of its own that sends the refund again, run with the lost answer, and count the lines inpayments/ledger.txt. - The
NotSentarm ends the run. Change it to send the refund once more, since nothing was sent. Run withPROVIDER=downtwice in a row: what does the second attempt return, and what would you add so the run can't loop forever? PROVIDER=declinedmakes the provider refuse. Which arm takes it, and what does the run print?- Rewrite
refund.pyso that it only retries when it knows the request never left. What doesprovider.pyhave to tell it, and how would it know?