Messaging Patterns LabPython · ZeroMQ

Chapter 21

Dispatch with worker credit

Send a job only when a worker has room.

What you’ll learn

Compare how many jobs the broker assigns when workers do and do not get their credit back.

Prerequisite: Forward through a real proxy. Course map →

The situation

A busy worker keeps receiving new jobs because the dispatcher only knows that its connection exists.

A credit is permission to assign one job to a worker. Each worker sends READY to the broker. The broker keeps a list of ready workers and uses one credit when it sends a job. In the starter, DONE gives that worker its credit back.

A credit represents application readiness
  1. WorkerREADYTell the dispatcher the worker can accept one job.
  2. Broker policyAssign one jobRemove that worker’s credit.
  3. WorkerDONE + assignmentTell the dispatcher that the assigned job finished.
  4. Broker policyCredit returnedThe worker becomes eligible again.

Conceptual diagram. The lab uses worker sockets one at a time in a single process. Its dispatcher decides when to return a worker’s permission to take another job.

Before you run

How many credits exist before and after a completed batch?

Run the experiment

Two worker sockets start with one credit each. Jobs 0 through 3 wait. The broker returns one credit to each worker when it receives DONE.

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

The workers alternate in assignments. credits_remaining is 2 after the four replies.

Full output from the original example
{
  "assignments": [
    {
      "job": 0,
      "worker": "w1"
    },
    {
      "job": 1,
      "worker": "w2"
    },
    {
      "job": 2,
      "worker": "w1"
    },
    {
      "job": 3,
      "worker": "w2"
    }
  ],
  "credits_remaining": 2,
  "policy": "Authored one-credit dispatch; workers share a process and no parallel service-time claim is made."
}

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

Try one change

Replace the last line in the editor with result = credits(return_credit=False). Click Run again. Read assignments, credits_remaining and blocked_job. Why did the broker stop before sending the third job?

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 credits(return_credit=True):
    with lab() as socket:
        broker=socket(zmq.ROUTER);broker.bind('inproc://credit');workers={}
        for identity in ['w1','w2']:
            worker=socket(zmq.DEALER);worker.identity=identity.encode();worker.connect('inproc://credit');worker.send(b'READY');workers[identity]=worker
        ready=sorted(broker.recv_multipart()[0].decode() for _ in workers)
        assignments=[]
        blocked_job=None
        for job in range(4):
            if not ready:
                blocked_job=job
                break
            identity=ready.pop(0);broker.send_multipart([identity.encode(),str(job).encode()]);value=workers[identity].recv().decode()
            workers[identity].send_multipart([b'DONE',value.encode()]);reply=broker.recv_multipart()
            if return_credit:ready.append(reply[0].decode())
            assignments.append({'job':int(value),'worker':identity})
        result={'assignments':assignments,'credits_remaining':len(ready),'policy':'Authored one-credit dispatch; workers share a process and no parallel service-time claim is made.'}
        if blocked_job is not None:result['blocked_job']=blocked_job
        return result
Costs, waiting and recovery
AspectWhat to account for
WorkThe broker updates its ready list for each job it assigns and each DONE it receives.
Stored informationThe broker needs an entry for each ready worker. A deployed service may also keep one record per job in progress.
Message pathREADY, jobs and DONE travel as application messages.
WaitingA job waits when there is no credit available.
RecoveryAfter a restart, open connections alone cannot tell the broker which jobs are already complete.

Check your understanding

The broker stops hearing from a worker. Why should it check the job outcome before sending the same job to another worker?

Show hints
  1. Hint 1

    A worker can finish an old job after the broker stops hearing from it.

  2. Hint 2

    What would tell you whether that worker already applied the effect?

Show explanation

Silence only tells the broker that the worker has stopped reporting. The worker may already have finished. Track assignments and completed results by ID, and define how to resolve a missing outcome without repeating a side effect.

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.

Experiment scope

The example sends real messages and uses Python to implement the credit rule. Both workers run one at a time in the same process. Recovery of unfinished work would need a saved assignment record.

ZeroMQ reference · Runtime and model boundaries