Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 68

Designing Agent API Interfaces

Recommended resources

Introduction

In our last lesson, we architected the internal engine of our agent service, designing a scalable, asynchronous system using message queues to decouple task ingestion from execution. This event-driven backbone is crucial for reliability, but it remains an internal mechanism. Now, we must design the "front door" — the public contract that exposes our agent's capabilities to the outside world.

This lesson focuses on designing the API interfaces for our agent service. We will explore various communication patterns, including synchronous request-response, asynchronous polling, streaming, and webhooks. Given your background in distributed systems and API design, we will treat this as a system design exercise, analyzing the trade-offs of each pattern and defining a robust, production-ready contract. The goal is to create an interface that is not only functional but also resilient and developer-friendly, capable of handling the unique challenges posed by long-running, non-deterministic agent tasks.


The Problem with Synchronous APIs for Agentic Workflows

Many introductory agent examples expose a single, synchronous /invoke endpoint. A client sends a request and holds the connection open, waiting for the agent to complete its entire reasoning loop and return a final answer. While simple, this pattern is fundamentally unsuited for production.

We Need to Talk About AI Agent Architectures

The video "We Need to Talk About AI Agent Architectures" effectively critiques this common anti-pattern.

Watch the initial segment from the beginning. The speaker highlights how this direct, synchronous model fails when faced with real-world requirements for reliability, cost control, and coordination of multi-step processes.

The core issue is a mismatch between the synchronous nature of HTTP and the asynchronous, often long-running nature of agent tasks. An agent might need to perform multi-step research, call several slow external tools, or even wait for human-in-the-loop approval. A synchronous HTTP connection is a fragile and expensive resource to hold open for an unpredictable duration.

Avoiding long running HTTP API requests.

To frame the solution, the video "Avoiding long running HTTP API requests" offers a clear analogy.

Watch the introduction from the start, which explains why a simple request-response model is insufficient for long-running work and introduces the fundamental pattern of offloading the work asynchronously.

This leads us to the foundational pattern for any robust, long-running task execution system, including our agent service.


The Asynchronous Job Pattern: The Reliable Default

Instead of making the client wait, we decouple task submission from task execution. This is the bedrock of our API design.

Async Agent Workflows: Designing for Long-Running Tasks

The article "Async Agent Workflows" provides an excellent first-principles explanation of this pattern. It's a pragmatic guide to designing APIs for exactly the kind of system we're building.

First, read the section "The Fundamental Mismatch," which elaborates on the problem we just discussed. Then, study the core solution in "The Async Job Pattern."

As the article outlines, the flow is straightforward and robust:

  1. Submit Task: The client sends a POST request to an endpoint like /tasks with the agent's instructions.
  2. Accept Task & Return Handle: The server validates the request, creates a task record in the state store (as designed in our backend architecture), places a corresponding event on the message queue, and immediately returns a 202 Accepted status. The response body contains a unique task_id.
  3. Poll for Status: The client uses the task_id to periodically send a GET request to a status endpoint, like /tasks/{task_id}.
  4. Retrieve Result: The status endpoint will initially show the task as pending or working. Once the agent worker completes the task, the status endpoint returns completed along with the final result.

This design gives us a simple, stateless, and reliable API. The client is free to disconnect after submission, and the server's agent workers can process tasks at their own pace.

A minimal task resource might look like this:

{
  "taskId": "c7a4d5e6-8f29-4b1d-a0b3-9f8c6d7e5a4b",
  "status": "working", // pending, working, completed, failed, cancelled
  "createdAt": "2023-10-27T10:00:00Z",
  "lastUpdatedAt": "2023-10-27T10:05:00Z",
  "result": null // or the final output when 'completed'
}

Fortifying the API: Idempotency is Non-Negotiable

What happens if a client sends the POST /tasks request, but the network connection drops before the 202 Accepted response is received? The client doesn't know if the task was created. The natural reaction is to retry. Without a specific mechanism to handle this, a retry would create a second, duplicate agent task, wasting resources and potentially causing dangerous side effects if the agent interacts with external systems.

Async Agent Workflows: Designing for Long-Running Tasks

This is where idempotency keys become essential. Let's return to the "Async Agent Workflows" article to understand their implementation.

Read the section "Idempotency Keys." Pay close attention to how the server uses a client-generated key to recognize and de-duplicate retry attempts.

By requiring clients to include an Idempotency-Key header (e.g., a UUID), our API Gateway or initial request handler can check if it has seen that key before. If so, it returns the status of the original task instead of creating a new one. This makes the submission endpoint safe to retry, a critical feature for any production-grade API.


A Spectrum of Communication Patterns

While the polling pattern is our reliable foundation, other patterns serve different needs, particularly around latency and real-time feedback.

A visual comparison of the data flow in polling versus webhook communication patterns. Polling is client-driven and pull-based, while webhooks are server-driven and push-based.

This diagram clearly contrasts the "pull" nature of polling with the "push" nature of webhooks.

Async Agent Workflows: Designing for Long-Running Tasks

The "Async Agent Workflows" article provides a superb decision framework for choosing between these patterns.

Please read the section "Polling vs. Webhooks." This section grounds the discussion in practical reliability concerns.

Let's summarize the key patterns and their trade-offs:

  • Polling (Request-Response):

    • Mechanism: Client periodically calls GET /tasks/{task_id}.
    • Pros: Highly reliable, simple for the client, works in any network environment. The state is always managed by the client pulling from the server.
    • Cons: Introduces latency (the client only learns of completion at the next poll), can generate unnecessary traffic.
    • Best for: The default, fallback mechanism. The source of truth for task status.
  • Webhooks:

    • Mechanism: Client provides a callback_url during task creation. The server sends a POST request to this URL upon task completion.
    • Pros: Low latency, efficient (no polling traffic). The server notifies the client immediately.
    • Cons: Less reliable. The client must expose a public endpoint, which can be complex or impossible. Notifications can be missed if the client is down.
    • Best for: An optimization on top of polling for server-to-server integrations where the client can easily receive inbound requests. Webhooks should always be signed to verify their origin.
  • Streaming (WebSockets / Server-Sent Events):

    • Mechanism: Client establishes a persistent connection (e.g., WS /tasks/{task_id}/stream) to receive real-time updates.
    • Pros: Provides immediate, low-latency feedback throughout the agent's execution, not just at the end.
    • Cons: More complex to implement and manage stateful connections on the backend.
    • Best for: User-facing applications where showing the agent's "thought process" (e.g., ReAct logs, intermediate tool outputs) or streaming a final result (e.g., token-by-token generation) dramatically improves the user experience.

Our backend architecture diagram already anticipates this need for multiple interface types.

This diagram shows a backend system with a FastAPI server exposing both REST endpoints (for polling and webhook submission) and WebSockets (for streaming), which aligns perfectly with our multi-pattern API design.

A Formal Protocol for Asynchronous Tasks

The patterns we've discussed are common in ad-hoc API designs. However, for interoperability, formal specifications emerge. The Model Context Protocol (MCP) provides a great example of how these async concepts can be standardized. While we are not implementing MCP, studying its design provides deep insight into building a robust and comprehensive async API.

MCP Async Tasks: Building long-running workflows for AI Agents — WorkOS

This article details the async task specification within the Model Context Protocol. It's a masterclass in designing a flexible and explicit async communication layer.

Focus on the following concepts: Skim the introduction to understand the motivation: "Why MCP Tasks are a big deal." Understand how a task is created by "augmenting" a normal request: "How to create an async task." See how interactive steps are handled with a specific status: "Handling input_required." Note the separation of concerns between getting status and getting the final data: read "Polling for status" and "Retrieving results."

Key takeaways from the MCP design that we can apply to our own system:

  • Explicitness: The protocol doesn't guess. Both client and server negotiate which operations can be asynchronous.
  • State Machine Granularity: The input_required status is a brilliant formalization for handling human-in-the-loop steps, pausing the task until the client provides more information.
  • Separation of Status and Result: Having distinct endpoints for polling status (tasks/get) and fetching the final payload (tasks/result) is a clean design that prevents the status object from becoming bloated with potentially large result data.

Conclusion

In this lesson, we designed the external API interfaces for our agent service, moving from the fragile synchronous model to a robust, multi-pattern asynchronous architecture. We've defined the contracts that allow clients to submit tasks, monitor their progress, and receive results in a way that aligns with the realities of long-running, non-deterministic work.

Key Takeaways:

  • Default to Asynchronous: The asynchronous job pattern (submit and poll) is the most reliable foundation for an agent API, decoupling the client from the execution lifecycle.
  • Idempotency is Essential: Using client-generated Idempotency-Key headers is non-negotiable for building a reliable task submission endpoint that is safe to retry.
  • Choose the Right Pattern for the Job:
    • Polling is the reliable workhorse.
    • Webhooks are a push-based optimization for server-to-server communication.
    • Streaming (via WebSockets/SSE) is for providing real-time, in-progress updates, crucial for interactive user experiences.
  • Learn from Formal Protocols: Studying specifications like MCP provides battle-tested ideas for designing clean, explicit, and extensible API contracts.

Preview of the Next Lesson:

Our system now has a robust internal engine and a well-defined external API. However, for production use, especially in enterprise contexts, we need traceability. In our next lesson, we will design an audit logging system for compliance and traceability of all agent decisions and actions. We will define what to log, where to store it, and how to ensure every action taken by an agent can be reviewed and understood.