Skip to content

Module 09 · Lesson 9.2

API Design, Background Jobs and Session Management

45 minUpdated 18 Nov 2026Part of Deployment, Observability and Optimization · AI Agent Development
On this page
  1. What you will learn
  2. What an API is and why an agent needs one
  3. Design the endpoints: request and response shapes
  4. Errors and status codes clients can understand
  5. Background jobs for tasks that take a long time
  6. A job queue with one worker in Python
  7. Sessions: remembering a customer between requests
  8. Idempotency: safe retries for POST requests
  9. Conclusion and your next step
  10. Common errors and fixes
  11. Validation checklist
  12. Hands-on exercise
  13. Knowledge check
  14. Frequently asked questions
  15. References

Think about ordering a pizza by phone. A short question gets an instant answer: "Yes, we are open." An order gets a ticket number, and you call back later to ask if it is ready. A good agent API works the same way. Quick questions are answered at once. Slow tasks get a ticket.

In this lesson you design the endpoints for the Quillfeather agent service, choose clear error codes, and see how background jobs and sessions work. You do not need to build a web server yet. The lab at the end of the module does that. One short Python script shows a job queue with a worker.

What you will learn

  • Design endpoints with clear request and response shapes for an agent service.
  • Choose sensible error responses and status codes.
  • Explain how a background job with a job id and polling works.
  • Run a small Python job queue with one worker thread.

Before you start

What an API is and why an agent needs one

An API (application programming interface) is a set of agreed addresses and message shapes that one program uses to talk to another. Your website does not run the agent. It sends a message to the agent's API and gets a reply.

Most web APIs use HTTP, the same system your browser uses. A request has a method (what to do), a path (where) and often a body (the data, usually JSON). The reply has a status code (a number that says how it went) and a body.

GET
Read something without changing it. Example: read a run's trace.
POST
Send something that causes work or a change. Example: ask a question.
Status code
A three-digit number in the reply. 200 means fine. 400 means the request was wrong. 404 means not found. 500 means the service failed.
JSON
A plain-text way to write structured data, such as {"question": "Where is QF-1042?"}.

Design the endpoints: request and response shapes

Keep the API small. Each endpoint does one thing and returns a fixed shape. These are the endpoints the lab at the end of this module uses.

EndpointRequestResponse
POST /ask{"question": "Where is QF-1042?"}{"run_id": "R-0001", "reply": "..."}
GET /runs/<run_id>No body. The run id is in the path.The trace events of that run, one per step
GET /healthNo body{"ok": true, "version": "v2"}
The reply field holds the reply contract from the earlier labs: status, order_id, sources and reply.

Notice what the response gives back: a run id. It is a unique label for one run. Later, anyone can use it to look up exactly what happened. You will use it heavily in Tracing Tool Calls and Agent Decisions.

  • Use clear names. /ask is better than /do.
  • Return the same shape every time, so clients can rely on it.
  • Never return secrets, internal file paths or stack traces to the client.
  • Add a version, such as v2, to /health so you can tell which build is running.
  • Validate every request in code before it reaches the model. See Designing Tool Schemas and Validating Arguments for the same idea applied to tools.

Errors and status codes clients can understand

When something goes wrong, the client needs to know whether it was its own mistake, a temporary problem or a bug. Status codes tell it, and a short JSON message tells it why.

SituationStatusExample body
Body is not valid JSON, or question is missing400{"error": "question is required"}
Question is far too long413{"error": "question is too long"}
Run id does not exist404{"error": "run not found"}
Client sends too many requests429{"error": "too many requests, try again later"}
The service itself failed500{"error": "internal error"}
The model provider is unavailable503{"error": "temporarily unavailable"}
Codes starting with 4 mean the client should change its request. Codes starting with 5 mean the problem is on the service side.

Background jobs for tasks that take a long time

An order question takes a few seconds. The Module 5 research agent can take minutes. If the client waits on an open connection that long, something will time out. The usual fix is a background job: the service accepts the task, returns a job id at once and does the work separately. The client later asks for the result. Asking again and again is called polling.

The life of a background job
  1. Client sends task

    POST /jobs

  2. Service saves job

    status queued, returns job id

  3. Worker runs it

    status running, then done or failed

  4. Client polls

    GET /jobs/<job id>

  5. Result returned

    status done plus the result

The client never waits for the slow part. It only holds a ticket.

  • queued: saved, not started.
  • running: a worker has it.
  • done: finished, the result is available.
  • failed: stopped with an error. Say why, without secrets.

Jobs should be saved in your state store, not only in memory, so a restart does not lose them. The checkpoint idea from Managing Long-Running Tasks and Checkpoints fits here: a worker that restarts can pick up the saved job and continue. Also set a limit on how long a job may run and how many jobs one client may queue.

A job queue with one worker in Python

The script below shows the core idea with the standard library. A queue holds jobs in order, like people waiting at a counter. A thread is a second line of work inside the same program. Here one worker thread takes jobs from the queue and fills in their results. The answers are fake text, so no model is needed.

Pythonjobs.py
import queue
import threading

jobs = {}
work = queue.Queue()


def worker():
    while True:
        job_id = work.get()
        job = jobs[job_id]
        job["status"] = "running"
        job["result"] = "Answer for: " + job["question"]
        job["status"] = "done"
        work.task_done()


helper = threading.Thread(target=worker, daemon=True)
helper.start()

Part 1: the store, the queue and the worker.

Pythonjobs.py
def submit(question):
    job_id = "J-%03d" % (len(jobs) + 1)
    jobs[job_id] = {"question": question, "status": "queued", "result": None}
    work.put(job_id)
    return job_id


first = submit("Where is QF-1042?")
second = submit("How long does delivery take?")
print("accepted:", first, second)
work.join()
for job_id in sorted(jobs):
    print(job_id, jobs[job_id]["status"], "|", jobs[job_id]["result"])

Part 2: add this below part 1 in the same file.

What each part does

  • jobs = {} is the job store. In a real service this would be a database or a file.
  • work = queue.Queue() is the waiting line. put adds a job id and get takes the next one. It is safe to use from several threads.
  • worker() runs forever. It waits for a job id, marks the job running, fills in a result and marks it done.
  • helper = threading.Thread(...) creates the worker thread and helper.start() runs it in the background. daemon=True lets the program exit without waiting for the endless loop.
  • submit() makes a job id such as J-001, saves the job as queued, puts the id on the queue and returns at once. This is your "return a ticket" step.
  • work.join() waits until every queued job has been marked finished with task_done().
  • The final loop prints jobs in sorted order, so the output is the same every time.
OutputCaptured from a real run
accepted: J-001 J-002
J-001 done | Answer for: Where is QF-1042?
J-002 done | Answer for: How long does delivery take?

Sessions: remembering a customer between requests

HTTP forgets. Each request arrives as a stranger. A session links requests from the same conversation. The client receives a session id and sends it back each time. The service uses it to look up the saved state for that conversation.

  • Make session ids long and unpredictable, so nobody can guess another customer's id.
  • Store only what the agent needs: recent messages, the case record, a pending request.
  • Give every session an expiry. For example, delete it after 30 minutes of silence. This protects privacy and saves space. Your organisation's policy decides the real time.
  • Trim long histories before sending them to the model. See Managing Context Windows and Conversation History.
  • Check that a session id belongs to the person using it. An id alone is not proof of identity.

Idempotency: safe retries for POST requests

Networks fail. A client sends POST /ask, loses the connection and sends it again. Did the first request already create a return? Idempotency means that repeating a request has the same effect as sending it once.

You met this in Tool Errors, Retries, Timeouts and Idempotency, where request_return used an idempotency key. The same idea works at the API. The client adds a unique key, for example in a header. The service saves the key with the result. If the same key arrives again, the service returns the saved result and does no new work.

  • Reads (GET) are naturally safe to repeat.
  • Any POST that causes a change or costs model money should accept a key.
  • Keep saved keys for a limited time, then delete them.

Conclusion and your next step

A good agent API is small and predictable: a few endpoints, fixed shapes and honest status codes. Slow work becomes a background job with a job id. Sessions carry state between requests and expire. Idempotency keys make retries safe.

Your next step: write a table of the endpoints your own agent service needs, with request shape, response shape and error codes. Then continue to Tracing Tool Calls and Agent Decisions, where each run id becomes a full step-by-step record.

For more on slow work, see Sequential, Parallel and Conditional Tool Execution and the Troubleshooting LLM API Errors guide.

Common errors and how to fix them

Clients time out when a long task runs.

Why it happens: The service does all the work while the request stays open.

Fix: Return a job id at once, run the work in a worker and let the client poll for the result.

Every failure returns status 200 with a vague message.

Why it happens: Errors and agent outcomes are mixed together.

Fix: Use 4xx and 5xx codes for broken requests and failed services. Keep needs_person and not_found as normal replies inside the reply contract.

A customer is charged twice, or two returns are created, after a retry.

Why it happens: The POST is not idempotent.

Fix: Accept an idempotency key and return the saved result for a repeated key.

Old conversations pile up and contain personal details.

Why it happens: Sessions never expire.

Fix: Set an expiry on every session and delete expired ones on a schedule.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Design the API for a return-request feature

Quillfeather wants customers to start a return through the agent. The review by staff can take up to 2 working days. Design the endpoints and responses for starting a return and checking its progress.

You will need

  • The agent can only create a PENDING request. A person approves it later.
  • Order ids look like QF-1042.
  • A customer may press the button twice by mistake.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Staff review is far too slow for an open connection.
  • Use 404 for an unknown id and 400 for a bad order id.
  • The status can be pending, approved or rejected.
Show a model answer

A good design: POST /returns with {"order_id": "QF-1042", "reason": "damaged"} and an idempotency key header. It answers {"return_id": "RT-001", "status": "pending"} at once. GET /returns/RT-001 returns the current status, which staff change when they approve or reject. A repeated POST with the same key returns the same return id and creates nothing new. Errors: 400 {"error": "order_id must look like QF-1234"}, 404 {"error": "return not found"} and 429 for too many requests. The long wait is handled by the pending status, so no request stays open for two days.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.A task takes several minutes. What is a sensible API design?
    Show the answer and explanation

    Answer: B. A job id is a stable handle that survives timeouts. Holding the connection open is tempting because it is simple, but long requests time out and cannot be resumed.

  2. 2.The agent replies with status needs_person. What HTTP status should the API return?
    Show the answer and explanation

    Answer: A. The request worked and the agent made a safe choice. A 500 would mean the service broke, which would trigger false alarms.

  3. 3.What does an idempotency key protect against?
    Show the answer and explanation

    Answer: B. The saved key lets the service return the earlier result instead of repeating the work. It does nothing for session ids or speed, although all three are API concerns.

Frequently asked questions

What is a background job in simple terms?

It is a task that the service starts and finishes on its own, while the client only holds a ticket number. The client checks the ticket later to get the result. It is like leaving a coat for repair and collecting it when it is ready.

What is polling?

Polling means asking again and again whether something is ready. Wait a moment between asks, such as two seconds, so you do not flood the service. Some systems use a callback instead, where the service contacts the client when the job is done.

How long should a session last?

As short as the task allows. A support chat might expire after 30 minutes of silence. Your organisation's privacy policy and local rules decide the real limit, so check them before you choose.

Why use a run id for every request?

A run id lets you find everything one request did: the model calls, the tool calls and the outcome. Without it, you cannot link a customer's complaint to the exact run that caused it.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.