Messaging Patterns LabPython · ZeroMQ

Chapter 23

Retry with stable identity

Compare repeated requests with repeated charges.

What you’ll learn

Check whether the same request ID produces one recorded charge or two.

Prerequisite: When does a worker own a job?. Course map →

The situation

The handler applies a charge but its ACK is deliberately lost. The client must make a decision with an unknown outcome.

The example uses a list to record charges. The handler records the first charge and withholds its reply. The client checks for the reply for a limited time, then opens a fresh request socket and sends the same request ID again. The handler can use a set of previously seen IDs to avoid recording the same charge twice.

A missing receipt can follow a completed effect
  1. REQ attempt 1charge-aHandler applies 12
  2. Client times outReply deliberately withheldEffect already exists
  3. New REQ · attempt 2same charge-aAuthored duplicate guard
  4. Client receives the replyHandler replies ACK charge-aThe same ID prevents a second effect in the starter

Conceptual diagram. The example keeps processed IDs and applied charges in memory. The run shows both attempts and the entries in the charge list.

Before you run

When the handler skips a charge with an ID it has seen, how many attempts and charges will the output report?

Run the experiment

The client sends request charge-a for 12. The first attempt gets no ACK. The client retries once with the same ID.

For the original example, click Restore code if it is shown, then click Run. Compare your output with the worked result.

Python prepares in the background while you read. First use can download about 71 MiB. Your code runs only when you select Run; each run starts with clean experiment state.

Your edits are saved in this browser when storage is available.

Troubleshooting

If Python stops responding, restart the environment and try again. Your code and last completed result are kept.

Downloads

Worked result

attempts lists two requests. effects contains one charge of 12 because the handler recognizes the repeated ID.

Full output from the original example
{
  "logical_id": "charge-a",
  "attempts": [
    {
      "attempt": 1,
      "reply_available": false,
      "client_socket": "discarded"
    },
    {
      "attempt": 2,
      "reply_available": true,
      "client_socket": "new REQ"
    }
  ],
  "effects": [
    12
  ],
  "total_effect": 12,
  "reply": "ACK charge-a",
  "dedup_store": "Volatile authored set; not a transactional payment service."
}

The build ran the original editor code to produce this output.

Try one change

Replace the last line with result = retries(deduplicate=False) and click Run again. Compare the attempts and effects lists. During which attempt does the extra effect appear?

Inspect the socket implementation

The editor calls this read-only helper. Read all socket helpers or read the separate-process code. The code download includes both files.

def retries(deduplicate=True):
    with lab() as socket:
        router=socket(zmq.ROUTER);router.bind('inproc://retry');seen=set();effects=[];attempts=[]
        for attempt in range(2):
            client=socket(zmq.REQ);client.connect('inproc://retry');client.send_json({'id':'charge-a','amount':12})
            address,delimiter,payload=router.recv_multipart();event=json.loads(payload)
            if not deduplicate or event['id'] not in seen:effects.append(event['amount']);seen.add(event['id'])
            if attempt==0:
                # Deliberately drop the first acknowledgement after applying work.
                available=bool(client.poll(10,zmq.POLLIN));client.close(0)
                attempts.append({'attempt':1,'reply_available':available,'client_socket':'discarded'})
            else:
                router.send_multipart([address,delimiter,b'ACK charge-a']);reply=client.recv().decode()
                attempts.append({'attempt':2,'reply_available':True,'client_socket':'new REQ'})
        return {'logical_id':'charge-a','attempts':attempts,'effects':effects,'total_effect':sum(effects),'reply':reply,'dedup_store':'Volatile authored set; not a transactional payment service.'}
Costs, waiting and recovery
AspectWhat to account for
WorkTwo attempts use more socket and handler work even when they represent one request.
Stored informationThe handler stores one entry for each ID it remembers. Decide how long a request may be retried before removing its entry.
Message pathThe retry uses a new socket and includes the original request ID.
WaitingThe timeout records that a reply did not arrive in time.
RecoveryA production service needs a saved record of the request and effect, or a charge service that recognizes retries itself.

Check your understanding

Would storing the seen-ID flag before an external payment call guarantee exactly one charge?

Show hints
  1. Hint 1

    What happens if the process stops between recording the ID and applying the charge?

  2. Hint 2

    Will the service still recognize the ID after it restarts?

Show explanation

No. A prewritten flag can suppress work that never happened; a later flag can allow duplicates after a crash. Use the service’s real idempotency/receipt contract or a transaction spanning the actual local effect and identity state, with retention and reconciliation.

ReferencesFunction documentation and helper source

References open in a new tab; course helpers are documented separately from library APIs. PyZMQ API links use version 27.3.0.

  • Poll with a deadline and retry deliberately

    The deadline controls waiting. The helper keeps the same application ID and implements duplicate suppression.

  • Course helper implementation

    These are functions written for this course, not additional library APIs. Inspect their parameters, operator calls and authored policies. The source shown is generated from the same Python files packaged with Run and Download Python.

Experiment scope

The client sends and waits on real sockets. The effect list and the record of seen IDs are Python objects that disappear when the process ends.

ZeroMQ reference · Runtime and model boundaries