Keep the PDF out of your queue
Claim checks keep messages small, idempotent filters survive duplicate delivery, and a few dozen lines of plain Python build the whole pipeline on a laptop.
In brief
- A pipe only moves messages along. All logic lives in the filters, and each filter needs to know only its own input and output schema.
- Write the large file to storage first, then publish the reference. The two operations are not atomic, so filters must be idempotent.
- When the client needs the result within the same request, an asynchronous pipeline is the wrong choice.
In Microsoft’s reference material on pipes and filters, the easiest detail to miss is that the messages passing between steps do not contain the image being processed. They carry only a reference (a claim check) to the image, which sits in storage.
This keeps messages small but leaves another risk unsolved: a queue can deliver the same message more than once. So besides using a claim check, each filter must be idempotent, meaning that receiving a message twice still produces exactly one result. Step 3 deals with this.
On FDE projects, the same problem appears under many names: loan applications, scanned contracts, insurance claims. The client submits a heavy file, the file has to go through several validation and extraction steps, and someone needs to know when processing is finished. This guide builds such a pipeline on a laptop, using only Python’s standard library.
What will you build, and what do you need?
The pipeline has three steps, validate, extract and store, connected by queues. Microsoft’s best-practice guidance on background jobs suggests this approach: split a job with several stages into separate filters and join them with queues. Outside the pipeline is an API that accepts documents and reports their processing status.
All you need is Python 3 and an empty directory. The code below is a simplified simulation: queue.Queue plays the message broker, a local directory plays blob storage, and the API is written as plain functions with no framework. At a client site, you replace each part with the client’s real services and keep the logic unchanged.
Step 1: write the file first, send the ticket second
As Microsoft describes it, a claim check stores a large payload in an external store and sends only a reference through the messaging system. The consumer receives the reference and fetches the payload itself. The order of the two operations matters: the documentation requires the reference to be published only after the payload has been written successfully.
import hashlib, queue, uuid
from pathlib import Path
STORE = Path("blobs"); STORE.mkdir(exist_ok=True)
q_validate, q_extract, q_store, q_dead = (queue.Queue() for _ in range(4))
def put_payload(data: bytes) -> str:
key = hashlib.sha256(data).hexdigest()
(STORE / key).write_bytes(data)
return key
def submit(data: bytes) -> str:
job_id = str(uuid.uuid4())
ref = put_payload(data) # 1. write the payload
q_validate.put({"job_id": job_id, "blob": ref, "schema": "document.v1"}) # 2. publish
return job_id
Check: call submit(b"%PDF-1.4 ...") and look in the blobs/ directory. It should contain exactly one file, while the message in q_validate holds only the job ID, the reference and the schema name.
Using the content hash as the key is deliberate: the same file always yields the same key. If the write is retried, it creates no extra copy.
Microsoft notes that the write and the publish do not happen atomically, so you must plan for both duplicate messages and orphaned payloads: files that were written but whose message was never sent.
Step 2: write one filter template and let pipes only move messages
The Azure documentation is explicit: a pipe does no routing and contains no logic. It only passes one filter’s output to the next filter as input. All processing, including error handling, therefore belongs in the filters.
def run_filter(inbox, outbox, work, max_attempts=3):
msg = inbox.get()
try:
result = work(msg)
if outbox is not None:
outbox.put({**msg, **result})
except Exception:
msg["attempts"] = msg.get("attempts", 0) + 1
(q_dead if msg["attempts"] >= max_attempts else inbox).put(msg)
The except branch handles poison messages. A message that keeps failing is moved to the dead-letter queue instead of being requeued forever, as the background job guidance recommends.
The schema field in the message also has a purpose. Filters know only their own input and output schemas, so once the schema is standardized you can reorder the steps without rewriting them.
Step 3: three filters, the last of them idempotent
DONE = {}
def validate(msg):
data = (STORE / msg["blob"]).read_bytes()
if not data.startswith(b"%PDF"):
raise ValueError("not a PDF")
return {}
def extract(msg):
data = (STORE / msg["blob"]).read_bytes()
return {"size_bytes": len(data)} # simplified: replace with real OCR/extraction
def store(msg):
if msg["job_id"] in DONE: # already processed, so skip
return {}
DONE[msg["job_id"]] = {"blob": msg["blob"], "size_bytes": msg["size_bytes"]}
return {}
The if line in store is there because the queue guarantees only at-least-once delivery, so the same message can arrive several times.
Microsoft also describes a specific case: a filter posts its result and then fails, the message is rerun on another instance, and the result is duplicated.
Any filter that writes to the outside world therefore needs a key to recognize work already done.
Check: run the three filters in order with run_filter(q_validate, q_extract, validate), run_filter(q_extract, q_store, extract) and run_filter(q_store, None, store). Then put the same message into q_store by hand and run the last filter again. len(DONE) should still be 1.
Step 4: find the slowest filter before optimizing
The Azure documentation says the time taken to process a request depends on the slowest filters in the pipeline. Say validate takes 1 second, extract takes 8 seconds and store takes 1 second.
Optimizing validate would change almost nothing. The right move is to run several instances of extract in parallel, all reading from q_extract, a direct benefit of separating the steps with queues.
In the simulation, you can create several threading.Thread objects that all call run_filter on q_extract. Because store is idempotent, the result stays correct even if two workers happen to process the same message.
Step 5: return 202, block duplicates, then return 303
The client should not have to hold a connection open while the pipeline runs. Under the async request-reply pattern, the API checks the request and immediately returns HTTP 202 with Location and Retry-After headers. The client then polls the status endpoint.
JOBS_BY_KEY = {}
def post_document(body: bytes, idem_key: str):
job_id = JOBS_BY_KEY.get(idem_key)
if job_id is None:
job_id = submit(body)
JOBS_BY_KEY[idem_key] = job_id
return 202, {"Location": f"/documents/status/{job_id}", "Retry-After": "5"}
def get_status(job_id: str):
if job_id in DONE:
return 303, {"Location": f"/documents/{job_id}"}
return 200, {"status": "processing"}
Two details in this code prevent two different failures. The Idempotency-Key header lets the backend return the existing status resource when a client submits twice, rather than adding another work item to the queue.
When the job is done, Microsoft advises 303 See Other over 302, because with some clients a 302 can cause the original POST to be sent again.
Check: call post_document twice with the same key. Both calls should return the same Location, and q_validate should gain only one message.
Final exercise: break validate on purpose
This exercise puts all five steps together. Call post_document(b"hello", "bad-key"): the file is still written to blobs/ and the API still returns 202, but the content does not begin with %PDF, so validate raises an error.
Now run run_filter(q_validate, q_extract, validate) three times. On the first two runs, the message returns to q_validate with a rising attempts count; on the third it lands in q_dead. Check that q_dead.qsize() is 1, q_extract is still empty, and get_status for this job still returns processing.
That last result exposes a gap in the simulation: the client will poll forever without learning that the document has failed. The next improvement is to have the status endpoint read the dead-letter queue too and return an error status.
Common mistakes
The first is publishing the message before the file has been fully written, reversing the order the claim check documentation requires. The first filter may then read a reference that points to nothing.
The second is leaving nobody responsible for deleting the payload. The claim check documentation calls for clear ownership of deletion and retention, and for payload retention to match the message’s lifetime, so that a valid reference does not point to deleted data.
The third concerns security: putting a security token in the claim check for convenience. Microsoft advises against it. The last is using the pattern in the wrong place. If processing must finish within the original request, in a request/response style, pipes and filters is a poor fit.
How does this skill show up at a client site?
At a client site, start with a question before writing any code: will users accept a result later, through a status endpoint, or must they have it right away?
The answer decides whether you use a pipeline at all. Next, draw the current steps as filters, mark the slowest one, and ask where the files are stored and who is allowed to delete them.
On your résumé, go beyond “used message queues.” State how you handled duplicate delivery, where you placed the dead-letter queue and who was responsible for cleaning up payloads.
The book Enterprise Integration Patterns poses this question for the pattern: how can a message be processed through several complex steps while those steps stay independent and flexible? The exercise above shows the answer. Each filter knows only its own input and output schemas, so you can reorder filters or add instances without rewriting any of them.
Was this article useful?
Thanks for the feedback!
5 sources
- Pipes and Filters pattern - Azure Architecture Center | Microsoft Learn · 2024-04-10
- Claim Check pattern - Azure Architecture Center | Microsoft Learn · 2026-08-31
- Best Practices for Background Jobs - Azure Architecture Center | Microsoft Learn · 2026-03-30
- Asynchronous Request-Reply Pattern - Azure Architecture Center | Microsoft Learn · 2026-03-30
- Pipes and Filters - Enterprise Integration Patterns