<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[lucrolearning]]></title><description><![CDATA[lucrolearning]]></description><link>https://blog.lucrolearning.com</link><image><url>https://cdn.hashnode.com/uploads/logos/6a51387ca8cf56c623690316/4354f2a7-738b-4da6-9295-7beeef9f3bea.jpg</url><title>lucrolearning</title><link>https://blog.lucrolearning.com</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 14 Nov 2026 05:48:29 GMT</lastBuildDate><atom:link href="https://blog.lucrolearning.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building a Task Queue From Scratch]]></title><description><![CDATA[BullMQ and Celery can't share a Redis queue. Here's how to build a job queue from scratch that Node.js and Python both use safely.]]></description><link>https://blog.lucrolearning.com/building-a-task-queue-from-scratch</link><guid isPermaLink="true">https://blog.lucrolearning.com/building-a-task-queue-from-scratch</guid><category><![CDATA[Redis]]></category><category><![CDATA[Python]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[shared_Queue_between_node_and_python]]></category><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Wed, 12 Aug 2026 22:01:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/4377258f-51d1-4d8f-9770-c5c6104a1ad5.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I wanted one thing: a Node.js service and a Python service pulling work from the same queue. Not two queues sitting next to each other, one queue, genuinely shared, so either language could pick up any job.</p>
<p>The obvious move is BullMQ on the Node side and Celery on the Python side, both backed by Redis. That's when I ran into the problem that ended up shaping this entire project: BullMQ and Celery don't actually share anything. Each one writes its own private data format into Redis. A BullMQ producer enqueues a job in a shape only BullMQ understands. A Celery worker looking at that same data sees nothing usable. They both happen to use Redis, the way two people can both happen to use the same filing cabinet while writing in languages neither one can read.</p>
<p>So I built the queue myself, directly on Redis's basic data structures, with one written contract both languages implement independently. No RPC between the two services, no shared library across the language boundary, just an agreed-upon shape for the data sitting in Redis.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/994e217f-bd9d-4007-8dd1-0718ce9f3c9f.jpg" alt="A Node.js API and worker and a Python worker, all reading and writing the same Redis data structures, no direct connection between the two languages" style="display:block;margin:0 auto" />

<h2>The contract that makes this work</h2>
<p>Before writing any code that actually does something, I wrote down exactly what a job looks like as data: its fields, its possible states, and which Redis keys represent the queue. This became the one thing both languages had to agree on, character for character, since they're reading and writing the exact same bytes in Redis, not talking to each other through any API.</p>
<p>A job has four states, not more: <code>pending</code> (waiting), <code>active</code> (a worker has it), <code>completed</code>, <code>dead</code> (given up on). A retry isn't a fifth state. It's a job going back to <code>pending</code> with a delayed availability ; <code>availableAt</code> and one more attempt counted.</p>
<pre><code class="language-typescript">export interface Job&lt;TPayload = unknown&gt; {
  id: string;
  type: string;
  payload: TPayload;
  priority: number;
  status: "pending" | "active" | "completed" | "dead";
  attempts: number;
  maxAttempts: number;
  availableAt: number;      // not claimable until now &gt;= this
  leaseExpiresAt: number | null;
  result: unknown | null;
  error: string | null;
  idempotencyKey: string | null;
}
</code></pre>
<p>The Python side reimplements this as a dataclass with the same fields, snake_case instead of camelCase, since that's idiomatic Python. That mismatch mattered more than I expected: the wire format actually sitting in Redis is camelCase (whatever the TypeScript side writes), so the Python side needs an explicit translation function at the boundary rather than hoping the two naming conventions happen to line up. Small detail, but it's exactly the kind of thing that only shows up once two independent implementations actually try to read each other's data for real.</p>
<h2>Sorting by priority and delay at the same time</h2>
<p>Jobs live in a Redis sorted set, <code>queue:pending</code>, where Redis keeps every member ordered by a numeric score automatically. The obvious score would just be the timestamp: oldest job first. But I needed two things sorted at once, priority (urgent jobs first) and delayed availability (a job retrying after a failure shouldn't be visible until its backoff period ends).</p>
<p>The fix is one formula:</p>
<pre><code class="language-plaintext">score = priority * 10_000_000_000_000 + availableAtMs
</code></pre>
<p>A millisecond timestamp never reaches 13 digits until the year 2286, so multiplying priority by something bigger than any possible timestamp guarantees priority always wins the comparison first. The timestamp only breaks ties between jobs of the same priority. One structure, one query, gives you priority ordering, FIFO within a priority tier, and delayed availability, all at once.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/d69fe6c8-f0ed-48af-b28f-2c989ab05e77.jpg" alt="Two sorted set scores compared: priority 1 delayed 60 seconds still sorts ahead of priority 9 available right now" style="display:block;margin:0 auto" />

<h2>Claiming a job without a race condition</h2>
<p>Here's the part that actually needs care. Two workers, in two different languages, could both look at the queue at nearly the same instant and both decide to take the same job. Whichever fix I used had to make claiming atomic: either a worker gets the job entirely, or it doesn't get it at all, with no window in between where two workers both think they succeeded.</p>
<p>Redis solves this with Lua scripting. A script submitted to Redis runs as one uninterruptible unit, nothing else can execute in the middle of it. I used the <em><strong>claim</strong></em> code as a single <code>.lua</code> script, loaded by both the Node.js and Python clients, not two separate implementations that are supposed to behave identically, the literal same file:</p>
<pre><code class="language-lua">local job_ids = redis.call('ZRANGE', KEYS[1], 0, 0)
if #job_ids == 0 then
  return nil
end

local job_id = job_ids[1]
redis.call('ZREM', KEYS[1], job_id)                    -- remove from pending
redis.call('ZADD', KEYS[2], lease_expires_at, job_id)   -- add to active, with a lease

local job = cjson.decode(redis.call('HGET', 'job:' .. job_id, 'data'))
job.status = 'active'
job.attempts = job.attempts + 1
redis.call('HSET', 'job:' .. job_id, 'data', cjson.encode(job))
return cjson.encode(job)
</code></pre>
<p>Both language clients call this exact script through Redis's <code>EVAL</code> command. Neither one has its own idea of what "claiming" means. There's exactly one definition, and it lives in Redis, not in either codebase.</p>
<h2>What happens when a worker just dies</h2>
<p>A claimed job doesn't just belong to a worker forever. It gets a lease, a deadline (<code>leaseExpiresAt</code>, 30 seconds out by default), like a parking meter. If the worker finishes before the meter runs out, the lease stops mattering. If the worker crashes and the meter runs out with nobody reporting back, a separate process called the reaper notices and puts the job back into circulation, exactly as if it had failed normally.</p>
<p>This wasn't a hypothetical I tested in isolation. During development, a worker genuinely crashed mid-job because of an unrelated bug, leaving a job stranded with an active lease and no one home. When I built the reaper afterward, it found that real, several-hours-old orphaned job and correctly recovered it on the next scan. Nothing staged about that, it was just sitting there.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/58950809-6076-47cb-90f4-95f6a3aef636.jpg" alt="A job's lease expiring with no worker reporting back, and a reaper putting it back into the pending queue" style="display:block;margin:0 auto" />

<h2>Retrying, backing off, and giving up</h2>
<p>When a job fails, whether the handler threw an exception or the reaper found it abandoned, the same function decides what happens next. If it's out of attempts, it moves to a dead letter set for a human to look at later. Otherwise it goes back to <code>pending</code>, but not immediately: the wait grows exponentially with each failure (roughly 1s, 2s, 4s, capped), plus a little random jitter so a burst of simultaneous failures doesn't cause a synchronized retry storm.</p>
<pre><code class="language-python">def _compute_backoff_ms(attempts: int) -&gt; int:
    backoff = min(BASE_BACKOFF_MS * (2 ** (attempts - 1)), MAX_BACKOFF_MS)
    jitter = random.uniform(0, backoff * 0.1)
    return int(backoff + jitter)
</code></pre>
<p>The Lua script that actually moves a job between queues stays deliberately dumb, it doesn't know what a retry is or how backoff math works, it just moves a job from one sorted set to another with whatever data it's handed. All the deciding happens in application code. That split kept the one piece of logic that's genuinely hard to get right (atomic multi-key updates) small and boring, while the part that changes and has actual judgment calls in it (how long to wait, when to give up) stayed in a normal, readable, testable function.</p>
<p>There's a good honesty check worth naming here: the claim script above, as originally written, just grabbed the lowest-scored job unconditionally. That was correct right up until retries existed. Once a failed job could have a future <code>availableAt</code>, a delayed high-priority retry could still sort ahead of an available low-priority job (priority dominates the score, remember), and the naive script would have claimed it immediately, ignoring the fact that it wasn't due yet. The fix was to scan the lowest few candidates in order and claim the first one actually due, rather than blindly taking the minimum. I'd left a comment documenting this exact limitation when I first wrote the script, specifically so it wouldn't get forgotten, and it didn't.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/8cad3058-6e4b-4a2b-9a8c-9cc086f0c45f.jpg" alt="A failed job branching into either a retry with backoff or a dead letter, depending on attempts remaining" style="display:block;margin:0 auto" />

<h2>Not every atomic operation needs a Lua script</h2>
<p>Submitting a job twice by accident, a double click, a retried HTTP request, is a different problem, and it turned out to need much less machinery. An idempotency key only ever touches one Redis key, so Redis's own <code>SET key value NX</code> (set only if the key doesn't already exist) is already atomic on its own:</p>
<pre><code class="language-typescript">const claimed = await redis.set(dedupKey, jobId, "EX", DEDUP_TTL_SECONDS, "NX");
if (claimed !== "OK") {
  // someone already claimed this key, return their job instead of creating a new one
}
</code></pre>
<p>Worth noticing as a general lesson: claiming and failing a job need a Lua script because they touch multiple keys as one operation. Deduplication only touches one key, so a single conditional command is enough. Reach for the heavier tool only when the problem actually needs it.</p>
<h2>Proving it's actually shared, not just two workers that happen to coexist</h2>
<p>The real test was running both workers against the same queue at once and checking, rigorously, whether any job ever got claimed by both. I diffed the claimed-job-id logs from each worker after a mixed run: zero overlap, every time.</p>
<p>The more interesting result was one I hadn't specifically engineered: retries don't stay with the worker that first touched them. A job that failed on its first attempt in Python got picked up and completed on its retry by Node.js, and separately, a job that failed in Node.js had its next attempt claimed by Python. Neither worker knows the other exists. They just both speak the same protocol against the same data, and whichever one is free next gets whatever's next in line.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/9c2372fa-e50b-4930-9ddf-832e837e96c5.jpg" alt="Two workers, Python and Node.js, both claiming from the same queue with zero overlapping job IDs, and a retry crossing from one language to the other" style="display:block;margin:0 auto" />

<h2>What this is actually good for</h2>
<p>This shape of system, thin API accepts and persists, a queue holds work, workers claim and process, isn't specific to any one kind of job. The same pattern shows up behind webhook delivery (retry a flaky endpoint with backoff, dead-letter it if it never recovers), transactional email, report generation, image processing, or slow AI inference behind a "submit and poll" API. The interesting part was never the concept of a queue. It was making the atomicity actually hold up once two independent, mutually unaware programs are reading and writing the same data at the same time, and being honest about the assumptions (like "nothing has a future <code>availableAt</code> yet") that stop being true as the system grows, catching them, and fixing them properly instead of working around them.</p>
]]></content:encoded></item><item><title><![CDATA[Inside the Pipeline: Clustering, Summarizing, and Mapping Themes at Scale]]></title><description><![CDATA[Part 8, the final part of the Beyond FastAPI series.]]></description><link>https://blog.lucrolearning.com/inside-the-pipeline-clustering-summarizing-and-mapping-themes-at-scale</link><guid isPermaLink="true">https://blog.lucrolearning.com/inside-the-pipeline-clustering-summarizing-and-mapping-themes-at-scale</guid><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Mon, 03 Aug 2026 21:34:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/16ef04b8-1314-4bbc-befb-c7e5ffc034f4.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In <a href="https://blog.lucrolearning.com/inside-the-pipeline-fetching-cleaning-and-embedding-survey-data-at-scale">Part 7</a> we followed a batch of raw text responses through fetching, pruning, deduplication, preprocessing, and embedding, and ended up with one clean dataset: every response paired with its vector, old and new responses merged into a single frame ready for the next stage. This post finishes the pipeline. We'll cluster those responses into themes, summarize an arbitrary number of themes into one coherent overview, map each theme onto a fixed set of categories, and then look at the part that ties the whole thing together: how the pipeline knows exactly where to pick up if it gets killed halfway through any of this.</p>
<p>If you've been following the series since Part 1, this is where it all pays off. Everything we built, the thin API that just persists a job and returns, the queue manager that respects concurrency limits, the worker that survives a <code>SIGTERM</code>, exists to give this code room to run for as long as it needs without anyone worrying about the HTTP request that kicked it off.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/735c7ff8-972a-4a3e-80da-61b3ca87941f.jpg" alt="" style="display:block;margin:0 auto" />

<h2>Step 7: Turning Responses into Themes</h2>
<p>Clustering takes four inputs: cleaned responses (for the model to find structure in), raw responses (for humans and the LLM to actually read later), response ids, and the embedding vectors from Part 7. The heavy lifting is done by BERTopic, which itself leans on two other libraries doing very different jobs. UMAP takes the high-dimensional embedding vectors and projects them down into a smaller space where distances are more meaningful for clustering. HDBSCAN then finds dense regions in that reduced space and calls each one a topic.</p>
<p>What's worth paying attention to isn't BERTopic itself, it's how much of its behavior is exposed as plain configuration rather than buried in code:</p>
<pre><code class="language-python">umap_params = {
    "n_neighbors": 20,
    "n_components": 10,
    "min_dist": 0.03,
    "metric": "cosine",
}
hdbscan_params = {
    "min_cluster_size": 5,
    "metric": "euclidean",
    "cluster_selection_method": "eom",
}
</code></pre>
<p>Whether to override BERTopic's defaults at all, whether to reduce the number of topics afterward with hierarchical merging, whether to steer clustering with a predefined set of seed categories: all of that lives in one config dictionary. Nobody has to touch the clustering code itself to tune how granular the resulting themes are.</p>
<p>One detail that's easy to skip past: HDBSCAN doesn't force every point into a cluster. Anything that doesn't fit a dense region gets labeled topic <code>-1</code>, effectively "noise." Left alone, that would mean some responses just vanish from the analysis. The pipeline explicitly reassigns those outliers to their nearest real topic afterward, so every response that made it this far ends up counted somewhere.</p>
<pre><code class="language-python">if -1 in topics:
    topics = self.topic_model.reduce_outliers(cleaned_responses, self.topic_model.topics_)
</code></pre>
<p>Clustering gives you groups of responses and a ranked list of keywords per group. It doesn't give you a readable theme name, a summary, or a sentiment breakdown. That's the next job, and it's handled per topic rather than all at once:</p>
<pre><code class="language-python">async def process_topic(self, topic_id, topic_subset, keywords_scores, topic_name, dataset_id, field_id):
    responses = topic_subset["raw_response"].tolist()
    ids = topic_subset["response_id"].tolist()
    keywords = [kw for kw, _ in keywords_scores]

    refined_data, sentiment_map = await self.llm_refiner_service.refine_topic(
        keywords, responses, ids, field_id
    )

    theme_id, _ = await self.db_service.store_topic_results(
        dataset_id, field_id, topic_name, refined_data, keywords_scores, sentiment_map, topic_id
    )
    return {"theme_id": theme_id, "theme_name": refined_data.get("name", "")}
</code></pre>
<p><code>refine_topic</code> batches the responses in a topic by token budget (using the same batching helper we'll see again in the next section), asks the LLM to name the theme, write a summary, suggest actions, and tag sentiment per response, then merges those pieces back together if the topic was too large for one prompt.</p>
<p>Here's the part that actually matters for reliability. Before any of that LLM refinement happens, the raw topic (its id, keywords, and the response ids in it) gets written to storage and flagged as unrefined:</p>
<pre><code class="language-python">async def store_raw_topic(self, dataset_id, field_id, topic_id, topic_name, keywords, response_ids):
    doc = {
        "datasetId": dataset_id,
        "fieldId": field_id,
        "topicId": topic_id,
        "topicName": topic_name,
        "keywords": keywords,
        "responseIds": response_ids,
        "refined": False,
    }
    return await self.db.insert_one("rawThemes", doc)
</code></pre>
<p>Only once refinement for a given topic finishes does that flag flip to <code>True</code>, alongside the finished theme document. And before doing any new clustering at all, the pipeline checks whether unrefined topics from a previous, interrupted run already exist:</p>
<pre><code class="language-python">unrefined = await self.db_service.get_unrefined_topics(dataset_id, field_id)
if unrefined:
    # skip clustering entirely, resume refinement on just these topics
    ...
</code></pre>
<blockquote>
<p><strong>Key insight:</strong> clustering the whole dataset is expensive and, more importantly, non-deterministic between runs (UMAP and HDBSCAN both involve randomness). If a worker died while refining topic 14 out of 20, you don't want to re-cluster from scratch and risk getting a different set of topics entirely. You want to pick up exactly where you left off, on the exact topics that already exist. Persisting the raw clustering result immediately, before spending a single token on refinement, is what makes that possible.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/978872ae-b7aa-4b1c-bd2b-399b5bc7e7b0.jpg" alt="Raw clustering output is persisted before any LLM refinement begins, so a restart resumes refinement instead of re-clustering" style="display:block;margin:0 auto" />

<h2>Step 8: Summarizing Any Number of Themes into One</h2>
<p>Once every theme has its own name and summary, the pipeline needs a single overall summary across all of them. The problem is that a dataset might produce six themes or six hundred, and there's no way to know that number ahead of time, or to fit six hundred summaries into one prompt.</p>
<p>The fix is a small utility that both the clustering stage and this stage lean on: a token-aware batcher built on <code>tiktoken</code>.</p>
<pre><code class="language-python">class PromptBatcher:
    def __init__(self, model_name="gpt-4.1"):
        self.encoder = tiktoken.encoding_for_model(model_name)

    def count_tokens(self, text):
        return len(self.encoder.encode(text))

    def batch_dynamic_content(self, dynamic_items, prompt_template, dynamic_placeholder_name,
                               constant_placeholders={}, max_total_tokens=7500):
        prompt_tokens = self.count_tokens(prompt_template.format(**constant_placeholders, **{dynamic_placeholder_name: ""}))
        max_batch_tokens = max_total_tokens - prompt_tokens

        batches, current_batch, current_tokens = [], [], 0
        for item in dynamic_items:
            item_tokens = self.count_tokens(item)
            if current_tokens + item_tokens &gt; max_batch_tokens:
                batches.append(current_batch)
                current_batch, current_tokens = [item], item_tokens
            else:
                current_batch.append(item)
                current_tokens += item_tokens
        if current_batch:
            batches.append(current_batch)
        return batches
</code></pre>
<p>It measures the fixed prompt template's token cost once, then greedily packs as many summaries as will fit under the remaining budget, starting a new batch whenever the next item would push it over.</p>
<p>Summarization then becomes a straightforward map, then reduce, then reduce again until there's nothing left to reduce:</p>
<pre><code class="language-python">initial_batches = batcher.batch_dynamic_content(summaries, prompt_template, "summaries_list", max_total_tokens=7500)
partial_summaries = await asyncio.gather(*[call_llm(batch) for batch in initial_batches])

while True:
    merge_batches = batcher.batch_dynamic_content(partial_summaries, prompt_template, "summaries_list")
    if len(merge_batches) == 1:
        final_summary = await call_llm(merge_batches[0])
        break
    partial_summaries = await asyncio.gather(*[call_llm(batch) for batch in merge_batches])
</code></pre>
<p>Six themes might fit in one batch and finish in a single round. Six hundred themes get summarized in groups, and those group summaries get merged together in groups, and so on, until the merge step produces exactly one batch and one final summary comes out. The number of rounds adapts automatically to however many themes actually exist, without anyone having to guess a batch size up front.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/ed0e2418-624e-4438-b196-f176ddb81f74.jpg" alt="Any number of theme summaries gets reduced to one overall summary through repeated token-bounded batching" style="display:block;margin:0 auto" />

<h2>Step 9: Mapping Themes onto a Fixed Taxonomy</h2>
<p>Raw themes and a summary are useful, but the product this pipeline feeds also wants every theme sorted into a small, fixed set of higher-level categories defined once for the whole system, not per analysis. That mapping is the last LLM-driven stage.</p>
<p>Themes go through the same token-aware batching as before, and each batch gets sent to the LLM as a single structured request asking it to score every theme against every category:</p>
<pre><code class="language-python">result = await asyncio.to_thread(
    mapper_service.llm.generate, prompt, parse_json=True,
    response_format={"type": "json_object"}
)

for theme_id, theme_data in result.get("results", {}).items():
    step_scores = theme_data.get("step_scores", {})
    if not step_scores:
        continue
    best_category = max(step_scores.items(), key=lambda x: x[1])[0]
    mapped_themes.add(theme_id)
    await db_service.upsert_theme_step(dataset_id, field_id, best_category, step_scores, theme_id)
</code></pre>
<p>Each theme lands in exactly one category, whichever one it scored highest against. What happens next is the part worth noticing:</p>
<pre><code class="language-python">missing_theme_ids = all_theme_ids - mapped_themes
if missing_theme_ids:
    return missing_theme_ids
</code></pre>
<p>If a theme doesn't come back with a valid score (a malformed LLM response, a theme the model skipped, anything), it isn't quietly dropped. The pipeline tracks exactly which theme ids didn't make it and treats the whole mapping step as incomplete until they do. That set of leftover ids becomes the input to the resume logic covered next.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/d574dc65-c9e5-408a-8d5a-1b43a44c45e2.jpg" alt="Themes are batched and classified against a fixed set of categories, with unmapped themes tracked for retry rather than dropped" style="display:block;margin:0 auto" />

<h2>Step 10: A Pipeline That Remembers Where It Left Off</h2>
<p>Everything above assumes a clean run from start to finish. In practice, workers get killed, machines restart, and jobs get re-enqueued. The last piece of this pipeline is the logic that decides, every time it starts, whether it actually needs to start from scratch at all.</p>
<p>Before touching any data, <code>run()</code> checks the persisted record for this exact dataset, field, and caller scope. If it already reached a finished state, the pipeline exits immediately and does nothing:</p>
<pre><code class="language-python">existing_record = await self.client.fetch_one("analysisResults", {...})
if existing_record and existing_record.get("state") == "DATA_READY":
    return
</code></pre>
<p>If the analysis isn't finished, the pipeline looks at the last meaningful checkpoint it reached, not the last milestone in general, but specifically the last one that represents a safe place to resume from:</p>
<pre><code class="language-python">relevant_checkpoints = ["overall summary generated", "clustering completed", "data combined"]
for milestone in reversed(job_doc["milestones"]):
    if milestone["message"] in relevant_checkpoints:
        return milestone["message"]
</code></pre>
<p>That single value decides which of three paths the run takes:</p>
<pre><code class="language-python">if last_checkpoint == "clustering completed":
    await self.resume_after_clustering()   # themes exist, jump to summarization
    return
elif last_checkpoint == "overall summary generated":
    await self.resume_after_overall_summary()   # summary exists, jump to mapping
    return
# otherwise: run everything from fetch_data onward
</code></pre>
<p><code>resume_after_clustering</code> loads the theme documents that already exist in storage and picks up exactly at summarization, skipping fetching, pruning, embedding, and clustering entirely. <code>resume_after_overall_summary</code> goes one step further: it loads both the themes and whatever mapping records already exist, works out which theme ids are still missing from the mapping (the same kind of set difference we saw at the end of Step 9), and maps only those.</p>
<p>There's one more detail worth calling out, because it's a decision that's easy to get wrong. The embedding cache from Part 7 is keyed only by dataset, field, and response id. It's shared freely across every caller, because raw text and its embedding don't depend on who's asking. Themes, summaries, and mappings are different: which responses a given caller is even allowed to see can differ from one caller to the next, which means the themes that come out of clustering can legitimately differ too. Every one of those derived records, not the embeddings, but everything downstream of clustering, is keyed by dataset, field, <em>and</em> a hash of the caller's access scope. Two callers analyzing the same field never share or overwrite each other's themes, even though they're drawing from the same underlying embedding cache.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/5cfaf0b2-650a-419b-bf8f-da8b29a6b14a.jpg" alt="The pipeline checks its last checkpoint before doing any work, and can resume at summarization or mapping instead of starting over" style="display:block;margin:0 auto" />

<blockquote>
<p><strong>Key insight:</strong> resumability here isn't one mechanism, it's the same idea applied at three different granularities. The watchdog from Part 4 decides whether a worker process is still alive. The top-level checkpoint logic in this section decides which pipeline stage to resume from. And the unrefined/refined flag from Step 7 decides which individual clustering topics still need work. None of these three layers know about each other, and none of them need to. Each one just answers the same question, "how much of the work already happened," at its own scale.</p>
</blockquote>
<h2>Closing the Loop</h2>
<p>Eight parts ago, this series started with a simple observation: an HTTP endpoint has no business blocking on work that takes minutes or hours. Everything since then has been one long answer to that problem, worked out one layer at a time. A thin API that only ever accepts and persists. A queue manager that claims work within limits it actually enforces. A listener loop that turns a database row into a running process. A worker that survives being told to stop mid-task. And now, finally, the pipeline itself: fetching only what's needed, never paying twice for the same embedding, clustering and refining in a way that can be interrupted and picked back up, and a state machine at the very top that always knows exactly how much of the job is already done.</p>
<p>None of the individual pieces are exotic. What makes the whole thing work is that the same handful of principles, bound your concurrency, treat the database as the source of truth, checkpoint before doing expensive work, show up again and again at every layer, from the FastAPI route all the way down to a single clustering topic. That consistency is the actual architecture. Everything else is implementation detail.</p>
<p>Thanks for following along through the whole series.</p>
]]></content:encoded></item><item><title><![CDATA[Inside the Pipeline: Fetching, Cleaning, and Embedding Survey Data at Scale]]></title><description><![CDATA[*Part 7 of the Beyond FastAPI series.*]]></description><link>https://blog.lucrolearning.com/inside-the-pipeline-fetching-cleaning-and-embedding-survey-data-at-scale</link><guid isPermaLink="true">https://blog.lucrolearning.com/inside-the-pipeline-fetching-cleaning-and-embedding-survey-data-at-scale</guid><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Sun, 02 Aug 2026 22:15:46 GMT</pubDate><content:encoded><![CDATA[<p>In <a href="https://blog.lucrolearning.com/making-workers-production-ready">Part 6</a> we closed the loop on the execution platform: a worker process boots in isolation, reports progress through a callback, listens for <code>SIGTERM</code>, and cleans up after itself no matter how it exits. At that point we had a fully production-ready way to <em>run arbitrary long-lived work</em> but we never looked at what that work actually was.</p>
<p>It's time to open that box. Everything from here on happens inside a single method call the worker makes once it has loaded the pipeline class:</p>
<pre><code class="language-python">analysis: PipeLineInterface = _load_analysis(analysis_path, constructor_args)
await analysis.run(progress_cb, stop_event=stop_event)
</code></pre>
<p>That one call <code>ThematicAnalysisPipeline.run()</code> is ten stages deep. It takes a batch of raw, free-text responses and turns them into clustered, summarized, mapped themes. This post covers the first six stages: getting the right slice of responses out of MongoDB, cleaning them, and turning them into embeddings without paying to re-embed anything twice. Part 8 will pick up from there and cover clustering, LLM summarization, and the mapping stage along with the resumability logic that lets a killed job pick up mid-clustering instead of starting over.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/87cc8edd-83a6-4208-98f3-7a5a8be2df9b.webp" alt="" style="display:block;margin:0 auto" />

<p>Every stage below reports a milestone through the same <code>progress_cb</code> we introduced in Part 5 <code>"data fetched"</code>, <code>"data prune completed"</code>, <code>"embeddings loaded"</code>, and so on. That's not just a progress bar for the frontend; each milestone also resets the watchdog's staleness clock from Part 4. A stage that takes forty minutes to embed ten thousand responses is fine. A stage that goes forty minutes <em>without reporting anything</em> looks exactly like a hung process, and the watchdog will kill it. Keep that in mind as we go it's why almost every stage below is chunked and batched rather than done in one giant pass.</p>
<h2>Step 1: Fetching the Right Slice of Data</h2>
<p>The pipeline doesn't operate on an entire dataset at once. It operates on one field within one dataset, seen through one caller's access scope. <code>fetch_data</code> delegates to a helper that builds a MongoDB query against the response records and pulls out just the answers for the target field:</p>
<pre><code class="language-python">query = {"datasetId": dataset_id}

if filters:
    and_conditions = []
    for field_id, values in filters.items():
        and_conditions.append({
            "answers": {
                "$elemMatch": {
                    "fieldId": field_id,
                    "values": {"$in": values[0].split("_")}
                }
            }
        })
    query["$and"] = and_conditions

records = await db_client.fetch_many(
    "responses", query, {"answers": 1, "_id": 1}
)
</code></pre>
<p>Two details here are easy to miss but matter a lot in practice:</p>
<p><strong>Multi-value answers get split into pseudo-records.</strong> An open-ended field like "what could we improve?" often comes back as a single comma-separated blob <em>"better pay, more flexible hours, less micromanagement."</em> Rather than treating that as one response, the pipeline splits it and gives each fragment its own synthetic ID (<code>{response_id}_{index}</code>), so three distinct themes don't get flattened into one incoherent response during clustering later. The split isn't naive string-splitting on commas, either a small guard list of conjunctions (<code>NO_SPLIT_WORDS</code>: "and", "because", "however", "for example"...) prevents cutting a sentence like <em>"pay is fine, but the hours are brutal"</em> into two meaningless halves.</p>
<p><strong>Hierarchy-scoped access is a BFS, not a flat lookup.</strong> When a dataset has organizational-hierarchy scoping enabled, a small resolver walks down from the caller's scope through a parent-scope field on each record, breadth-first, collecting every descendant scope before the main query runs. Someone scoped to one business unit should see that unit and everything beneath it but the query can't express "everything beneath it" directly, so the pipeline has to compute the full set of scopes first and filter against it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/2bb6f177-dde7-432e-90ad-0a569864f175.jpg" alt="" style="display:block;margin:0 auto" />

<p>The output isn't a list of strings , it's a <code>pandas.DataFrame</code> with <code>response_id</code>, <code>response</code>, and <code>redacted_response</code> columns, plus the raw set of <code>response_ids</code>. That set matters more than it looks: it's the key the next two stages use to avoid redoing work.</p>
<h2>Step 2: Pruning Garbage Before It Costs You Anything</h2>
<p>Free-text fields attract noise: <code>"n/a"</code>, <code>"...."</code>, <code>"xxxxx"</code>, single characters, and the occasional string of keyboard mashing. None of that is worth an embedding call or a clustering pass, so <code>prune_data</code> filters it out early before any paid API call touches it.</p>
<p><code>DataFramePruner._is_meaningful</code> runs each response through a small stack of cheap filters, ordered from cheapest to most expensive:</p>
<pre><code class="language-python">def _is_meaningful(self, value: str) -&gt; bool:
    v = value.strip()

    if self.pattern.match(v):          # "na", "n/a", "tbd", "--", single letters...
        return False
    if self.gibberish_pattern.match(v):  # "aaaa", "!!!!", repeated chars
        return False

    if self.ai_detector:
        result = self.ai_detector(v[:512], top_k=None)
        gibberish_score = next((r['score'] for r in result if r['label'].lower() == 'noise'), 0.0)
        if gibberish_score &gt; 0.8:
            return False

    if self.use_nlp_filter:
        meaningful_words = [t for t in tokens if t not in self.stopwords]
        if len(meaningful_words) == 0:   # response is *only* stopwords
            return False

    return True
</code></pre>
<p>The two regexes catch the obvious junk for free. The optional AI detector a locally-loaded gibberish-classification model, only wired up if <code>AI_DETECTOR_PATH</code> is set , it catches subtler noise the regexes miss.</p>
<p>The stopword check catches the residual case where a response is grammatically valid but semantically empty, like <em>"it is what it is."</em></p>
<p>Pruning isn't just cosmetic it's a gate. If fewer than 50 responses survive, the pipeline stops outright and marks the run <code>INSUFFICIENT_DATA</code> instead of running an entire clustering pipeline on a handful of data points:</p>
<pre><code class="language-python">if len(df_pruned) &lt; 50:
    await self.update_state(self.dataset_id, self.field_id, "INSUFFICIENT_DATA")
    return None, response_info
</code></pre>
<blockquote>
<p><strong>Key insight:</strong> every expensive stage downstream: embedding, clustering, LLM refinement costs real money and real time per response. Pruning aggressively at the top of the funnel isn't an optimization, it's what makes the economics of the rest of the pipeline work.</p>
</blockquote>
<h2>Step 3: Don't Pay to Embed the Same Response Twice</h2>
<p>This is the stage I'd call the most architecturally interesting of the six, and it's easy to walk right past it. Before generating a single new embedding, the pipeline checks what it's already embedded for this exact dataset/field pair, using the <code>response_ids</code> collected back in Step 1:</p>
<pre><code class="language-python">async def fetch_with_retry(chunk):
    async with semaphore:
        return await self.client.fetch_many(
            "embeddings_new",
            {"datasetId": self.dataset_id, "fieldId": self.field_id,
             "responseId": {"$in": chunk}},
            {"_id": 0, "responseId": 1, "processedResponse": 1, "embedding": 1}
        )

tasks = [fetch_with_retry(value_list[start:start + batch_size])
          for start in range(0, len(value_list), batch_size)]
results = await asyncio.gather(*tasks)
</code></pre>
<p>Response IDs are chunked into batches of 1,000, fetched concurrently under a semaphore (so a dataset with fifty thousand responses doesn't fire fifty thousand-ID queries or fifty unbounded ones), with exponential backoff plus jitter on failure. The result is two dictionaries <code>existing_responses</code> and <code>existing_embedding_map</code> keyed by response ID.</p>
<p><code>split_new_existing</code> then does exactly what it sounds like: any response already found gets routed into <code>df_existing</code> (its previously-computed clean text gets reattached), and everything else goes into <code>df_new</code>; the only rows that will actually touch the embedding API in Step 5.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/f1541ea0-8448-4669-ac6c-9ea22d5f3d8b.jpg" alt="" style="display:block;margin:0 auto" />

<p>This is a cache lookup, functionally, but it's worth naming as a distinct architectural decision rather than an implementation detail. Datasets get re-analyzed as new responses trickle in over time. Without this step, every re-run would re-embed every response ever collected, and embedding cost would grow without bound instead of scaling with <em>new</em> responses only.</p>
<h2>Step 4: Normalizing Text for the Model</h2>
<p>Only <code>df_new</code> the responses that survived pruning and aren't already embedded goes through <code>TextPreprocessor</code>. The interesting design choice here is that the preprocessing steps are configuration, not code:</p>
<pre><code class="language-python">self.step_funcs = {
    "remove_placeholder": self._remove_placeholders,
    "lowercase": self._lowercase,
    "remove_punctuation": self._remove_punctuation,
    "remove_whitespace": self._remove_whitespace,
    "remove_stopwords": self._remove_stopwords,
    "lemmatize": self._lemmatize,
}
</code></pre>
<p><code>PREPROCESS_CONFIG["steps"]</code> is just a list of strings naming which functions to run and in what order:</p>
<pre><code class="language-python">"steps": ["remove_placeholder", "lowercase", "remove_punctuation",
          "remove_whitespace", "lemmatize", "remove_stopwords"]
</code></pre>
<p><code>transform()</code> walks that list and calls <code>self.step_funcs[step]</code> for each name, batch by batch. Want to drop lemmatization for a faster run, or reorder stopword removal to happen before lowercasing? That's a config change, not a code change ; the same "swap behavior without touching the class" instinct we saw with <code>PIPELINE_CLASS_PATH</code> dynamic loading back in Part 5, just applied one level down.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/d141a32f-5852-4279-805b-70d19a2c9674.jpg" alt="" style="display:block;margin:0 auto" />

<p>Lemmatization is the expensive step it runs every response through spaCy. The preprocessor checks for a GPU up front and falls back to spreading the work across CPU cores if theisn't one:</p>
<pre><code class="language-python">if self.use_gpu_if_available and torch.cuda.is_available():
    spacy.require_gpu()
    n_process = 1
else:
    spacy.require_cpu()
    n_process = multiprocessing.cpu_count() - 1

self.nlp = spacy.load(self.spacy_model, disable=["ner", "parser"])
</code></pre>
<p>Note the <code>disable=["ner", "parser"]</code> the pipeline only needs lemmas and part-of-speech tags, so named-entity recognition and dependency parsing (two of spaCy's moexpensive components) aswitched off entirely. It's a small line, but on a dataset with tens of thousands of responses it's the difference between a preprocessing pass that takes seconds and one that takes minutes.</p>
<h2>Step 5: Generating Embeddings Without Melting the API</h2>
<p>Only truly new responses reach this stage, and it reuses a pattern this codebase clearly likes: a thin interface with swappable providers.</p>
<pre><code class="language-python">class BaseEmbeddingProvider(ABC):
    @abstractmethod
    def embed_data(self, texts: List[str]) -&gt; List[List[float]]:
        pass
</code></pre>
<pre><code class="language-python">def get_embedding_provider(provider: str, model_type: str = None, **kwargs):
    provider = provider.lower()
    if provider == "openai":
        return OpenAIEmbedding(model=model_type, **kwargs)
    elif provider == "vertex":
        return VertexEmbedding(model=model_type, **kwargs)
    elif provider == "huggingface":
        return HuggingFaceEmbedding(model_type=model_type)
    elif provider == "bedrock":
        return BedrockEmbedding(model_id=model_type, **kwargs)
</code></pre>
<p>This is the same shape as the <code>PipeLineInterface</code> / dynamic-import pattern from Part 5, just scoped to one concern: which embedding backend to call. Config picks <code>openai</code> / <code>text-embedding-3-large</code> today; swapping to a self-hosted HuggingFace model for cost reasons is a config change, not a rewrite of the pipeline.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/59e6c039-37ef-45f5-b4c0-fc7ef01a0d83.jpg" alt="" style="display:block;margin:0 auto" />

<p>The orchestration around the actual API calls is where the concurrency discipline from earlier posts shows up again this time applied to an external, rate-limited API instead of internal processes:</p>
<pre><code class="language-python">async def process_chunk(start_idx, end_idx):
    chunk_raw = raw_responses[start_idx:end_idx]
    async with self.api_semaphore:
        embeddings = await asyncio.to_thread(
            self.embedding_service.generate_embeddings, chunk_raw
        )
    async with self.db_semaphore:
        await self.db_service.save_embeddings(embeddings, ..., collection_name)
    return embeddings

tasks = [process_chunk(i, min(i + self.chunk_size, len(raw_responses)))
          for i in range(0, len(raw_responses), self.chunk_size)]
chunk_results = await asyncio.gather(*tasks)
</code></pre>
<p>Responses are split into chunks of 200, and two independent semaphores bound the work: one caps how many embedding API calls are in flight at once, the other caps concurrent MongoDB writes. They're deliberately separate the API and the database have completely different capacity limits, and coupling them would mean tuning for whichever one is more fragile.</p>
<p><code>EmbeddingService.generate_embeddings</code> adds its own retry loop with backoff on top of this so a transient rate-limit error on one chunk doesn't take down the whole batch, it just delays that one chunk's <code>asyncio.gather</code> slot.</p>
<h2>Step 6: Recombining Old and New</h2>
<p>The last stage in this post is the shortest, but it's where the two paths from Step 3 rejoin:</p>
<pre><code class="language-python">def combine_data_for_clustering(self, df_new_processed, df_existing, new_embedding_map, existing_embedding_map):
    df_all = pd.concat([df_new_processed, df_existing], ignore_index=True)

    embedding_vectors = [
        new_embedding_map[rid] if rid in new_embedding_map else existing_embedding_map.get(rid)
        for rid in df_all["response_id"]
    ]

    df_all['redacted_response'] = df_all['redacted_response'].combine_first(df_all["response"])
    df_all.rename(columns={"redacted_response": "response"}, inplace=True)

    return df_all, embedding_vectors
</code></pre>
<p>Two things worth calling out. First, the embedding vector list is rebuilt by looking up each response ID in <em>either</em> map this is the point where "responses we just embedded" and "responses we already had embeddings for" become a single aligned dataset, ready to hand to clustering as one <code>responses</code>/<code>embeddings</code> pair. Second, and easy to miss: <code>combine_first</code> means the <strong>redacted</strong> version of a response wins whenever one exists, falling back to the raw response only when no redaction was recorded. Every downstream stage clustering, LLM refinement, summarization sees the PII-safe version of the text, not the original.</p>
<h2>What to Notice Across All Six Steps</h2>
<p>Look back across fetch → prune → dedupe → preprocess → embed → combine and a few patterns repeat on purpose:</p>
<ul>
<li><p><strong>Provider abstraction shows up twice</strong> (embeddings here, LLMs in Part 8) using the same "interface + factory function" shape as the dynamic pipeline loading from Part 5. It's the same idea applied at three different layers of the system.</p>
</li>
<li><p><strong>Every I/O-bound stage is chunked and semaphore-bounded</strong> response ID lookups, embedding API calls, and DB writes all cap their own concurrency independently, because each has a different real-world capacity limit.</p>
</li>
<li><p><strong>Config, not code, controls behavior</strong> preprocessing steps, batch sizes, chunk sizes, and provider choice all live in plain dictionaries in <code>pipelines/config/</code>, not scattered through the pipeline logic.</p>
</li>
<li><p><strong>Cheap filters run before expensive ones</strong> regex before AI-model inference in pruning; a cache lookup before any paid API call in the embedding stage.</p>
</li>
</ul>
<p>None of this is exotic engineering. It's the boring, disciplined kind bound your concurrency, cache what you can, gate expensive work behind cheap checks applied consistently at every stage. That discipline is exactly what makes it possible for a job to survive a <code>SIGTERM</code> mid-embedding and pick back up later without corrupting state or double-billing an API.</p>
<p>That survivability becomes the whole story in Part 8, where we cover the three stages that actually produce a "theme": clustering, LLM-based topic refinement, map-reduce summarization across an arbitrary number of themes, and the resume logic that lets the pipeline recognize "clustering already finished, just re-enter at the mapping stage" instead of starting from <code>fetch_data</code> again.</p>
]]></content:encoded></item><item><title><![CDATA[Making Workers Production Ready]]></title><description><![CDATA[From dependency injection to graceful shutdown: engineering resilient worker processes]]></description><link>https://blog.lucrolearning.com/making-workers-production-ready</link><guid isPermaLink="true">https://blog.lucrolearning.com/making-workers-production-ready</guid><category><![CDATA[Python]]></category><category><![CDATA[backend]]></category><category><![CDATA[workers]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Sun, 02 Aug 2026 11:45:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/aeb3c266-e028-4aeb-9cae-40ad81a0c7c3.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>The Worker Has Been Loaded… Now What?</h2>
<p>In the <a href="https://blog.lucrolearning.com/inside-the-worker-building-a-resilient-ai-execution-platform">previous</a> article we followed a job from the Queue Manager into a newly created worker process. By this point our worker has:</p>
<ul>
<li><p>Started a new Python process</p>
</li>
<li><p>Created its own asyncio event loop</p>
</li>
<li><p>Connected to MongoDB</p>
</li>
<li><p>Dynamically loaded the configured analysis pipeline</p>
</li>
</ul>
<p>At this stage the worker is finally ready to execute the actual business logic. It might be tempting to simply instantiate the pipeline and call:</p>
<pre><code class="language-python">await pipeline.run()
</code></pre>
<p>That would certainly work. But an execution platform needs much more than simply running code.</p>
<p>The worker needs a way to:</p>
<ul>
<li><p>Communicate progress</p>
</li>
<li><p>Manage external resources</p>
</li>
<li><p>Terminate gracefully</p>
</li>
<li><p>Avoid resource leaks</p>
</li>
<li><p>Remain independent from global application state</p>
</li>
</ul>
<p>These concerns are just as important as the analysis itself.</p>
<p>In this article we'll explore how those responsibilities are handled.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/8af4b4cd-684a-4d48-932d-5e8839c4ef13.webp" alt="" style="display:block;margin:0 auto" />

<h2>Dependency Injection Instead of Global State</h2>
<p>One design decision that often goes unnoticed is how the analysis pipeline receives its dependencies.</p>
<p>Rather than importing global objects, everything required by the pipeline is injected during construction.</p>
<pre><code class="language-python">constructor_args = {
    "survey_id": payload["survey_id"],
    "question_id": payload["questionId"],
    "logger": logger,
    "register_thread": register_thread,
    "register_process": register_process,
}
</code></pre>
<p>The worker knows how to construct the pipeline, but it doesn't dictate how the pipeline should behave.</p>
<p>This approach has several advantages.</p>
<h3>Loose Coupling</h3>
<p>The pipeline doesn't need to know where the logger came from. It simply receives one. The same applies to thread registration, subprocess registration, configuration, or database services.</p>
<h3>Easier Testing</h3>
<p>Because dependencies are injected rather than imported globally, unit tests can substitute lightweight mock implementations. Instead of starting real worker processes, tests can inject fake loggers and in-memory services.</p>
<h3>Reusable Pipelines</h3>
<p>Nothing inside the pipeline depends on FastAPI, Queue Manager or multiprocessing.</p>
<p>The pipeline could be executed from:</p>
<ul>
<li><p>A worker process</p>
</li>
<li><p>CLI/Terminal based execution</p>
</li>
<li><p>Another orchestration system</p>
</li>
<li><p>Notebook</p>
</li>
</ul>
<p>without modification.</p>
<p>This separation keeps the orchestration layer independent from the business logic.</p>
<h2>Reporting Progress</h2>
<p>AI workloads can easily take several minutes. Some may process thousands of comments. Others may call hundreds of external APIs. Without progress reporting the client has no visibility into what is happening.</p>
<p>Instead of waiting silently, the worker continuously publishes milestones back to MongoDB.</p>
<pre><code class="language-python">async def progress_cb(message, percentage):
    await db_client.post_milestone(message, percentage)
</code></pre>
<p>The pipeline receives this callback during execution.</p>
<p>Whenever meaningful progress occurs, it simply calls</p>
<pre><code class="language-python">await progress_cb("Generating embeddings", 35)
</code></pre>
<p>or</p>
<pre><code class="language-python">await progress_cb("Clustering comments", 70)
</code></pre>
<p>The pipeline never needs to know where those updates are stored. It simply reports progress. The worker takes responsibility for persistence. This is another example of separating execution from business logic.</p>
<h2>Why Callbacks Instead of Database Calls?</h2>
<p>The answer is abstraction.</p>
<p>Imagine replacing MongoDB tomorrow with Redis, PostgreSQL or an event bus.</p>
<p>If every pipeline contained database code, every implementation would need to change.</p>
<p>Instead, the pipeline exposes intent:</p>
<blockquote>
<p>"Progress has reached 60%."</p>
</blockquote>
<p>The worker decides how that information should be persisted.</p>
<p>Keeping responsibilities separated makes the pipeline significantly easier to evolve.</p>
<h2>Graceful Shutdown</h2>
<p>Long-running AI jobs must also be interruptible: A deployment may require workers to stop , a watchdog may detect a stalled process or an administrator may terminate a runaway job.</p>
<p>If we simply kill the process immediately, that can leave:</p>
<ul>
<li><p>Partially written data</p>
</li>
<li><p>Orphaned subprocesses</p>
</li>
<li><p>Unfinished threads</p>
</li>
<li><p>Inconsistent state</p>
</li>
</ul>
<p>Instead the worker listens for operating system signals.</p>
<pre><code class="language-python">signal.signal(SIGTERM, handle_sigterm)
</code></pre>
<p>When the operating system sends <code>SIGTERM</code>, the handler doesn't terminate immediately.</p>
<p>Instead it requests a graceful shutdown.</p>
<pre><code class="language-python">stop_event.set()
</code></pre>
<p>The pipeline periodically checks this event. If shutdown has been requested it can complete its current operation, release resources and exit safely.</p>
<p>This gives the worker an opportunity to leave the system in a consistent state before terminating.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/917636ec-d4b2-4982-b4dc-bec2aeeb8135.webp" alt="" style="display:block;margin:0 auto" />

<h2>Cleanup Matters</h2>
<p>One of the easiest ways to destabilise production systems is forgetting about resources created during execution.</p>
<p>Analysis pipelines often create:</p>
<ul>
<li><p>Background threads</p>
</li>
<li><p>Subprocesses</p>
</li>
<li><p>External tools</p>
</li>
</ul>
<p>Those resources don't automatically disappear when your analysis completes. To avoid leaks the worker keeps track of everything it creates. Whenever the pipeline starts a thread it registers it. Whenever it launches a subprocess it registers that as well. When execution finishes the worker performs one final cleanup pass.</p>
<pre><code class="language-python">cleanup_subtasks()
</code></pre>
<p>Internally this function:</p>
<ul>
<li><p>Terminates child processes</p>
</li>
<li><p>Waits for graceful shutdown</p>
</li>
<li><p>Joins background threads</p>
</li>
<li><p>Clears internal registries</p>
</li>
</ul>
<p>Only after cleanup completes does the worker exit.</p>
<p>This guarantees that every job leaves the system exactly as it found it.</p>
<h2>Putting it all together</h2>
<p>By now our worker has become much more than a background process.</p>
<p>It is a complete execution environment.</p>
<pre><code class="language-text">Worker Starts
      │
      ▼
Load Pipeline
      │
      ▼
Inject Dependencies
      │
      ▼
Execute Analysis
      │
      ▼
Report Progress
      │
      ▼
Handle Shutdown Requests
      │
      ▼
Cleanup Resources
      │
      ▼
Exit
</code></pre>
<p>Every worker is isolated.</p>
<p>Every worker owns its lifecycle.</p>
<p>Every worker can be terminated independently.</p>
<p>Most importantly, the orchestration platform remains completely unaware of what the pipeline actually does.</p>
<p>It simply provides a safe environment in which arbitrary analysis workloads can execute reliably.</p>
<h2>Conclusion</h2>
<p>At this point we've completed the execution platform.</p>
<p>A client submits work.</p>
<p>FastAPI persists the request.</p>
<p>The Queue Manager schedules execution.</p>
<p>An isolated worker loads the configured pipeline, executes it safely, reports progress, and cleans up every resource before exiting.</p>
<p>What we haven't explored yet is <strong>the pipeline itself</strong>.</p>
<p>How do we process tens of thousands of comments without exceeding LLM token limits?</p>
<p>How do we execute embedding generation concurrently while respecting API rate limits?</p>
<p>How do we recover from failures without repeating expensive computation?</p>
<p>In the next—and final—article we'll step inside the AI pipeline itself and explore the engineering patterns behind scalable LLM-powered thematic analysis.</p>
]]></content:encoded></item><item><title><![CDATA["Inside the Worker: Building a Resilient AI Execution Platform" ]]></title><description><![CDATA[Design resilient worker processes using Python multiprocessing, FastAPI, dynamic loading and dependency injection for long-running AI workloads.]]></description><link>https://blog.lucrolearning.com/inside-the-worker-building-a-resilient-ai-execution-platform</link><guid isPermaLink="true">https://blog.lucrolearning.com/inside-the-worker-building-a-resilient-ai-execution-platform</guid><category><![CDATA[Python]]></category><category><![CDATA[FastAPI]]></category><category><![CDATA[multiprocessing    architecture]]></category><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Sat, 18 Jul 2026 22:09:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/ffebba9b-1159-43de-9cb0-a5ced5052a5f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<blockquote>
<p><strong>This is Part 5 of the <em>Beyond FastAPI</em> series</strong></p>
<p>In the previous article, <a href="https://blog.lucrolearning.com/the-listener-loop-turning-jobs-into-work"><strong>The Listener Loop: Turning Jobs into Work</strong></a>, we built the scheduling layer responsible for monitoring the queue, enforcing concurrency limits, and spawning isolated worker processes.</p>
<p>In this article we'll step inside one of those workers and explore what happens after the Queue Manager decides a job should run.</p>
</blockquote>
<hr />
<h2>Previously...</h2>
<p>So far our architecture looks like this:</p>
<pre><code class="language-text">Client
   │
   ▼
FastAPI
   │
   ▼
MongoDB Job Queue
   │
   ▼
Queue Manager
   │
   ▼
Spawn Worker Process
</code></pre>
<p>The Queue Manager continuously polls the database for pending jobs, claims work atomically, checks whether there's available capacity, and finally launches a completely new operating system process for every accepted job.</p>
<p>At this point, the API request has already completed.</p>
<p>The client has received a Job ID.</p>
<p>The Queue Manager has finished scheduling.</p>
<p>Everything from here happens <strong>independently</strong> inside a worker process.</p>
<p>The obvious question is...</p>
<p><strong>What exactly happens inside that worker?</strong></p>
<hr />
<h2>The Worker is More Than "Some Code"</h2>
<p>The real reasons to go for worker based design are architectural.</p>
<p>We want every job to execute inside its own isolated runtime.</p>
<p>That gives us:</p>
<ul>
<li><p>independent memory</p>
</li>
<li><p>independent event loop</p>
</li>
<li><p>isolated failures</p>
</li>
<li><p>individual lifecycle management</p>
</li>
<li><p>safe termination</p>
</li>
<li><p>clean resource ownership</p>
</li>
</ul>
<p>Instead of thinking of a worker as <strong>a function running elsewhere</strong>, think of it as <strong>a miniature application</strong> dedicated to executing a single job.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/9097f41f-aea5-4c2b-90d7-1f0464eacda3.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Crossing the Process Boundary</h2>
<p>The Queue Manager creates workers using Python's <code>multiprocessing</code> module.</p>
<pre><code class="language-python">proc = Process(
    target=worker_entry,
    args=(
        job_id,
        payload,
        DBFactory,
        PIPELINE,
        logger,
    ),
    daemon=False,
)

proc.start()
</code></pre>
<p>When <code>proc.start()</code> is called.</p>
<p>A completely new Python interpreter is launched.</p>
<p>That new interpreter starts with its own memory space, its own global variables, its own event loop, and its own execution context.</p>
<p>Conceptually, this is what happens:</p>
<pre><code class="language-text">Queue Manager

        │

        ▼

Create Process

        │

        ▼

New Python Interpreter

        │

        ▼

Import Modules

        │

        ▼

Run worker_entry()

        │

        ▼

Execute Job
</code></pre>
<p>Notice that the worker shares <strong>nothing</strong> with the Queue Manager except the arguments passed during creation.</p>
<p>There is no shared application state.</p>
<p>No shared database objects.</p>
<p>No shared event loop.</p>
<p>Everything begins from a clean slate.</p>
<hr />
<h2>Why Processes Instead of Threads?</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/0a533d14-644a-46c6-a9e9-550f330b326f.jpg" alt="" style="display:block;margin:0 auto" />

<p>This is one of the most important architectural decisions in the entire platform.</p>
<p>Many engineers immediately ask:</p>
<blockquote>
<p>Why not simply create a thread?</p>
</blockquote>
<p>The answer has very little to do with performance.</p>
<p>It has everything to do with isolation.</p>
<table>
<thead>
<tr>
<th>Threads</th>
<th>Processes</th>
</tr>
</thead>
<tbody><tr>
<td>Share memory</td>
<td>Independent memory</td>
</tr>
<tr>
<td>Shared global state</td>
<td>Completely isolated</td>
</tr>
<tr>
<td>Harder to terminate safely</td>
<td>Can terminate individually</td>
</tr>
<tr>
<td>Errors may affect application state</td>
<td>Failures remain isolated</td>
</tr>
<tr>
<td>Good for lightweight concurrent tasks</td>
<td>Ideal for long-running AI workloads</td>
</tr>
</tbody></table>
<p>Imagine one analysis pipeline suddenly starts consuming several gigabytes of memory.</p>
<p>Or enters an infinite loop.</p>
<p>Or launches a subprocess that never exits.</p>
<p>With threads, those failures happen inside your application's own process.</p>
<p>With worker processes, the Queue Manager simply terminates the offending worker without affecting any other running jobs.</p>
<p>That's an enormous operational advantage.</p>
<hr />
<blockquote>
<h2>💡 Engineering Insight</h2>
<p>The worker process is not a performance optimisation.</p>
<p>It's an isolation boundary.</p>
<p>Every job becomes independently manageable, observable and disposable.</p>
</blockquote>
<hr />
<h3>Every Worker Starts at the Same Entry Point</h3>
<p>Every worker begins execution inside a single function.</p>
<pre><code class="language-python">def worker_entry(
    job_id,
    payload,
    DBFactory,
    PIPELINE,
    logger=None,
):
</code></pre>
<p>You can think of <code>worker_entry()</code> as the worker's own <code>main()</code> function.</p>
<p>Every worker follows exactly the same lifecycle.</p>
<pre><code class="language-text">Worker Starts

↓

Configure Logging

↓

Create Event Loop

↓

Connect Database

↓

Load Pipeline

↓

Run Analysis

↓

Report Progress

↓

Cleanup

↓

Exit
</code></pre>
<p>Having a single entry point makes every worker predictable.</p>
<p>Regardless of what type of analysis is executed in the future, the execution lifecycle remains identical.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/fb7f9708-879d-4952-a95e-adbfe9ed6ac8.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Every Worker Has Its Own Event Loop</h2>
<p>Inside <code>worker_entry()</code> we eventually reach this line:</p>
<pre><code class="language-python">asyncio.run(main())
</code></pre>
<p>This creates a completely new asyncio event loop <strong>inside the worker process</strong>.</p>
<p>The FastAPI server already has its own event loop.</p>
<p>The Queue Manager also runs inside that application's event loop.</p>
<p>Once the worker starts, it creates an entirely separate event loop dedicated to executing exactly one job.</p>
<p>That means asynchronous operations inside the worker never interfere with the web server.</p>
<p>The API can continue accepting new requests while workers independently perform long-running AI workloads.</p>
<hr />
<h2>Loading the Analysis Pipeline Dynamically</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/7043eb25-48d6-4bcc-b5f5-ade2eda81011.png" alt="" style="display:block;margin:0 auto" />

<p>One of my favourite design decisions in this project is that the worker <strong>doesn't know anything about thematic analysis.</strong></p>
<p>Instead, it receives the pipeline to execute as configuration.</p>
<pre><code class="language-python">analysis = _load_analysis(
    PIPELINE,
    constructor_args
)
</code></pre>
<p>The helper responsible for loading the pipeline looks roughly like this:</p>
<pre><code class="language-python">module = importlib.import_module(module_path)

cls = getattr(module, class_name)

return cls(**constructor_args)
</code></pre>
<p>Rather than importing a concrete implementation directly, the worker loads whatever class is configured at runtime.</p>
<p>Conceptually:</p>
<pre><code class="language-text">Configuration

↓

Pipeline Class Name

↓

importlib

↓

Instantiate Class

↓

Run Pipeline
</code></pre>
<p>This makes the worker completely reusable.</p>
<p>Today it executes a thematic analysis pipeline.</p>
<p>Tomorrow the exact same worker could execute:</p>
<ul>
<li><p>document processing</p>
</li>
<li><p>OCR pipelines</p>
</li>
<li><p>image classification</p>
</li>
<li><p>audio transcription</p>
</li>
<li><p>video analysis</p>
</li>
<li><p>ETL jobs</p>
</li>
</ul>
<p>without changing a single line inside the worker itself.</p>
<hr />
<blockquote>
<h2>💡 Engineering Insight</h2>
<p>The worker knows <strong>how to execute work</strong>, but it deliberately knows nothing about <strong>what the work actually is</strong>.</p>
<p>This is a classic plugin architecture.</p>
<p>The execution platform remains stable while individual analysis pipelines evolve independently.</p>
</blockquote>
<hr />
<h2>Why Dynamic Loading Matters</h2>
<p>Imagine if the worker looked like this:</p>
<pre><code class="language-python">analysis = ThematicAnalysisPipeline(...)
</code></pre>
<p>Every time a new pipeline is introduced, we'd need to modify the worker itself.</p>
<p>Instead, our worker depends only on an interface.</p>
<pre><code class="language-python">PipeLineInterface
</code></pre>
<p>Any implementation satisfying that interface can be loaded dynamically.</p>
<p>That means the orchestration layer remains generic while new AI workflows can be introduced simply by changing configuration.</p>
<p>This separation of concerns is one of the key reasons the platform is extensible.</p>
<hr />
<h2>Architecture So Far</h2>
<p>At this point, our execution platform looks like this:</p>
<pre><code class="language-text">Client
   │
   ▼
FastAPI
   │
   ▼
MongoDB Queue
   │
   ▼
Queue Manager
   │
   ▼
Spawn Worker
   │
   ▼
worker_entry()
   │
   ▼
Dynamic Pipeline Loader
   │
   ▼
Analysis Pipeline
</code></pre>
<p>The Queue Manager doesn't know what kind of work is being executed.</p>
<p>The Worker doesn't know which specific pipeline it will load.</p>
<p>And the Pipeline doesn't know anything about FastAPI, queues, or scheduling.</p>
<p>Each component has exactly one responsibility.</p>
<hr />
<h2>Coming Up Next</h2>
<p>So far we've focused on <strong>how a worker starts</strong>.</p>
<p>In the next section we'll explore what happens <strong>after the pipeline has been loaded</strong>.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[The Listener Loop: Turning Jobs into Work]]></title><description><![CDATA[Putting It All Together]]></description><link>https://blog.lucrolearning.com/the-listener-loop-turning-jobs-into-work</link><guid isPermaLink="true">https://blog.lucrolearning.com/the-listener-loop-turning-jobs-into-work</guid><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Fri, 17 Jul 2026 12:35:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/00476dac-6023-45f8-833f-6cc8cb8ede07.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So far, we've built an execution engine that starts alongside our <a href="https://hashnode.com/edit/cmrm4rj0c00000akjac41alas">FastAPI</a> application and runs independently of incoming <a href="https://hashnode.com/edit/cmrnf7vk900000ahtatwo5i7b">HTTP requests</a>. We have also seen the role of a <a href="https://hashnode.com/edit/cmrnviyxe00000aht95te86p6">queue manager</a> that schedules and dispatches worker processes</p>
<p>The next question is straightforward:</p>
<blockquote>
<p><strong>How does a pending job actually become a running worker?</strong></p>
</blockquote>
<p>That responsibility belongs to the <strong>Listener Loop</strong>.</p>
<p>Conceptually, the Listener Loop acts as a scheduler. It continuously monitors the job queue, checks whether the system has available capacity, and dispatches new work when resources become available.</p>
<p>Unlike message brokers such as RabbitMQ or Kafka, MongoDB doesn't push notifications when new documents are inserted. Instead, our scheduler periodically polls the queue for pending work.</p>
<p>The implementation is surprisingly compact.</p>
<pre><code class="language-python">async def _listener_loop(self):

    while True:

        await self._reap_finished()

        running = await self.db.count_running_jobs()

        capacity = max(
            0,
            MAX_CONCURRENT_JOBS - running
        )

        if capacity &gt; 0:

            for _ in range(capacity):

                doc = await self.db.claim_next_pending_job(...)

                if not doc:
                    break

                await self._spawn_worker(...)

        await asyncio.sleep(POLL_INTERVAL_SECONDS)
</code></pre>
<p>Despite its size, this loop performs nearly all of the scheduling decisions in the platform.</p>
<p>Let's break it down.</p>
<hr />
<h2>A Scheduler, Not a Consumer</h2>
<p>It's tempting to think of the Listener Loop as a "consumer" that simply pulls jobs from a queue.</p>
<p>In reality, it's doing considerably more than that.</p>
<p>Every iteration of the loop answers three questions:</p>
<ol>
<li><p><strong>How many jobs are already running?</strong></p>
</li>
<li><p><strong>How many more jobs can this instance execute?</strong></p>
</li>
<li><p><strong>Which pending jobs should be promoted to running?</strong></p>
</li>
</ol>
<p>Only after answering all three does it create new worker processes.</p>
<p>This is why I prefer describing it as a <strong>scheduler</strong> rather than a queue consumer.</p>
<p>It isn't just reading jobs.</p>
<p>It's making execution decisions.</p>
<hr />
<p><strong>Listener Loop Scheduling Cycle</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/e4941395-95cd-48f0-bfb8-b5e126e2644c.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Step 1: Reclaim Finished Workers</h2>
<p>Every scheduling cycle begins by checking whether any worker processes have completed.</p>
<pre><code class="language-python">await self._reap_finished()
</code></pre>
<p>Why first?</p>
<p>Imagine three workers finish while the Listener Loop is sleeping.</p>
<p>From MongoDB's perspective, those jobs may already be marked as completed.</p>
<p>However, from the operating system's perspective, the associated processes still exist until the parent process acknowledges their termination. Reaping completed workers keeps the Queue Manager's in-memory process registry accurate and frees capacity for new work.</p>
<p>We'll explore process reaping in much greater detail later in this article, but for now it's enough to think of it as housekeeping before new scheduling decisions are made.</p>
<hr />
<h2>Step 2: Measure Current Capacity</h2>
<p>The next step is determining how much work the system can safely accept.</p>
<pre><code class="language-python">running = await self.db.count_running_jobs()

capacity = max(
    0,
    MAX_CONCURRENT_JOBS - running
)
</code></pre>
<p>Rather than blindly launching workers whenever pending jobs exist, the scheduler first checks how many analyses are already executing.</p>
<p>Suppose our configuration allows a maximum of four concurrent workers.</p>
<pre><code class="language-plaintext">MAX_CONCURRENT_JOBS = 4
</code></pre>
<p>If three jobs are currently running, the scheduler computes:</p>
<pre><code class="language-plaintext">capacity = 4 - 3 = 1
</code></pre>
<p>Only one additional worker may be started. If four jobs are already running:</p>
<pre><code class="language-plaintext">capacity = 0
</code></pre>
<p>No new workers are launched until capacity becomes available.</p>
<p>This simple calculation provides a hard upper bound on system resource usage.</p>
<hr />
<blockquote>
<p><strong>Why Limit Concurrency?</strong></p>
<p>LLM-powered analysis is both CPU and network intensive. Every worker consumes memory, maintains its own database client, performs external API calls, and may generate embeddings or process large datasets. Allowing unlimited workers would quickly exhaust available resources and degrade overall system performance. By enforcing a configurable concurrency limit, the scheduler ensures that throughput increases in a controlled and predictable manner rather than overwhelming the host machine.</p>
</blockquote>
<hr />
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/cb5496ba-3623-4792-8537-8fbe4f11623f.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Step 3: Claiming Work Atomically</h2>
<p>Finding a pending job sounds trivial.</p>
<p>At first, you might imagine something like this:</p>
<pre><code class="language-python">job = db.find_one({
    "status": "pending"
})
</code></pre>
<p>Unfortunately, this introduces a subtle race condition.</p>
<p>Imagine two Queue Managers running simultaneously.</p>
<pre><code class="language-plaintext">Queue Manager A

↓

Find Pending Job #123

↓

Worker Spawn
</code></pre>
<p>At exactly the same moment:</p>
<pre><code class="language-plaintext">Queue Manager B

↓

Find Pending Job #123

↓

Worker Spawn
</code></pre>
<p>Both schedulers have now selected the same document.</p>
<p>The result?</p>
<p>Two workers execute the same analysis.</p>
<p>Duplicate processing.</p>
<p>Conflicting updates.</p>
<p>Undefined behaviour.</p>
<p>This is one of the most common pitfalls in distributed scheduling systems. Instead of simply reading a pending document, our implementation performs an <strong>atomic claim</strong>.</p>
<p>Conceptually, it behaves like this:</p>
<pre><code class="language-plaintext">Find first pending job

AND

Immediately update status

↓

running
</code></pre>
<p>Because both operations occur as a single database transaction (or atomic update operation), only one scheduler can successfully claim a given job. Every other scheduler simply moves on to the next available document. This small implementation detail is what makes the scheduler safe to scale horizontally across multiple application instances.</p>
<hr />
<blockquote>
<p><strong>Key Insight</strong></p>
<p>A queue isn't just about storing work. It's about ensuring that every piece of work is executed exactly once.</p>
</blockquote>
<hr />
<h2>Filling Available Capacity</h2>
<p>Once a job has been successfully claimed, the scheduler repeats the process until either:</p>
<ul>
<li><p>there are no more pending jobs, or</p>
</li>
<li><p>the concurrency limit has been reached.</p>
</li>
</ul>
<pre><code class="language-python">for _ in range(capacity):

    doc = await self.db.claim_next_pending_job(...)

    if not doc:
        break

    await self._spawn_worker(...)
</code></pre>
<p>Notice that the scheduler doesn't claim every pending job in one pass.</p>
<p>Instead, it only claims enough work to fill the currently available capacity.</p>
<p>Suppose we have:</p>
<pre><code class="language-plaintext">Pending Jobs: 15

Running Jobs: 2

Maximum Workers: 6
</code></pre>
<p>The scheduler calculates:</p>
<pre><code class="language-plaintext">capacity = 4
</code></pre>
<p>Only four jobs are claimed.</p>
<p>The remaining eleven stay safely in the queue until the next scheduling cycle.</p>
<p>This approach naturally applies back-pressure to the system. The queue can grow as demand increases, while worker creation remains bounded by the configured concurrency limit. Rather than overwhelming the machine during traffic spikes, excess work simply waits its turn.</p>
<p>This is one of the defining characteristics of resilient asynchronous systems.</p>
<hr />
<h2>Sleeping Without Blocking</h2>
<p>After scheduling any available work, the Listener Loop pauses briefly before repeating.</p>
<pre><code class="language-python">await asyncio.sleep(
    POLL_INTERVAL_SECONDS
)
</code></pre>
<p>Because the scheduler is implemented using <code>asyncio</code>, this sleep doesn't block the event loop.</p>
<p>While the Listener is waiting, FastAPI continues serving HTTP requests, the Watchdog continues monitoring running jobs, and worker processes continue executing analyses.</p>
<p>The scheduler simply yields control until it's time for the next polling cycle.</p>
<p>Choosing the polling interval is a trade-off.</p>
<p>A shorter interval reduces the delay before new jobs begin executing but increases database activity.</p>
<p>A longer interval reduces database load at the cost of slightly higher scheduling latency.</p>
<p>In practice, a polling interval of a few seconds is more than sufficient for long-running AI workloads measured in minutes rather than milliseconds.</p>
<hr />
<h2>The Result</h2>
<p>By the end of each iteration, the Listener Loop has transformed persisted job records into actively executing worker processes while respecting the system's configured capacity.</p>
<p>It doesn't perform any analysis itself.</p>
<p>It doesn't understand embeddings, prompts, or LLMs.</p>
<p>Its sole responsibility is deciding <strong>when work should begin</strong>.</p>
<p>That separation keeps the scheduler simple, predictable, and easy to reason about—qualities that become increasingly valuable as systems grow in complexity.</p>
]]></content:encoded></item><item><title><![CDATA[Building the Execution Engine: Queue Manager, Workers and Process Orchestration]]></title><description><![CDATA[Part 3 of the "Beyond FastAPI" series. In the previous article, we built a thin orchestration layer using FastAPI. The API validates incoming requests…]]></description><link>https://blog.lucrolearning.com/building-the-execution-engine-queue-manager-workers-and-process-orchestration</link><guid isPermaLink="true">https://blog.lucrolearning.com/building-the-execution-engine-queue-manager-workers-and-process-orchestration</guid><category><![CDATA[Python]]></category><category><![CDATA[# orchestration layer]]></category><category><![CDATA[queue manager]]></category><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Thu, 16 Jul 2026 19:00:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/8fe7ccdf-79c4-4fbd-a183-833eef449f32.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><em>Part 3 of the "Beyond FastAPI" series.</em></p>
</blockquote>
<p>In the <a href="https://hashnode.com/edit/cmrnf7vk900000ahtatwo5i7b">previous article</a>, we built a thin orchestration layer using FastAPI. The API validates incoming requests, persists them as pending jobs, and immediately returns a Job ID to the client. At this point, our application is responsive, but it's also incomplete.</p>
<p>Although jobs are now safely stored in MongoDB, nothing is actually executing them.</p>
<p>Something still needs to answer a number of important questions.</p>
<ul>
<li><p>Which job should run next?</p>
</li>
<li><p>How many jobs can execute concurrently?</p>
</li>
<li><p>How do we prevent two workers from processing the same job?</p>
</li>
<li><p>What happens when a worker crashes?</p>
</li>
<li><p>How do we detect jobs that become stuck?</p>
</li>
<li><p>How do we clean up finished processes?</p>
</li>
</ul>
<p>These responsibilities don't belong inside the API. They belong to a dedicated scheduling component. In our architecture, that component is the <strong>Queue Manager</strong>.</p>
<hr />
<h3>The Queue Manager Is Not the Queue</h3>
<p>One misconception developers often have when reading architectures like this is assuming that the Queue Manager <em>is</em> the queue.</p>
<p>It isn't. The queue already exists. It's our MongoDB collection. Although it can be any other SQL based database as following.</p>
<pre><code class="language-plaintext">┌──────────────────────────┐
│ MongoDB Jobs Collection  │
├──────────────────────────┤
│ pending                  │.            │
│ pending                  │.            │ 
│ running                  │.            │
│ completed                │.            │
│ failed                   │.            │
└──────────────────────────┘
</code></pre>
<p>Every analysis request submitted through FastAPI is stored as a document (or row) inside this collection. Each document represents the current state of a job.</p>
<p>The Queue Manager doesn't own this data. Instead, it continuously observes it and makes scheduling decisions based on the current state of the system. This distinction is subtle but extremely important.</p>
<p>So MongoDB as the <strong>source of truth</strong>. The Queue Manager is simply the <strong>scheduler</strong> responsible for moving jobs through their lifecycle.</p>
<hr />
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/6459f262-2cd5-4580-8403-9e7bdd75caaa.jpg" alt="" style="display:block;margin:0 auto" />

<h3>Separating Scheduling from Execution</h3>
<p>One of the design goals of this platform was ensuring that no single component performs too many responsibilities.</p>
<p>Let's compare two possible implementations.</p>
<h3>Option 1</h3>
<pre><code class="language-plaintext">FastAPI

↓

Find Pending Job

↓

Execute Analysis

↓

Store Result
</code></pre>
<p>This is simple.</p>
<p>Unfortunately, it's also tightly coupled.</p>
<p>The API now owns:</p>
<ul>
<li><p>HTTP communication</p>
</li>
<li><p>Scheduling</p>
</li>
<li><p>Concurrency</p>
</li>
<li><p>Worker lifecycle</p>
</li>
<li><p>Analysis execution</p>
</li>
</ul>
<p>Every new feature increases the complexity of the web application.</p>
<p>Instead, our architecture separates these concerns.</p>
<pre><code class="language-plaintext">              FastAPI
                  │
                  ▼
        MongoDB Job Queue
                  │
                  ▼
           Queue Manager
          ┌───────┴────────┐
          ▼                ▼
     Listener Loop   Watchdog Loop
          │
          ▼
     Worker Process
</code></pre>
<p>Each component now has a single responsibility.</p>
<p>FastAPI accepts work.</p>
<p>MongoDB stores work.</p>
<p>Queue Manager schedules work.</p>
<p>Workers execute work.</p>
<p>Because each component focuses on one job, the overall system becomes much easier to understand, test and evolve.</p>
<hr />
<h2>Anatomy of the Queue Manager</h2>
<p>Let's look at the class itself.</p>
<pre><code class="language-python">class QueueManager:

    def __init__(
        self,
        DBFactory
    ):
        self.db = DBFactory()
        self._db_impl_factory_for_worker = DBFactory

        self._listener_task = None
        self._watchdog_task = None

        self._running_processes = {}
</code></pre>
<p>Although the implementation is relatively small, every member variable exists for a specific reason.</p>
<h3>Database Interface</h3>
<pre><code class="language-python">self.db
</code></pre>
<p>The scheduler never communicates directly with MongoDB. Instead, it depends on the same abstraction used throughout the application. This keeps scheduling logic independent of the underlying persistence implementation.</p>
<hr />
<h3>Worker Database Factory</h3>
<pre><code class="language-python">self._db_impl_factory_for_worker
</code></pre>
<p>This is one of the more interesting design decisions in the project.</p>
<p>Instead of sharing a single database instance with worker processes, we inject a <strong>factory function</strong> capable of creating fresh database implementations.</p>
<p>Why?</p>
<p>Because worker processes execute in separate operating system processes. Sharing an already connected database client across processes can lead to unpredictable behaviour depending on the driver and operating system.</p>
<p>Instead, every worker creates its own independent database connection.</p>
<pre><code class="language-plaintext">Parent Process
      │
      ▼
Queue Manager
      │
      ▼
Factory Function
      │
 ┌────┴────┐
 ▼         ▼
Worker 1  Worker 2
 │         │
 ▼         ▼
MongoDB   MongoDB
Connection Connection
</code></pre>
<p>This keeps process boundaries clean while avoiding shared state between workers.</p>
<blockquote>
<p><strong>A Note on Database Connections</strong></p>
</blockquote>
<p>At first glance, creating a separate database client for each worker process might seem expensive. However, workers are <strong>not spawned without bounds</strong>. The Queue Manager enforces a configurable concurrency limit, ensuring that only a fixed number of worker processes can run simultaneously. Each worker establishes its own process-local MongoDB client; following MongoDB's recommendation of one client per process and exits once its job completes. Because the number of concurrent workers is tightly controlled, the maximum number of database clients is also bounded and predictable. We'll explore how this concurrency limit is enforced in the next section when we dive into the Listener Loop and scheduling logic.</p>
<hr />
<h3>Background Tasks</h3>
<p>The Queue Manager owns two asynchronous tasks.</p>
<pre><code class="language-python">_listener_task

_watchdog_task
</code></pre>
<p>These are long-running background coroutines that execute independently of incoming HTTP requests. Each solves a different problem:</p>
<p>The <strong>Listener Loop</strong> continuously searches for new work.</p>
<p>The <strong>Watchdog Loop</strong> monitors already running work.</p>
<p>Keeping these responsibilities separate makes the scheduling logic significantly easier to reason about. We'll dive into both loops next.</p>
<hr />
<h3>Tracking Running Processes</h3>
<p>Finally, the Queue Manager maintains an in-memory registry.</p>
<pre><code class="language-python">_running_processes
</code></pre>
<p>Conceptually, it looks like this.</p>
<pre><code class="language-plaintext">{
    "job-123": Process(pid=4128),

    "job-456": Process(pid=4132),

    "job-789": Process(pid=4141)
}
</code></pre>
<p>Notice what this dictionary is <strong>not</strong>.</p>
<p>It isn't the source of truth for job state. <em><mark class="bg-yellow-200 dark:bg-yellow-500/30">MongoDB already provides that</mark></em><mark class="bg-yellow-200 dark:bg-yellow-500/30">.</mark> Instead, this registry exists purely so the Queue Manager can interact with operating system processes.</p>
<p>For example:</p>
<ul>
<li><p>Determining whether a worker is still alive</p>
</li>
<li><p>Terminating workers during shutdown</p>
</li>
<li><p>Reclaiming finished processes</p>
</li>
<li><p>Detecting crashed workers</p>
</li>
</ul>
<p>Keeping process metadata separate from persisted job state keeps the architecture both simple and resilient.</p>
<hr />
<h3>Starting the Execution Engine</h3>
<p>Once FastAPI starts, it invokes the Queue Manager's startup routine.</p>
<pre><code class="language-python">async def start(self):


    self._listener_task = asyncio.create_task(
        self._listener_loop()
    )

    self._watchdog_task = asyncio.create_task(
        self._watchdog_loop()
    )
</code></pre>
<p>Notice something interesting. Neither loop blocks the application. Instead, both are started using:</p>
<pre><code class="language-python">asyncio.create_task(...)
</code></pre>
<p>This allows them to execute concurrently alongside the FastAPI event loop.</p>
<pre><code class="language-plaintext">                Event Loop

         ┌─────────┬──────────┐
         ▼         ▼          ▼

    HTTP Server  Listener   Watchdog
</code></pre>
<p>Although all three components share the same event loop, they remain completely independent.</p>
<ul>
<li><p>The HTTP server continues accepting requests.</p>
</li>
<li><p>The Listener discovers new jobs.</p>
</li>
<li><p>The Watchdog monitors existing workers.</p>
</li>
</ul>
<p>No component blocks another. This is precisely the type of workload <code>asyncio</code> was designed for—multiple long-running, I/O-bound tasks cooperating within a single thread.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/bd25a0f0-ca4a-454c-9618-8968d5711858.jpg" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Why <code>asyncio</code> Instead of Threads?</h3>
<p>A common question is why the scheduler itself isn't implemented using threads. The answer lies in understanding what the Queue Manager actually does. It isn't performing CPU-intensive computation. Instead, it's mostly waiting.</p>
<ul>
<li><p>Waiting for database operations.</p>
</li>
<li><p>Waiting for polling intervals.</p>
</li>
<li><p>Waiting for workers to finish.</p>
</li>
<li><p>Waiting for timeout checks.</p>
</li>
</ul>
<p>These are classic <strong>I/O-bound</strong> operations.</p>
<p>Using <code>asyncio</code> allows a single thread to efficiently coordinate hundreds or even thousands of these waiting operations without the overhead of managing multiple operating system threads.</p>
<p>The workers, on the other hand, are a completely different story.</p>
<p>They execute expensive LLM pipelines, consume significant CPU and memory resources, and need strong isolation from one another.</p>
<p>That's why the workers are implemented using <strong>separate processes</strong>, not asynchronous coroutines.</p>
<p>This separation allows each technology to solve the problem it is best suited for:</p>
<ul>
<li><p><strong>asyncio</strong> coordinates work.</p>
</li>
<li><p><strong>Processes</strong> execute work.</p>
</li>
</ul>
<p>As we'll see next, the Listener Loop brings these two worlds together by continuously transforming pending jobs into isolated worker processes.</p>
]]></content:encoded></item><item><title><![CDATA[Building the Orchestration Layer: Designing a Thin FastAPI API for Long-Running AI Workloads]]></title><description><![CDATA[Accepting requests elegantly]]></description><link>https://blog.lucrolearning.com/building-the-orchestration-layer-designing-a-thin-fastapi-api-for-long-running-ai-workloads</link><guid isPermaLink="true">https://blog.lucrolearning.com/building-the-orchestration-layer-designing-a-thin-fastapi-api-for-long-running-ai-workloads</guid><category><![CDATA[Python]]></category><category><![CDATA[FastAPI]]></category><category><![CDATA[# orchestration layer]]></category><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Thu, 16 Jul 2026 11:23:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/71b90793-9d55-4337-9845-f018188823e7.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<blockquote>
<p><em>Part 2 of the "Beyond FastAPI" series.</em></p>
</blockquote>
<p>In the <a href="https://hashnode.com/edit/cmrm4rj0c00000akjac41alas">previous article</a>, we explored why long-running AI workloads don't belong inside a traditional request-response cycle. We introduced an architecture that decouples request handling from job execution, allowing our API to remain responsive while computationally intensive analysis runs asynchronously in the background.</p>
<p>In this article, we'll build the <strong>orchestration layer</strong> of that architecture.</p>
<p>Rather than focusing on FastAPI itself, we'll look at how the application is composed, how dependencies are injected, and why the API layer should remain intentionally thin. We'll also see how background services such as our queue manager are integrated into the application's lifecycle without leaking infrastructure concerns into the web layer.</p>
<hr />
<h2>The Role of the Orchestration Layer</h2>
<p>When developers first begin building APIs, it's common to let the web framework become the centre of the application.</p>
<p>A request arrives.</p>
<p>The endpoint validates input.</p>
<p>The endpoint queries the database.</p>
<p>The endpoint performs business logic.</p>
<p>The endpoint calls external APIs.</p>
<p>The endpoint returns the response.</p>
<p>This works remarkably well—until the business logic becomes expensive.</p>
<p>Our thematic analysis pipeline isn't a simple CRUD operation. A single request can involve fetching thousands of survey responses, cleaning and preprocessing text, generating embeddings, orchestrating multiple LLM calls, aggregating intermediate results, and finally persisting the generated insights.</p>
<p>That's not the responsibility of an HTTP endpoint.</p>
<p>Instead, our FastAPI application has a much simpler responsibility:</p>
<blockquote>
<p><strong>Accept work. Persist work. Return immediately.</strong></p>
</blockquote>
<p>Everything else belongs elsewhere.</p>
<hr />
<blockquote>
<p><strong>Key Design Principle</strong></p>
<p>HTTP APIs should be responsible for communication, not computation.</p>
</blockquote>
<hr />
<h2>Overall Architecture</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/4616d43b-a15a-44cf-bdfa-d58885cf2966.png" alt="" style="display:block;margin:0 auto" />

<p>Notice something important.</p>
<p>The API is no longer responsible for executing the analysis.</p>
<p>Instead, it acts as the entry point into a much larger execution platform.</p>
<p>This separation of concerns has several advantages:</p>
<ul>
<li><p>API requests complete in milliseconds instead of minutes.</p>
</li>
<li><p>Long-running analyses survive independently of HTTP connections.</p>
</li>
<li><p>Workers can scale independently of the API.</p>
</li>
<li><p>Failures are isolated to individual jobs.</p>
</li>
<li><p>Progress can be tracked asynchronously.</p>
</li>
</ul>
<p>FastAPI simply becomes the gateway into the system rather than the system itself.</p>
<hr />
<h3>The Composition Root</h3>
<p>One of the most overlooked aspects of application architecture is <strong>where objects are created</strong>.</p>
<p>Every application has a point where its major components are instantiated and connected together. This is commonly referred to as the <strong>Composition Root</strong>.</p>
<p>In our project, that responsibility belongs to the application's entry point.</p>
<pre><code class="language-python">def run():
    myDB = _make_db_impl()
    DBFactory = _make_db_impl

    app = create_app(
       DBFactory
    )

    uvicorn.run(app, host="0.0.0.0", port=8000)
</code></pre>
<p>At first glance this looks almost trivial.</p>
<p>In reality, this function defines the entire dependency graph of the application.</p>
<p>Before FastAPI ever starts accepting requests, we create:</p>
<ul>
<li><p>the database implementation</p>
</li>
<li><p>the worker database factory</p>
</li>
<li><p>the queue manager</p>
</li>
<li><p>the web server</p>
</li>
<li><p>the FastAPI application</p>
</li>
</ul>
<p>Only once every component has been assembled do we hand control over to Uvicorn.</p>
<p>This may seem like a small design choice, but it has significant architectural benefits.</p>
<p>The application has exactly one place responsible for wiring dependencies together. No class reaches into another module to construct its own dependencies. Nothing relies on global state. Every component receives exactly what it needs through its constructor.</p>
<p>This makes the application significantly easier to understand, maintain, and test.</p>
<h3>Why Dependency Injection Matters</h3>
<p>Let's imagine we wrote our queue manager like this:</p>
<pre><code class="language-python">class QueueManager:

    def __init__(self):
        self.db = MongoJobsDB(...)
</code></pre>
<p>This works.</p>
<p>But now the queue manager is permanently coupled to MongoDB.</p>
<p>Testing becomes difficult.</p>
<p>Switching databases becomes difficult.</p>
<p>Replacing MongoDB with Redis, PostgreSQL, or a mock implementation becomes impossible without modifying the class itself.</p>
<p>Instead, our implementation receives its dependencies from the outside.</p>
<pre><code class="language-python">class QueueManager:

    def __init__(
        self,
        DBFactory,
    ):
        self.db = DBFactory()
</code></pre>
<p>This small change fundamentally alters the architecture.</p>
<p>The queue manager no longer knows or cares where the database comes from. It simply depends on the behaviour defined by the interface. This is an example of the <strong>Dependency Inversion Principle</strong>, one of the SOLID design principles.</p>
<p>Rather than depending on concrete implementations, high-level components depend on abstractions.</p>
<p>As a result:</p>
<ul>
<li><p>business logic becomes independent of infrastructure</p>
</li>
<li><p>testing becomes straightforward</p>
</li>
<li><p>implementations become interchangeable</p>
</li>
<li><p>components become easier to reuse</p>
</li>
<li><p>QueueManager<br /><code>│</code><br /><code>▼</code><br /><code>DBInterface</code><br /><code>▲</code><br /><code>│</code><br /><code>┌─────────────┴──────────────┐</code><br /><code>▼ ▼</code><br /><code>MongoJobsDB MockDatabase</code></p>
</li>
</ul>
<p>Although our current implementation only uses MongoDB, the queue manager itself has no knowledge of that decision.</p>
<p>That's exactly where we want to be.</p>
<h3>Building a Thin API Layer</h3>
<p>One of the easiest ways for an application to become difficult to maintain is to allow the web framework to absorb business logic. Over time, the web layer becomes tightly coupled to every other component in the system, making it increasingly difficult to test, extend, or replace.</p>
<p>Instead, the FastAPI application in this project acts purely as a <strong>transport layer</strong>. Its responsibilities are deliberately limited to:</p>
<ul>
<li><p>Receiving HTTP requests</p>
</li>
<li><p>Validating incoming data</p>
</li>
<li><p>Delegating work to the orchestration layer</p>
</li>
<li><p>Returning an appropriate HTTP response</p>
</li>
</ul>
<p>Everything else belongs elsewhere.</p>
<p>This philosophy is reflected in the <code>WebServer</code> class.</p>
<pre><code class="language-python">class WebServer:
    def __init__(self, db: DBInterface, queue_mgr: QueueManager):
        self.db = db
        self.queue_mgr = queue_mgr

        self.app = FastAPI(
            title="Async Queue Server",
            lifespan=self._lifespan,
        )

        self.app.add_api_route(
            "/enqueue",
            self.enqueue_post,
            methods=["POST"],
            response_model=EnqueueResponse,
        )

        self.app.add_api_route(
            "/jobs/{job_id}",
            self.get_job,
            methods=["GET"],
        )
</code></pre>
<p>There are a couple of interesting design decisions here.</p>
<p>First, notice that the <code>WebServer</code> doesn't construct its own dependencies.</p>
<p>Both the database implementation and the queue manager are injected into the constructor, continuing the dependency injection pattern introduced earlier.</p>
<p>Second, the class doesn't contain any scheduling logic.</p>
<p>It doesn't spawn workers.</p>
<p>It doesn't communicate with LLMs.</p>
<p>It doesn't poll queues.</p>
<p>It doesn't even know how jobs are executed.</p>
<p>Its only responsibility is exposing a clean HTTP interface over the orchestration platform.</p>
<hr />
<h3>Why Register Routes Programmatically?</h3>
<p>If you've used FastAPI before, you're probably familiar with decorators.</p>
<pre><code class="language-plaintext">@app.post("/enqueue")
async def enqueue():
    ...
</code></pre>
<p>Decorators are concise and work well for smaller applications.</p>
<p>However, once the application begins to grow, I generally prefer encapsulating related endpoints inside classes and registering routes programmatically.</p>
<pre><code class="language-python">self.app.add_api_route(
    "/enqueue",
    self.enqueue_post,
    methods=["POST"],
)
</code></pre>
<p>This provides several advantages:</p>
<ul>
<li><p>The web server becomes a self-contained component.</p>
</li>
<li><p>Dependencies are injected through the constructor.</p>
</li>
<li><p>Routes are registered in one place.</p>
</li>
<li><p>And the application structure more closely resembles the architecture itself.</p>
</li>
</ul>
<p>Instead of scattered decorators across multiple modules, the routing layer becomes an object with a clearly defined responsibility. This is largely a matter of preference, but I've found it scales better as applications grow beyond a handful of endpoints.</p>
<hr />
<h3>Managing Background Services with FastAPI Lifespan</h3>
<p>One of the more elegant features introduced in modern versions of FastAPI is the <strong>lifespan protocol</strong>.</p>
<p>Rather than relying on startup events or background threads, FastAPI allows applications to define asynchronous startup and shutdown logic using an asynchronous context manager.</p>
<pre><code class="language-python">@asynccontextmanager
async def _lifespan(self, app: FastAPI):
    await self.queue_mgr.start()

    try:
        yield
    finally:
        await self.queue_mgr.stop()
</code></pre>
<p>It defines the lifecycle of the entire orchestration platform. When the application starts:</p>
<pre><code class="language-plaintext">FastAPI Starts
      │
      ▼
Queue Manager Starts
      │
      ▼
Listener Loop Starts
      │
      ▼
Watchdog Starts
      │
      ▼
API Ready
</code></pre>
<p>Likewise, during shutdown:</p>
<pre><code class="language-plaintext">SIGTERM
      │
      ▼
FastAPI Shutdown
      │
      ▼
QueueManager.stop()
      │
      ▼
Cancel Async Tasks
      │
      ▼
Terminate Workers
      │
      ▼
Exit
</code></pre>
<p>Every long-running background component starts together.</p>
<p>Every component stops together.</p>
<p>This avoids one of the most common problems in asynchronous applications—background tasks that continue running after the web server has begun shutting down.</p>
<p>Instead, the entire application behaves as a single coordinated unit.<br />Here is the comparison illustrated:  </p>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/8411b7c9-ee79-402c-979b-d3d9ebc37e12.jpg" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Accepting Work Instead of Executing Work</h3>
<p>The most important endpoint in the application is <code>/enqueue</code>.</p>
<p>Its implementation is surprisingly small.</p>
<pre><code class="language-python">async def enqueue_post(self, req: EnqueueRequest):
    job_id = await self.db.insert_pending_job(req.payload)

    return EnqueueResponse(
        id=job_id,
        status="pending",
    )
</code></pre>
<p>That’s all it does: no worker creation, no scheduling, no analysis, no LLM calls, and no expensive computation. The endpoint simply records a pending job and immediately returns a response. It may seem almost too simple until you compare it with the alternative.</p>
<h2>Synchronous Design</h2>
<pre><code class="language-plaintext">Client
   │
   ▼
POST /analyse
   │
   ▼
FastAPI
   │
   ▼
Fetch Data
   │
   ▼
Generate Embeddings
   │
   ▼
Call LLM
   │
   ▼
Store Results
   │
   ▼
HTTP Response
</code></pre>
<p>The client waits for every stage of the pipeline to complete.</p>
<p>If the analysis takes five minutes, the HTTP request remains open for five minutes.</p>
<p>Now compare that to the asynchronous design.</p>
<h2>Asynchronous Design</h2>
<pre><code class="language-plaintext">Client
   │
   ▼
POST /enqueue
   │
   ▼
Insert Pending Job
   │
   ▼
Return Job ID
</code></pre>
<p>Milliseconds later, the response has already been returned.</p>
<p>Meanwhile, independently of the HTTP request:</p>
<pre><code class="language-plaintext">Queue Manager
      │
      ▼
Claim Job
      │
      ▼
Spawn Worker
      │
      ▼
Run Analysis
      │
      ▼
Store Results
</code></pre>
<p>The API remains completely free to serve additional clients.</p>
<p>The orchestration platform performs the expensive work independently.</p>
<p>This decoupling is one of the defining characteristics of asynchronous systems.</p>
<hr />
<h3>Tracking Progress Instead of Holding Connections Open</h3>
<p>Returning a Job ID fundamentally changes the interaction model between the client and the server, the client receives an acknowledgement that work has been accepted.</p>
<pre><code class="language-http">POST /enqueue

HTTP/1.1 200 OK

{
    "id": "0f9d4b8f",
    "status": "pending"
}
</code></pre>
<p>The client can now continue using the application while the analysis executes in the background.</p>
<p>Whenever progress is needed, it simply queries another endpoint.</p>
<pre><code class="language-http">GET /jobs/0f9d4b8f
</code></pre>
<p>This pattern has several advantages.</p>
<ul>
<li><p>The API never holds long-lived HTTP connections.</p>
</li>
<li><p>Progress can be reported incrementally.</p>
</li>
<li><p>Users can safely refresh the page without interrupting processing.</p>
</li>
<li><p>Clients can poll or subscribe for updates.</p>
</li>
<li><p>Jobs become durable entities rather than transient HTTP requests.</p>
</li>
</ul>
<p>From a user's perspective, the experience is actually better.</p>
<p>Instead of staring at a loading spinner for several minutes, they receive immediate feedback that their request has been accepted and can monitor its progress asynchronously.</p>
<hr />
<p><em>Let's continue to design reliable worker processes and queue manager in part 3!</em></p>
]]></content:encoded></item><item><title><![CDATA[Beyond FastAPI: Building a Production-Ready Asynchronous Job Orchestrator in Python]]></title><description><![CDATA[How I built a scalable execution platform for long-running AI workloads using FastAPI, asyncio, multiprocessing, and MongoDB.]]></description><link>https://blog.lucrolearning.com/beyond-fastapi-building-a-production-ready-asynchronous-job-orchestrator-in-python</link><guid isPermaLink="true">https://blog.lucrolearning.com/beyond-fastapi-building-a-production-ready-asynchronous-job-orchestrator-in-python</guid><category><![CDATA[software architecture]]></category><category><![CDATA[Python]]></category><category><![CDATA[job-orchestration]]></category><dc:creator><![CDATA[Kashif Mohammad]]></dc:creator><pubDate>Wed, 15 Jul 2026 13:43:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/e048ae54-af11-40ca-8b44-bf5d5e9b1511.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Background</h2>
<p>Modern organizations collect an enormous amount of unstructured textual data through customer surveys, support tickets, employee feedback, product reviews, and research responses. While Large Language Models (LLMs) have made it possible to automate qualitative analysis, applying them to production-scale datasets introduces challenges that go far beyond simply making an API call. Processing thousands of responses can take several minutes, involve multiple stages of analysis, require retries, and depend on external services that are inherently slow or unreliable.</p>
<p>The core feature I wanted to build was an <strong>LLM-powered thematic analysis engine</strong> capable of processing large collections of textual responses and automatically identifying recurring themes, topics, and insights. The objective was to provide users with a simple interface where they could submit an analysis request, continue using the application, and retrieve the results once processing had completed. Rather than treating each request as a traditional synchronous API call, the system needed to support long-running, resource-intensive workloads while remaining responsive to other users.</p>
<p>This immediately shifted the problem from being purely about AI to being about <strong>backend systems engineering</strong>. The challenge was no longer just generating prompts or orchestrating LLM interactions—it was designing an execution platform that could reliably schedule analysis jobs, execute them in isolation, track progress, recover from failures, and scale as demand increased. In other words, the thematic analysis pipeline became just one component of a much larger asynchronous processing architecture.</p>
<p>In this series, I'll walk through the design and implementation of that execution platform. We'll look at how <strong>FastAPI</strong>, <strong>asyncio</strong>, <strong>multiprocessing</strong>, and <strong>MongoDB</strong> can be combined to build a production-style asynchronous job orchestration system capable of supporting long-running AI workloads without compromising the responsiveness or reliability of the API layer.</p>
<h2>Part 1 - Why FastAPI Alone Isn't Enough for Long-Running Workloads</h2>
<h3>Introduction</h3>
<p>Imagine exposing an API endpoint that performs thematic analysis on thousands of customer comments. Behind a single request lies a complex, multi-stage workflow that includes data retrieval, text preprocessing, embedding generation, multiple interactions with LLM services, aggregation of intermediate results, and persistence of the final analysis. Since each stage may involve expensive computation or external network calls, the total execution time can range from several seconds to many minutes. Executing such workloads synchronously would tie up server resources, increase the likelihood of request timeouts, and degrade the responsiveness of the API for other users..</p>
<p>That also creates several other problems:</p>
<ul>
<li><p>Reverse proxy timeouts</p>
</li>
<li><p>No progress tracking</p>
</li>
<li><p>Poor scalability</p>
</li>
<li><p>Inability to recover if the server crashes</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/3e644a60-1708-4c95-a833-3e071c09534e.jpg" alt="" style="display:block;margin:0 auto" />

<p>In other words, the API is trying to fulfil two very different responsibilities: serving HTTP requests and executing computationally expensive background jobs. These concerns have different scalability and reliability requirements, and coupling them together makes the system harder to scale, monitor, and recover. A better approach is to keep the API lightweight by accepting the request, persisting the job, and delegating the long-running work to a dedicated orchestration and worker layer.</p>
<h2>A Better Architecture</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6a51387ca8cf56c623690316/f1dc7309-8aab-4fbc-8d24-83c7230f08c7.jpg" alt="" style="display:block;margin:0 auto" />

<p>Instead of coupling the API directly to the analysis pipeline, we can decouple request handling from job execution by introducing an asynchronous orchestration layer. In this architecture, the API is responsible only for validating incoming requests, creating a job, and returning a unique job identifier to the client. The actual analysis is performed independently in the background, allowing the API to remain responsive regardless of how long the analysis takes.</p>
<p>The journey begins when a client submits an analysis request to the <strong>FastAPI</strong> application. Rather than executing the analysis immediately, FastAPI persists the request as a <strong>pending job</strong> in a MongoDB-backed job queue and immediately responds with a job ID. This completes the HTTP request within milliseconds while ensuring that the analysis request has been durably stored.</p>
<p>A dedicated <strong>Queue Manager</strong> continuously monitors the job queue for pending work. Based on configurable concurrency limits, it claims jobs atomically and dispatches them to a pool of isolated worker processes. This orchestration layer acts as the scheduler for the system, ensuring that only a safe number of analyses execute concurrently while preventing multiple workers from processing the same job.</p>
<p>Each worker process provides an isolated execution environment for a single analysis job. Rather than containing the business logic itself, the worker dynamically loads the appropriate <strong>LLM analysis pipeline</strong> through a plugin architecture. This keeps the orchestration layer generic and allows new analysis pipelines to be introduced without changing the worker infrastructure. During execution, workers periodically report progress milestones, making it possible for clients to monitor long-running jobs instead of waiting for a single HTTP response.</p>
<p>Finally, once the analysis completes, the generated themes, insights, and metadata are persisted to <strong>MongoDB</strong>, where they can be retrieved through a separate API endpoint. If a worker crashes or becomes unresponsive, the orchestration layer can detect the failure, mark the job appropriately, and recover gracefully without affecting the API server or other running analyses.</p>
<p>By separating <strong>request handling</strong>, <strong>job scheduling</strong>, and <strong>analysis execution</strong> into distinct components, each part of the system can scale independently. The API remains lightweight and responsive, the queue manager efficiently coordinates workloads, and the worker pool focuses exclusively on executing computationally expensive AI tasks. This separation of concerns results in a more scalable, resilient, and maintainable architecture for long-running LLM-powered applications.</p>
<p>Here is the high level break down of the components involved in the new architecture along with their primary function</p>
<table>
<thead>
<tr>
<th>Component</th>
<th>Responsibility</th>
</tr>
</thead>
</table>
<table style="min-width:50px"><colgroup><col style="min-width:25px"></col><col style="min-width:25px"></col></colgroup><tbody><tr><td><p>FastAPI</p></td><td><p>Accepts Requests for thematic analysis</p></td></tr><tr><td><p>MongoDb</p></td><td><p>Persists jobs, intermediate and final results of analsyis, also stores milestone progress of analysis process</p></td></tr><tr><td><p>Queue Manager</p></td><td><p>Schedules jobs</p></td></tr><tr><td><p>Workers</p></td><td><p>Execute analysis</p></td></tr><tr><td><p>LLM pipeline</p></td><td><p>Core logic of LLM based analysis</p></td></tr></tbody></table>

<table style="min-width:25px"><colgroup><col style="min-width:25px"></col></colgroup><tbody><tr><td><p></p></td></tr></tbody></table>

<h2>Key Design Principles</h2>
<p>Although the technologies used to build this platform are important, the architecture is ultimately driven by a handful of fundamental design principles. These principles allow the system to remain responsive, resilient, and scalable as the complexity and volume of analysis jobs grow.</p>
<h3>Decoupling</h3>
<p>The API layer and the analysis pipeline serve very different purposes and therefore should not depend on each other. The API is responsible for accepting requests, validating input, and creating jobs, while the worker infrastructure is responsible for executing long-running analyses. By introducing a job queue between these components, requests can be accepted and acknowledged immediately without waiting for the analysis to complete. This separation also allows each component to evolve independently without impacting the others.</p>
<h3>Fault Isolation</h3>
<p>Long-running workloads inevitably fail. External APIs may become unavailable, network requests may time out, or unexpected errors may occur during processing. By executing each analysis in an isolated worker process, failures are contained to a single job rather than affecting the API server or other running analyses. A crashed worker simply results in a failed job, while the rest of the platform continues operating normally.</p>
<h3>Horizontal Scalability</h3>
<p>As demand increases, the solution should be to add more execution capacity rather than making a single server more powerful. Since jobs are persisted in a shared queue and workers operate independently, additional worker processes—or even workers running on different machines—can be introduced to increase throughput. The API layer, queue manager, and worker pool can each be scaled independently according to their individual workloads.</p>
<h3>Asynchronous Processing</h3>
<p>The request-response lifecycle should be measured in milliseconds, even if the underlying analysis takes several minutes. By treating analysis as an asynchronous background task, the API remains responsive and clients are free to continue using the application while their jobs execute. Progress can be tracked independently, and results can be retrieved once processing has completed.</p>
<h3>Worker Isolation</h3>
<p>Each analysis executes within its own operating system process, providing complete isolation from every other job. This prevents memory leaks, crashes, or resource-intensive analyses from impacting other workers. It also enables graceful shutdown, independent process lifecycle management, and more predictable resource utilisation, all of which are essential for building reliable long-running processing systems.</p>
<hr />
<p><em>Lets continue to work on FastAPI in part 2</em></p>
]]></content:encoded></item></channel></rss>