AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 61

    Background Jobs, Queues and Event-Driven AI Processing

    Northwind's instructor clicked "Draft reminders" for the cohort.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 61 · Production AI Products, Capstones and Career Readiness

    Lesson Overview

    Northwind's instructor clicked "Draft reminders" for the cohort. The API tried to call the model once per learner, forty times, inside the tutor container's request. The 8-second player budget from LLM Cost, Latency and Performance Engineering fired, then the 30-second platform deadline from the deployment lesson fired behind it. Twelve drafts had been written. The instructor retried. Those twelve were written again, and the click still never finished. The status poll for that run returned a Contoso job id because the queue was one global list and the handler returned whatever sat at the head. Synthesis, which lesson 60 had already classified as a job, was still a function that hoped the container would wait.

    A job is work the learner or the instructor does not watch token by token. A queue holds the job until a worker can run it. An event is the fact that caused the job: reminder.requested, eval.scheduled, document.uploaded. The HTTP handler validates the session, writes the job, and returns 202 with a job id. The worker claims the job, calls the model under the same allowance and redaction rules as the player, and records a side effect once. The player polls or subscribes for status. It does not hold a stream open until forty completions exist.

    Cloud Deployment, Serverless and Managed Runtime Choices already placed the eval batch on a worker with a cursor. This lesson generalizes that cursor into a queue the reminder, the synthesis, and the embedding rebuild can share. The eval case cap and spend cap stay. They are policy on the job, not a reason to invent a second runner.

    Planning assumptions:

    • Delivery is at least once. The worker can see the same job twice after a crash. The side effect key makes the second run a no-op.
    • A lease lasts 60 seconds in the lab. A leased job whose lease has expired returns to queued. A live lease is left alone.
    • Three attempts, then dead. Dead jobs are visible to the owning organization and are not retried by the worker.
    • The payload carries subject ids such as lrn_priya and document ids such as doc_pgvector_1. It does not carry emails, prompt text, or provider keys. The worker loads the authorized excerpt the way the request path does.
    • Status reads are tenant-scoped. A Northwind session that asks for a Contoso job id gets not_found.
    • The lab queue is an in-memory array. Production is a table with a unique key on (organization_id, idempotency_key) and a conditional update for the lease. No queue vendor account is required to finish the lesson.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Say why forty model calls do not belong inside one HTTP request.
    2. Return 202 with a job id and keep the provider call on the worker.
    3. Map reminder.requested, eval.scheduled, and document.uploaded onto job kinds.
    4. Build a job envelope whose payload is subject ids, an organization id, and an idempotency key.
    5. Reject a subject id that contains an email address or a space.
    6. Treat a second enqueue with the same organization and idempotency key as a duplicate.
    7. Claim the next queued job for one organization, increment the attempt, and set a lease.
    8. Requeue a job whose lease has expired, and leave a live lease in place.
    9. Complete a job, or mark it dead after the attempt limit.
    10. Apply a side effect once, keyed by organization, subject, and period.
    11. Hide another tenant's job id behind not_found.
    12. Keep the eval batch cursor from lesson 58 inside the eval job so a kill does not restart at case zero.
    13. Charge worker tokens through the lesson 60 ledger, against the worker allowance, not by bypassing it.
    14. Emit a worker.batch span with ids and counts, not with the reminder body.

    Prerequisites

    Detailed Core Concepts

    The request accepts work. The worker does the work

    An HTTP request on the tutor container has a deadline shorter than a cohort. Putting the loop in the handler couples instructor patience, platform timeout, and token spend into one socket. Some side effects commit before the timeout. A retry repeats them. The instructor cannot tell "still drafting" from "the connection died."

    The split is:

    StepWhere it runsWhat it returns
    Authorize, validate, enqueueAPI, inside a short request202 and jobId
    Call the model, write draftsWorker, leasedStatus on the job row
    Show progressAPI read, or a later pollqueued, leased, succeeded, dead

    The player copies the status. It does not infer success from a closed socket. 202 means the job was accepted, not that the reminder was sent. Copy on the panel stays in the "waiting" family already used for approval flows. "Sent" is reserved for a job whose status is succeeded and whose side effects committed.

    Events name facts. Jobs name work

    An event is immutable and small. reminder.requested carries the organization, an idempotency key, and the learner ids the instructor is allowed to see. The handler maps the event name to a job kind:

    EventJob kindWhy it is off the request
    reminder.requestedcohort_reminderOne model call per learner, then a draft row
    eval.scheduledeval_batchMinutes, a case cap, a spend cap, a cursor
    document.uploadedembed_documentParse and embed after the upload response

    The event is not the prompt. The worker loads lesson text and the learner's allowed fields when it runs, under the session organization stored on the job. A prompt baked into the queue message would freeze personal text into a broker you retain longer than privacy-retention-v1, and it would let a poisoned upload travel as instructions. Load late. Treat the loaded text as data, the way the tool-use lessons already require.

    At least once, and a side effect that can survive that

    Queues in this design acknowledge after the handler returns, and a worker crash returns the job. You will see duplicates. Exactly-once delivery from a broker is not the guarantee you design for. Idempotent effects are the guarantee.

    The enqueue idempotency key stops a double click from creating two jobs. The effect key stops two attempts of one job from drafting two reminders. The effect key is organizationId:subjectId:period. For a weekly reminder, period is the week. For an embedding, period is the content hash, so a new document version is a new effect and a retry of the same bytes is not. applyEffect returns applied the first time and skipped after that.

    The eval job keeps lesson 58's cursor: nextCaseIndex and spentUnits commit with the case result. A lease expiry requeues the job. The worker reads the cursor and continues. It does not reset to case zero.

    Leases, attempts, and the dead letter

    A claim sets status to leased, increments attempt, and stores leaseExpiresAtMs. Another worker skips a job whose lease is still in the future. reclaim returns an expired lease to queued without incrementing attempt again. The increment happened at claim. A crash after claim and before success still counts as an attempt, which is what you want. Silent infinite retries are how a poisoned prompt burns the allowance overnight.

    After maxAttempts (3 in the lab), fail sets dead. Dead is a product state. The Northwind panel shows that the draft did not finish and that an operator can inspect it. The worker does not pick it up. Re-driving a dead job is a new enqueue with a new idempotency key, done by a person, after the cause is known. Automatic rebirth of dead jobs recreates the loop you just capped.

    Tenant fence on the queue

    claim takes organizationId and only claims a job for that organization. A shared worker process runs one claim per organization it is allowed to serve, or it runs as that organization's task identity. A Northwind worker identity does not claim Contoso jobs. readStatus returns not_found when the job is missing or when it belongs to another organization. 403 would confirm that the id exists. The course uses not_found for cross-tenant reads of ids the caller should not know.

    Subject ids are checked against the organization's roster before enqueue. lrn_contoso in a Northwind event fails at that roster check, which lives in the tenant module. This package also rejects any subject that contains @ or whitespace, so an email cannot hide inside the id field.

    What the worker may spend and log

    Each model call inside the job uses unitsForCall and recordCharge from lesson 60, with a request id of jobId:subjectId so a retry of one learner does not charge twice and a different learner still charges. The worker allowance is the separate cap from the previous lesson's cost notes. Player traffic and the cohort draft do not share an uncapped counter.

    Spans use worker.batch with runId, jobId, attempt, and counts. The reminder text is not an attribute. Lesson 59's emitSpan remains the gate. A worker that logs the drafted email body has walked around that gate.

    Architecture and Request Flow

    flowchart TB
      subgraph api [Short API request]
        Handler[Validate session and event]
        Enq[enqueue]
      end
    
      subgraph data [Private Postgres]
        Jobs[(jobs unique on org and key)]
        Effects[(effect keys)]
        Ledger[(worker allowance)]
      end
    
      subgraph worker [Worker]
        Claim[claim with lease]
        Model[Model call per subject]
        Once[applyEffect]
      end
    
      Handler --> Enq
      Enq --> Jobs
      Handler -->|202 jobId| Browser[Instructor panel]
      Claim --> Jobs
      Claim --> Model
      Model --> Ledger
      Model --> Once
      Once --> Effects
      Browser -->|poll status| Jobs
    text
    Instructor clicks Draft reminders
    -> session organization is northwind
    -> event reminder.requested with learner ids and idempotency key
    -> reject if any subject contains @ or a foreign roster id
    -> enqueue: new row or duplicate of the existing job
    -> 202 { jobId, status: queued }
    Worker loop
    -> reclaim expired leases
    -> claim next northwind job, attempt += 1, lease 60s
    -> for each subject id
    -> load the authorized excerpt
    -> model call
    -> recordCharge(jobId:subjectId) against the worker allowance
    -> applyEffect(northwind:lrn_priya:2026-W46) once
    -> success: status succeeded
    -> throw: status queued if attempts remain, else dead
    Poll
    -> northwind may read its job
    -> northwind asking for a contoso job id receives not_found

    Trust boundary: the browser receives a job id and a status enum. It does not receive the provider key, the prompt, or another tenant's ids. The worker reads the secret store the same way the API does. The queue table is on the private network.

    Failure point: a status route that looks up by job id alone. The first matching row may be Contoso's.

    Step-by-step Implementation

    Package: packages/jobs/. In-memory queue. The unique key and the conditional lease update are the production notes beside the functions.

    Step 1: Events, envelopes, leases

    packages/jobs/src/types.ts

    typescript
    export type EventName = "reminder.requested" | "eval.scheduled" | "document.uploaded";
    export type JobKind = "cohort_reminder" | "eval_batch" | "embed_document";
    export type JobStatus = "queued" | "leased" | "succeeded" | "dead";
    export interface DomainEvent {
    name: EventName;
    organizationId: string;
    idempotencyKey: string;
    subjectIds: readonly string[];
    }
    export interface JobEnvelope {
    jobId: string;
    organizationId: string;
    kind: JobKind;
    idempotencyKey: string;
    subjectIds: string[];
    attempt: number;
    status: JobStatus;
    leaseExpiresAtMs: number | null;
    }
    export interface Queue {
    jobs: JobEnvelope[];
    }
    export const MAX_ATTEMPTS = 3;
    export const LEASE_MS = 60_000;

    Subject ids are a list, not a blob. An empty list is rejected. Eval jobs use case ids from the golden set, which are public fixtures, still scoped by the organization that scheduled the run so the report row lands on the right tenant.

    Step 2: Enqueue and the event map

    packages/jobs/src/enqueue.ts

    typescript
    import type { DomainEvent, JobEnvelope, JobKind, Queue } from "./types.js";
    export function jobKindFor(name: DomainEvent["name"]): JobKind {
    switch (name) {
    case "reminder.requested":
    return "cohort_reminder";
    case "eval.scheduled":
    return "eval_batch";
    case "document.uploaded":
    return "embed_document";
    default: {
    const neverName: never = name;
    throw new Error(`unknown event ${neverName}`);
    }
    }
    }
    export function subjectLooksPersonal(subjectId: string): boolean {
    return subjectId.includes("@") || /\s/.test(subjectId);
    }
    export function enqueue(
    queue: Queue,
    event: DomainEvent,
    jobId: string,
    ): { ok: true; job: JobEnvelope; duplicate: boolean } | { ok: false; code: "pii_in_subject" | "empty_subject" } {
    if (event.subjectIds.length === 0) return { ok: false, code: "empty_subject" };
    if (event.subjectIds.some(subjectLooksPersonal)) return { ok: false, code: "pii_in_subject" };
    const existing = queue.jobs.find(
    (job) => job.organizationId === event.organizationId && job.idempotencyKey === event.idempotencyKey,
    );
    if (existing) return { ok: true, job: existing, duplicate: true };
    const job: JobEnvelope = {
    jobId,
    organizationId: event.organizationId,
    kind: jobKindFor(event.name),
    idempotencyKey: event.idempotencyKey,
    subjectIds: [...event.subjectIds],
    attempt: 0,
    status: "queued",
    leaseExpiresAtMs: null,
    };
    queue.jobs.push(job);
    return { ok: true, job, duplicate: false };
    }

    The HTTP layer returns 202 and { jobId: job.jobId, status: job.status } when ok is true, including the duplicate case. A double click returns the original job id. It does not start a second cohort. pii_in_subject is 400. The address is not echoed in the error body.

    Step 3: Claim, lease, complete, and the effect key

    packages/jobs/src/worker.ts

    typescript
    import { LEASE_MS, MAX_ATTEMPTS } from "./types.js";
    import type { JobEnvelope, Queue } from "./types.js";
    export function reclaim(queue: Queue, nowMs: number): number {
    let returned = 0;
    for (const job of queue.jobs) {
    if (job.status === "leased" && job.leaseExpiresAtMs !== null && nowMs >= job.leaseExpiresAtMs) {
    job.status = "queued";
    job.leaseExpiresAtMs = null;
    returned += 1;
    }
    }
    return returned;
    }
    export function claim(queue: Queue, organizationId: string, nowMs: number): JobEnvelope | null {
    const job = queue.jobs.find((row) => row.organizationId === organizationId && row.status === "queued");
    if (!job) return null;
    job.status = "leased";
    job.attempt += 1;
    job.leaseExpiresAtMs = nowMs + LEASE_MS;
    return job;
    }
    export function complete(job: JobEnvelope): void {
    job.status = "succeeded";
    job.leaseExpiresAtMs = null;
    }
    export function fail(job: JobEnvelope): "retry" | "dead" {
    if (job.attempt >= MAX_ATTEMPTS) {
    job.status = "dead";
    job.leaseExpiresAtMs = null;
    return "dead";
    }
    job.status = "queued";
    job.leaseExpiresAtMs = null;
    return "retry";
    }
    export function effectKey(organizationId: string, subjectId: string, period: string): string {
    return `${organizationId}:${subjectId}:${period}`;
    }
    export function applyEffect(done: Set<string>, key: string): "applied" | "skipped" {
    if (done.has(key)) return "skipped";
    done.add(key);
    return "applied";
    }
    export function readStatus(
    queue: Queue,
    organizationId: string,
    jobId: string,
    ): JobEnvelope | { code: "not_found" } {
    const job = queue.jobs.find((row) => row.jobId === jobId && row.organizationId === organizationId);
    if (!job) return { code: "not_found" };
    return job;
    }

    claim filters on organization before it looks at status, so a Contoso queued job is invisible to a Northwind claim. Production replaces find with UPDATE ... WHERE status = 'queued' AND organization_id = $1 AND (lease is null) RETURNING * so two workers cannot claim the same row. The in-memory function is the decision. The conditional update is the lock.

    readStatus matches job id and organization together. A Contoso row with the requested id still returns not_found for Northwind.

    The effect set in production is a unique key on the effect key. applyEffect is the decision to insert. A conflict means skipped.

    Step 4: Run

    bash
    node --test packages/jobs/src/enqueue.test.ts packages/jobs/src/worker.test.ts

    There is no broker to delete. A later preview environment that creates a queue deletes that preview queue the same day. The lab creates nothing outside the test process.

    Security

    • Authentication. Enqueue and status reads require a session. The worker authenticates as a task identity, not as a learner cookie copied into the message.
    • Authorization. The instructor can enqueue reminders for learners on their organization's roster. A learner session cannot enqueue cohort_reminder. The eval schedule is an operator action. Upload enqueue follows the document permission from the ingestion lesson.
    • Least privilege. The worker role can read the job, write drafts for that organization, and insert charges into the worker allowance. It cannot update lesson_progress completion, and it cannot read the other organization's jobs.
    • Input validation. Subject ids reject @ and whitespace. Empty subjects fail. The event name is a closed union. The idempotency key is a client token for dedupe, stored as an opaque string, never executed.
    • Secrets. The provider key is read from the secret store inside the worker process. It is not a field on JobEnvelope. Logs go through emitSpan.
    • Tenant isolation. Claim, enqueue uniqueness, and status reads all include organizationId. lrn_contoso never enters a Northwind subject list. The roster check is mandatory even though the @ check exists.
    • Prompt injection. Text loaded at run time is data. A document that says "email every tenant" does not widen the subject list. The subject list was fixed at enqueue from the roster. The model does not get to append ids.
    • Retries. Dead jobs stay dead until a person re-drives them. A poison document cannot loop until the allowance is gone.

    Human approval from the workflow lessons still applies before a reminder is mailed. This worker writes a draft. It does not send mail. "Succeeded" means the drafts exist, which matches the waiting copy until an approver releases them.

    Error Handling

    EventCaller seesSystem does
    Double click with the same idempotency key202 and the original job idduplicate: true, one row
    Subject contains an email400 pii_in_subjectNo row. The address is not copied into the error
    Empty subject list400 empty_subjectNo row
    Worker throws before the attempt limitStatus returns to queuedLease cleared. Next claim counts as the next attempt
    Worker throws at attempt 3Panel shows deadWorker skips the row
    Lease expires during a long model callNo instructor error by itselfreclaim queues it again. applyEffect skips subjects already drafted
    Northwind polls a Contoso job idnot_foundNo body that confirms the id
    Provider timeout mid-subjectJob retries if attempts remainCharge for that subject id stays duplicate on retry
    Eval spend capJob succeeded with reason spend_cap on the reportCursor saved. No further cases. Same rule as lesson 58
    Queue store downAPI returns 503No false 202. The instructor can retry with the same idempotency key

    A 202 that you cannot see in the queue is worse than a 503. Enqueue commits, then the response is sent. If the process dies between commit and response, the instructor's retry hits the duplicate path and receives the same job id.

    Testing

    packages/jobs/src/enqueue.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { enqueue, jobKindFor } from "./enqueue.js";
    import type { Queue } from "./types.js";
    function queue(): Queue {
    return { jobs: [] };
    }
    test("maps a reminder event to a cohort job", () => {
    assert.equal(jobKindFor("reminder.requested"), "cohort_reminder");
    assert.equal(jobKindFor("document.uploaded"), "embed_document");
    });
    test("rejects an email used as a subject id", () => {
    const result = enqueue(
    queue(),
    {
    name: "reminder.requested",
    organizationId: "northwind",
    idempotencyKey: "idem_1",
    subjectIds: ["priya@northwind.example"],
    },
    "job_1",
    );
    assert.deepEqual(result, { ok: false, code: "pii_in_subject" });
    });
    test("returns the original job on a double click", () => {
    const store = queue();
    const event = {
    name: "reminder.requested" as const,
    organizationId: "northwind",
    idempotencyKey: "idem_1",
    subjectIds: ["lrn_priya", "lrn_omar"],
    };
    const first = enqueue(store, event, "job_1");
    const second = enqueue(store, event, "job_2");
    assert.equal(first.ok && first.duplicate, false);
    assert.equal(second.ok && second.job.jobId, "job_1");
    assert.equal(store.jobs.length, 1);
    });

    packages/jobs/src/worker.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { applyEffect, claim, complete, effectKey, fail, readStatus, reclaim } from "./worker.js";
    import type { JobEnvelope, Queue } from "./types.js";
    function leasedQueue(): Queue {
    const job: JobEnvelope = {
    jobId: "job_c",
    organizationId: "contoso",
    kind: "cohort_reminder",
    idempotencyKey: "idem_c",
    subjectIds: ["lrn_contoso"],
    attempt: 0,
    status: "queued",
    leaseExpiresAtMs: null,
    };
    const north: JobEnvelope = {
    jobId: "job_n",
    organizationId: "northwind",
    kind: "cohort_reminder",
    idempotencyKey: "idem_n",
    subjectIds: ["lrn_priya"],
    attempt: 0,
    status: "queued",
    leaseExpiresAtMs: null,
    };
    return { jobs: [job, north] };
    }
    test("claims only the caller's organization", () => {
    const store = leasedQueue();
    const job = claim(store, "northwind", 1_000);
    assert.equal(job?.jobId, "job_n");
    assert.equal(job?.attempt, 1);
    assert.equal(job?.status, "leased");
    });
    test("hides a Contoso job from a Northwind status read", () => {
    const store = leasedQueue();
    assert.deepEqual(readStatus(store, "northwind", "job_c"), { code: "not_found" });
    });
    test("requeues an expired lease and then dead-letters at the attempt cap", () => {
    const store = leasedQueue();
    const job = claim(store, "northwind", 1_000);
    assert.ok(job);
    assert.equal(reclaim(store, 1_000 + 60_000), 1);
    assert.equal(job?.status, "queued");
    job!.attempt = 3;
    job!.status = "leased";
    assert.equal(fail(job!), "dead");
    assert.equal(job?.status, "dead");
    });
    test("applies a reminder draft once per learner and week", () => {
    const done = new Set<string>();
    const key = effectKey("northwind", "lrn_priya", "2026-W46");
    assert.equal(applyEffect(done, key), "applied");
    assert.equal(applyEffect(done, key), "skipped");
    complete({
    jobId: "job_n",
    organizationId: "northwind",
    kind: "cohort_reminder",
    idempotencyKey: "idem_n",
    subjectIds: ["lrn_priya"],
    attempt: 1,
    status: "leased",
    leaseExpiresAtMs: 2_000,
    });
    });

    The complete call at the end of the last test is only a status flip. Point it at the claimed job in your tree so the assertion is status === "succeeded". Add a test that a second enqueue with the same idempotency key and organizationId: "contoso" creates a different job, and a test that fail returns retry when attempt is 1.

    Performance and Cost

    • The API request is a single insert. It stays on the short path and can live on the progress runtime. The model loop cannot.
    • Worker concurrency is a ceiling, shared with the spirit of admitTutor. Forty subjects are sequential in the lab so the allowance moves one charge at a time. Parallel subjects need the same ceiling and the same per-subject request id. Unbounded parallel model calls are how a cohort draft becomes the launch-week bill.
    • Lease length must exceed one subject plus slack, or a healthy job is reclaimed and you depend entirely on applyEffect. If a subject can take 20 seconds, do not use a 10-second lease. The lab's 60 seconds assumes a small cohort and a capped model call. Raise the lease when you measure, and heartbeat the lease if a job outlives it.
    • Polling status every 100 ms from every open panel is its own load. Poll on an interval of a few seconds, or push one status event. Status reads are cheap only when they hit the job primary key.
    • Eval jobs stay capped by case count and units. The queue does not weaken those caps. A retry continues at the cursor.
    • Embedding jobs should hash bytes once and reuse the vector. The cache is the next lesson. The queue still dedupes the job. It does not dedupe the vector computation by itself.
    • Dead jobs need an operator view. An unbounded dead table is a storage leak and a privacy store. Keep the subject ids, the attempt count, and the error code. Keep the drafted body in the draft table under the retention clock, not copied again into the dead payload.

    Illustrative split, not a quote: the instructor request costs one insert. The cohort costs one model call per learner, charged to the worker allowance, skipped when the effect key exists. The timeout that used to discard half the work is gone because the request no longer does the work.

    Knowledge Check

    1. What problem does the queue solve?

    It takes cohort reminders, eval batches, synthesis, and embedding off the player deadline. The instructor receives 202 and a job id. A worker runs the model. A retry drafts each reminder once. Northwind cannot see Contoso's job. The connection no longer dies in the middle of learner twelve.

    2. What alternatives exist, and when would you choose each?

    A stream fits a single glossary or section explanation the learner is watching, inside the 8-second budget. A database table polled by a worker fits this product and keeps the job next to the tenant fence. A separate broker fits when you already operate one and you still mirror the job row in Postgres for status and idempotency. A cron that scans all learners fits a nightly sweep and does not fit an instructor click that needs a job id on screen. Doing the loop in the request fits a demo with two fixtures and fails the cohort.

    3. Which data, identity, and trust boundaries matter?

    The session organization is written onto the job by the server. Subject ids are roster ids, not emails. The provider key stays in the secret store. Claim and status include the organization. The worker does not send mail. Loaded document text is data and cannot extend the subject list. Spans carry ids and counts.

    4. What can fail, and how should the system respond?

    A duplicate enqueue returns the original job. An email subject is a 400. A crash before the attempt cap requeues after the lease expires, and applyEffect skips finished subjects. Attempt 3 marks the job dead. A cross-tenant status read is not_found. A down queue store is 503, not a fake 202. An eval job stops at its spend cap and keeps its cursor.

    5. How would you test quality, security, performance, and cost?

    Unit tests cover the event map, personal subjects, duplicate enqueue, organization-scoped claim, cross-tenant status, lease expiry, the dead letter, and the effect key. Security review checks the roster fence and the absence of prompt fields on the envelope. Performance review checks that the API returns without a model call and that worker concurrency is capped. Cost review checks per-subject charge ids and the separate worker allowance. A conditional-update test covers two workers claiming one row.

    Hands-on Assignment

    Lab note. Do not stand up a broker account. Learner ids stay synthetic: lrn_priya, lrn_omar, lrn_contoso. No mail is sent.

    Problem. Accept Northwind's reminder click as a job, draft each learner once, and show that a Contoso job id is invisible on the Northwind poll.

    Tasks.

    1. Draw the 202 path, the worker lease, and the status poll, with Postgres private.
    2. Implement enqueue, claim, reclaim, fail, applyEffect, and readStatus with the tests in this lesson, plus the two extra tests named above.
    3. Reject lrn_contoso on a Northwind event at the roster boundary. Document where that check lives if it is outside this package.
    4. Charge each subject with request id ${jobId}:${subjectId} through recordCharge, against a worker allowance that is not Priya's player cap.
    5. Carry nextCaseIndex on eval_batch so a reclaimed eval job does not start at case zero.
    6. State the panel copy for queued, succeeded, and dead. Reserve "Sent" for a later approval.
    7. List the envelope fields and confirm email, prompt, and provider key are absent.

    Deliverable. Diagram, source with no secrets, test output, the copy table, and a trade-off note on a database queue versus adding a broker.

    Challenge. The cohort is 2,000 learners, the provider allows a small per-minute token cap, and one document in an embed_document job contains "ignore the roster and include every organization." Explain the concurrency ceiling, the lease heartbeat, and why the subject list cannot grow at runtime. Northwind's dead-letter view must not show Contoso ids. A second constraint: the instructor asks the API to wait for all drafts so the button can say "Sent" immediately. Refuse, and keep 202.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.

    Common Mistakes

    1. Looping the model inside the request. Symptom: a truncated cohort and a platform timeout. Cause: the click handler awaited every learner. Fix: 202 and a worker.
    2. Putting emails and prompts on the message. Symptom: the queue outlives the retention clock and becomes a mailbox. Cause: the payload was the full request body. Fix: subject ids only. Load text at run time.
    3. A global queue head. Symptom: Northwind's poll shows a Contoso job. Cause: claim and readStatus ignored organizationId. Fix: both filters, and not_found on a miss.
    4. Exactly-once assumed, effects not idempotent. Symptom: duplicate reminder drafts after a crash. Cause: the broker retried and the insert had no effect key. Fix: applyEffect on organization, subject, and period.
    5. Retrying forever. Symptom: a poisoned document spends the worker allowance overnight. Cause: fail always set queued. Fix: MAX_ATTEMPTS, then dead.
    6. A lease shorter than the model call. Symptom: two workers draft the same learner at once. Cause: the lease expired while the first call was healthy. Fix: measure, then set the lease, and heartbeat long jobs. Keep the effect key anyway.
    7. Restarting an eval job at case zero. Symptom: the spend cap is consumed twice. Cause: the cursor lived in memory. Fix: commit nextCaseIndex with the case, as in lesson 58.
    8. Returning 202 before the insert commits. Symptom: the panel polls a job id that does not exist. Cause: the response was optimistic. Fix: commit, then respond. A retry uses the idempotency key.
    9. Logging the drafted body on the worker span. Symptom: reminder text in the trace store. Cause: the span spread the model result. Fix: lesson 59's allowlist. Counts and ids only.
    10. Sending mail from the worker because the draft succeeded. Symptom: a reminder goes out without approval. Cause: succeeded was treated as "deliver." Fix: succeeded means drafts exist. Delivery stays behind the approval step.

    Summary

    Background jobs move AI work that cannot finish inside a player deadline onto a worker TechLearningPro already knows how to place. The API validates a Northwind event, stores subject ids and an idempotency key, and returns 202. The worker leases the job, calls the model per subject, charges the worker allowance once per subject, and writes each draft once. Expired leases retry until the attempt cap, then the job is dead. Contoso's job id does not appear on a Northwind status read. Eval batches keep their cursor. The repeated glossary call that still hits the model on the player path is a cache problem, which is the next lesson.

    Next Lesson Preview

    Caching Strategies for AI and Full-Stack Systems stops Northwind from paying for the same glossary answer and the same embedding on every click. You will key result caches by organization and prompt version, key embedding caches by content hash, and keep personalized tutor drafts off the CDN and off other learners' keys.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.