polycratia

A repeated callback is a no-op only when it says the same thing

· 9 min read

Every payment rail I have integrated delivers its state changes at least once, which is a polite way of saying that each state change will eventually arrive twice. Spotting the duplicate is easy. Deciding what it means is where money goes missing, because a state machine has to say what a repeat means, and both of the obvious answers lose money.

Treat any repeat as an error and you break the retry. The rail's second delivery is part of the contract, and a handler that raises on it either keeps the rail redelivering forever or, worse, records the withdrawal as failed because the second callback looked like an illegal transition. Treat any repeat as success and you throw away the one thing the callback carries. A withdrawal already sitting at sent with transaction 0xdeadbeef will cheerfully accept a second callback carrying 0xfeedface, overwrite the reference, and leave nothing behind to say the first one ever existed. Reconciliation then has one hash on the chain and a different hash in the database, with no record of which came first.

Only the middle rule holds up: compare the payload. An identical repeat is a no-op that hands back the value which already exists, and a repeat carrying different data is refused as a conflict. I built the withdrawal state machine in withdrawals around exactly that rule. The rule itself is the easy half. Where the comparison has to happen, and what it is allowed to compare, is the half I had to think about.

The constraint: the answer has to live on the value#

Nothing in that package stores a request, holds a connection or owns a clock. Every step takes a value and hands back a new one, and where it gets written down is the caller's decision. That rules out the idempotency strategy most codebases reach for first (look up the row, see what state it is in, decide from there) because there is no row to look at. The repeat has to be answered by the request itself, from the data it already carries, before anything touches storage.

Which turns out to be the better place for it anyway. The rail's payload and the stored payload meet in one function, in one language, with no transaction semantics in the way.

Each transition answers its own replay#

python
def mark_sent(self, reference: str) -> WithdrawalRequest:
    """Record the transfer or transaction reference handed back by the rail."""
    reference = _require_text(reference, "reference")
    if self.state is WithdrawalState.SENT:
        return self._replay(reference=reference)
    return self._move(WithdrawalState.SENT, reference=reference)

Three lines, and the order of them matters. _require_text turns a blank reference into a ValueError before anything else happens: an empty payload counts as malformed, which puts it outside both the repeat case and the conflict case, and it never reaches the state machine. Then comes the replay question. If the request is already SENT, this is a second delivery and _replay decides. The transition table gets consulted only when neither of those applied.

_move is the part every state machine has.

python
def _move(self, state: WithdrawalState, **changes: Any) -> WithdrawalRequest:
    if state not in _TRANSITIONS[self.state]:
        raise InvalidTransition(
            f"withdrawal {self.id} cannot go from {self.state} to {state}"
        )
    return replace(self, state=state, **changes)

That table is where the strict answer lives, which is precisely why the replay check has to come first. sending -> sent is a legal edge. sent -> sent is absent from the table entirely. A second callback routed straight into _move fails, and it fails with a message about an impossible transition for an event that was entirely expected.

Transitions that carry no data can short-circuit as soon as they see their own target state: approve, start_sending and confirm just return self. The ones that carry data cannot, because "already there" is not enough information. mark_sent, reject and fail hand the question to _replay, which compares what the request stored against what was delivered. A match returns self, a mismatch raises InvalidTransition.

The no-op is observable by identity#

A WithdrawalRequest is a frozen dataclass and every transition returns a new value, so the one case where a method hands back the receiver is unmistakable.

python
from decimal import Decimal

from withdrawals import WithdrawalRequest
from withdrawals.models import InvalidTransition

request = WithdrawalRequest(
    id="w-1041",
    amount=Decimal("25.00"),
    currency="USDC",
    destination="0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f",
    requested_by="alice",
)
sent = request.approve().start_sending().mark_sent("0xdeadbeef")

assert sent.mark_sent("0xdeadbeef") is sent     # the same value, not an equal one

try:
    sent.mark_sent("0xfeedface")
except InvalidTransition:
    pass                                        # a different hash is a conflict

is, not ==. That distinction buys you more than it looks like it should. A callback handler that gets the identical object back knows there is nothing to persist, without comparing states or diffing fields, so the duplicate becomes the cheapest path through the code, where otherwise it would be a write that happens to be harmless. And if the request were mutable, the no-op and the silent overwrite would look the same from the outside: the object would seem fine either way, and only the stored row would tell you which one happened.

Order of checks, again: the duplicate outlives the state#

record_approval applies the same priority in a different shape.

python
def record_approval(self, approval: Approval) -> WithdrawalRequest:
    """Add one approval; the same approver recorded twice counts once."""
    if not isinstance(approval, Approval):
        raise TypeError("an approval must be an Approval")
    if approval.approver in self.approvers:
        return self
    if self.state is not WithdrawalState.REQUESTED:
        raise InvalidTransition(
            f"withdrawal {self.id} is {self.state} "
            f"and takes no further approvals"
        )
    return replace(self, approvals=self.approvals + (approval,))

Approvals are only recorded while the request is requested, and after that the request carries the ones it left with. But the duplicate check sits above the state check, and that ordering is the whole argument. A double-clicked approve button, or a retried call that lands after the withdrawal has already moved on, is still the approval that is already recorded, so the call comes back as a no-op and nothing raises. Put the state check first and ordinary retries start returning failures to a compliance operator who did nothing wrong, on an action that already succeeded.

routed works the same way: the rail a routing decision chose returns self when it is already the rail on the request, and it raises only when a different rail turns up.

A replaced reference is still a conflict#

External transactions get stuck, and the answer to a stuck transaction is a replacement. bump applies the three-way rule and then one more clause, refusing an internal rail outright, since a ledger move has no transaction to replace.

python
replacement = sent.bump("0xfeedface")

assert replacement.reference == "0xfeedface"
assert replacement.replaced == ("0xdeadbeef",)
assert replacement.bump("0xfeedface") is replacement   # the bump replays too

Then the awkward delivery arrives. The original transaction's callback, late, carrying 0xdeadbeef. It is a repeat of something that was true once, which is exactly why it must not be accepted.

python
replacement.mark_sent("0xdeadbeef")   # InvalidTransition: not the current reference
replacement.bump("0xdeadbeef")        # InvalidTransition: already replaced

Both refusals fall straight out of comparing the payload against what the request holds now, "not equal to the current reference" and "already in replaced". What makes the comparison trustworthy is enforced in the constructor, up front. __post_init__ refuses a request whose reference also sits in replaced, and _references refuses a replaced tuple containing duplicates. A reference belongs to exactly one slot, so "has this hash already lost" has a single answer at every point in the request's life.

The same rule, one layer down#

python
booked = self._entries.get(entry.withdrawal_id)
if booked is not None:
    if booked != replace(entry, reference=booked.reference):
        raise IdempotencyConflict(
            f"withdrawal {booked.withdrawal_id} is already credited "
            f"as {booked.amount} {booked.currency} to {booked.account}"
        )
    return booked.reference

That is InMemoryLedger.credit. Asking for the same credit again gives you back the reference the first one got, and asking for a different credit under the same withdrawal is a conflict. Look at what it compares: the candidate entry with the booked reference substituted in, because the reference is the one field the ledger generates rather than receives. Everything the caller supplied has to match, and the part the ledger invented is excluded by construction, with no hand-written field list anywhere.

One layer above, submissions.submit(key, request, send) runs the send once per request key and replays what the first call produced for every retry after that. Three layers, one rule, and three different notions of "the payload", the fields a transition carries, the fields a caller supplied, and the request key.

What I would do differently#

A payload conflict and an out-of-order transition both raise InvalidTransition, and they are not the same event. An illegal transition usually means my own code called things in the wrong order. My bug, fix the caller. A payload conflict means two sources disagree about what happened to real money, which lands outside my code, and it is the one case that should page someone. Today a caller has to read the message to tell them apart, and that is the kind of distinction which vanishes into a generic except InvalidTransition in a webhook handler. The conflict deserves its own exception type, the way the ledger already has IdempotencyConflict.

The second thing I would change is comparing free text. The replay rule is only as useful as the payload is canonical, and a human-written reason is not canonical: two independent failure paths describing the same refusal in different words produce a conflict where there is no disagreement. return_funds gets away with it because one piece of code owns the wording. broadcast catches a BroadcastRejected with nothing to say and substitutes a fixed phrase. Outside that path, reject(reason) and fail(reason) would probably be better off comparing a reason code and carrying the prose in a separate field that nobody compares.

Close#

At-least-once reads like a flaw to engineer around. It is the strongest delivery guarantee a rail can actually give you. The part you control is what your own state machine says when that guarantee gets honoured twice. Make each transition answer its own replay before the table is consulted, and make the answer a value you can check by identity, and the second delivery turns from an operational hazard into the dullest branch in the system.

react

$ new-project --brief

or email hey@polycratia.com