Module 6 · Capstone project

Exposing via API and task queue

6 min read

A graph running in a terminal isn't a product. To be used, Atlas must be exposed to other applications: a web interface, an internal tool, an automation. This lesson turns Atlas into a robust HTTP service, with background execution and persistent pending approvals.

The API contract

A summary note takes tens of seconds, even minutes, and can wait days for human approval. A synchronous HTTP request waiting for completion is therefore out of the question. We use the classic asynchronous model:

MethodRouteEffectResponse
POST/briefsSubmits a question, starts processing in the background202 + identifier
GET/briefs/{id}Status: running, awaiting_review, published, failed200 / 404
POST/briefs/{id}/decisionApproves or sends back with a comment202 / 409

202 Accepted means "request accepted, processing in progress": the client then checks the status (or, in a more advanced version, receives a notification).

The note ID is the thread_id

The whole trick fits in one line: the note's public identifier is the LangGraph thread identifier.

def _config(brief_id: str) -> dict:
    return {"configurable": {"thread_id": brief_id}, "recursion_limit": 50}

Thanks to the checkpointer, each note's state — including a pending approval — can be retrieved from this identifier, by any process of the service.

The service (atlas/api.py)

Creating a note

@app.post("/briefs", status_code=202)
def create_brief(request: BriefRequest, background: BackgroundTasks) -> dict:
    brief_id = uuid.uuid4().hex
    question = " ".join(request.question.split())
    background.add_task(_execute, brief_id, {"question": question, "revisions": 0})
    return {"id": brief_id, "status": "running"}

Input validation is declarative (Field(min_length=3, max_length=2000) in BriefRequest): a question that's too short is rejected with 422 before any model call.

Running in the background without losing errors

def _execute(brief_id: str, payload) -> None:
    """Background task: runs (or resumes) the graph up to the next pause or the end."""
    try:
        graph.invoke(payload, _config(brief_id))
    except Exception as exc:  # the failure becomes a queryable status, not a lost error
        FAILURES[brief_id] = f"{type(exc).__name__}: {exc}"

An exception in a background task is seen by nobody unless you catch it. Here it becomes a queryable failed status — including a BudgetExceeded or a RefusalError.

Deriving the status from the graph state

@app.get("/briefs/{brief_id}")
def get_brief(brief_id: str) -> dict:
    if brief_id in FAILURES:
        return {"id": brief_id, "status": "failed", "error": FAILURES[brief_id]}
    snapshot = graph.get_state(_config(brief_id))
    if not snapshot.values:
        raise HTTPException(404, "Unknown note (or not started yet).")
    if snapshot.interrupts:
        pending = snapshot.interrupts[0].value
        return {"id": brief_id, "status": "awaiting_review", "draft": pending["draft"], "review": pending["review"]}
    if snapshot.values.get("approved"):
        return {"id": brief_id, "status": "published", "draft": snapshot.values["draft"]}
    return {"id": brief_id, "status": "running", "next": list(snapshot.next)}

graph.get_state() returns a snapshot containing the state values, the pending interrupts and the next nodes to run. The note's status is derived entirely from the graph state: no second source of truth to keep in sync.

Resuming after the human decision

@app.post("/briefs/{brief_id}/decision", status_code=202)
def decide(brief_id: str, decision: Decision, background: BackgroundTasks) -> dict:
    snapshot = graph.get_state(_config(brief_id))
    if not snapshot.interrupts:
        raise HTTPException(409, "No approval pending for this note.")
    background.add_task(_execute, brief_id, Command(resume=decision.model_dump()))
    return {"id": brief_id, "status": "running"}

409 Conflict protects against double approvals (double click, network replay): you only resume what is actually waiting for a decision.

Persistence: a Postgres checkpointer

InMemorySaver loses everything on restart: a note awaiting approval for two days would vanish at the next deployment. In production, Atlas uses a Postgres checkpointer as soon as the ATLAS_DB_URI variable is set:

@asynccontextmanager
async def lifespan(app: FastAPI):
    global graph
    db_uri = os.environ.get("ATLAS_DB_URI")
    if db_uri:
        from langgraph.checkpoint.postgres import PostgresSaver

        with PostgresSaver.from_conn_string(db_uri) as checkpointer:
            checkpointer.setup()  # creates the tables on first launch
            graph = build_graph(checkpointer)
            yield
    else:
        graph = build_graph(InMemorySaver())  # development only
        yield

Installation: pip install langgraph-checkpoint-postgres "psycopg[binary]". The binary psycopg driver is required on a machine without the PostgreSQL client library installed: without it, the import fails.

from_conn_string is a context manager that opens and closes the connection cleanly; FastAPI's lifespan ensures it lives exactly as long as the application.

Testing the service

def test_brief_lifecycle():
    with TestClient(app) as http:  # "with" triggers the lifespan
        brief_id = http.post("/briefs", json={"question": "How do you orchestrate agents?"}).json()["id"]
        assert http.get(f"/briefs/{brief_id}").json()["status"] == "awaiting_review"
        assert http.post(f"/briefs/{brief_id}/decision", json={"approved": True}).status_code == 202
        assert http.get(f"/briefs/{brief_id}").json()["status"] == "published"
        assert http.post(f"/briefs/{brief_id}/decision", json={"approved": True}).status_code == 409

This test actually runs the graph (in offline mode) through the API, from submission to publication.

Scaling up: a real task queue

BackgroundTasks runs the work inside the web server process. That's enough to get started, but:

  • a restart interrupts running executions;
  • the web server and the agents compete for the same resources;
  • you can't scale the number of workers independently.

The next step separates roles: the API enqueues a task (Redis, a Postgres table, a managed service), and independent workers consume it by calling the same _execute. Thanks to the shared checkpointer, any worker can resume any note. Then add:

  • a concurrency limit per worker (respecting the model API's rate limits);
  • crash recovery: an interrupted task is relaunched, and the checkpointer lets it resume from the last completed step rather than from scratch;
  • a notification (webhook, email) at the end rather than repeated status polling.

Securing the API

  • Authentication on every route, and a check that the user is allowed to view and approve this note (otherwise anyone knowing an identifier could approve it).
  • Per-user rate limiting: every note costs money.
  • No internal details in public error messages: log the full exception, return a generic message.

Key takeaways

  • Long-running work is exposed asynchronously: 202 + identifier, then status checks.
  • The public identifier is the thread_id; the status is derived from graph.get_state() (values, interrupts, next nodes).
  • Background task errors are caught and exposed as a status.
  • In production: Postgres checkpointer (psycopg[binary]), then a real task queue with workers, authentication and rate limiting.

Hands-on

  1. Run uvicorn atlas.api:app --reload (in offline mode) and walk through the life cycle with curl or the /docs interface.
  2. Start a local Postgres (with Docker, for example), set ATLAS_DB_URI, create a note, restart the server, then approve it: the approval must work.
  3. Add a GET /briefs/{id}/trace route returning the run's tracing summary.

Resources