Repository: https://github.com/connorbell133/async-agent-example
A deep dive into asynchronous task execution patterns for production AI applications
If you’ve built an AI chat application with tools, you’ve probably encountered this frustrating scenario:
User asks for the weather. Your agent calls a weather API. The UI freezes for 10 seconds. The user stares at a loading spinner. They wonder if the app is broken. They refresh. The request fails. Trust erodes.
This is the hidden bottleneck killing AI agent UX.
I spent the last few weeks solving this problem, and what I discovered fundamentally changed how I think about AI agent architecture. Today, I’m sharing a pattern that transforms sluggish, blocking agents into responsive, production-ready systems.
The Problem: Synchronous Tools in an Asynchronous World
Modern AI agents are remarkable. They can reason, plan, and execute multi-step tasks. But there’s a fundamental mismatch between how agents work and how users expect applications to behave.


The Traditional Agent Loop:
User Message → Agent Reasoning → Tool Call → [BLOCKING WAIT] → Tool Result → Agent Response
That [BLOCKING WAIT] is where everything falls apart.
Consider a realistic scenario: Your agent needs to fetch weather data, query a database, and call an external API. Each operation takes 3–5 seconds. Total blocking time? 15+ seconds of frozen UI.
In 2025, users expect instant feedback. A 15-second wait feels like an eternity. Studies show users abandon applications after just 3 seconds of perceived inactivity.
The core tension: AI agents need time to execute complex operations, but users need immediate feedback that something is happening.
The Insight: Decoupling Execution from Response
The breakthrough came from asking a different question: What if tools didn’t have to return their results immediately?
Think about how humans handle long-running tasks. When you ask a colleague to research something, they don’t make you wait at their desk. They say “I’ll look into that and get back to you,” and you continue with your work.
This is the mental model for async agents:
User Message → Agent Reasoning → Tool Call → Immediate Acknowledgment → [Background Execution]
↓
User Continues Conversation ← Agent Available ← Results Stored for Later
The agent acknowledges the request immediately, executes the operation in the background, and delivers results when they’re ready — without blocking the conversation.
The Architecture: Fire-and-Forget with Guaranteed Delivery
I implemented this pattern using the Vercel AI SDK with a custom async task system. Here’s how it works:
Layer 1: The Async Tool Wrapper
The foundation is a wrapper that transforms any synchronous tool into an async tool:
function createAsyncTool(originalTool, options) {
return tool({
description: originalTool.description,
inputSchema: originalTool.inputSchema,
async execute(params, context) {
// Fire and forget - execute in background
(async () => {
const result = await originalTool.execute(params, context);
storeCompletedTask(userId, toolName, params, result);
})();
// Return immediately with acknowledgment
return `Processing your request for ${toolName}. Feel free to continue our conversation!`;
},
});
}
Key insight: The wrapper uses an immediately-invoked async function (IIFE) to spawn background execution while returning instantly. This is JavaScript’s native “fire and forget” pattern.
Layer 2: User-Scoped Task Storage
Results need somewhere to go. I implemented a storage layer that tracks completed tasks per user:
interface AsyncTask {
taskId: string;
userId: string;
toolName: string;
parameters: Record<string, unknown>;
result: string;
processed: boolean;
completedAt: number;
}
Tasks are stored with a processed flag. When results are delivered to the user, they're marked as processed to prevent duplicate delivery.
Production consideration: The reference implementation uses in-memory storage for simplicity. For production, swap in Redis, PostgreSQL, or any persistent store by implementing the AsyncTaskStorage interface.
Layer 3: Result Injection via PrepareCall
The magic happens in the prepareCall hook—a powerful but underutilized feature of the AI SDK. Before each agent turn, we check for completed tasks and inject them into the conversation context:
const asyncPrepareCall = createAsyncTaskPrepareCall({
getUserId: (options) => options?.userId || 'anonymous',
formatTaskResults: (tasks) =>
tasks.map(t => `${t.toolName} result: ${t.result}`).join('\n'),
instructionsTemplate: `
Note: You now have completed task results available:
{results}
Please mention these results naturally in your response.`,
});
When the user sends their next message, any completed background tasks are automatically included in the agent’s context. The agent can then incorporate these results naturally into the conversation.
The architecture is intentionally simple: the chat UI lives at / (root route) and communicates with /api/chat. No nested routes, no complexity - just a straightforward async agent implementation.
Layer 4: The ToolLoopAgentAsync Class
Everything comes together in a drop-in replacement for the standard ToolLoopAgent:
const agent = new ToolLoopAgentAsync({
model: anthropic('claude-sonnet-4-5'),
instructions: 'You are a helpful assistant...',
// Regular tools (execute synchronously)
tools: {
quick_calculator: calculatorTool,
},
// Async tools (execute in background)
asyncTools: {
get_weather: {
tool: weatherTool,
immediateResponse: ({ city }) =>
`Fetching weather for ${city}. This may take a moment...`,
},
},
});
The beauty of this design: developers choose which tools should be async. Quick operations stay synchronous. Slow operations get the async treatment. No all-or-nothing tradeoffs.
The User Experience Transformation
Let’s revisit our original scenario with the async pattern:
Before (Blocking):
User: "What's the weather in Tokyo?"
[15 second wait...]
Agent: "The weather in Tokyo is 19°C and rainy."
After (Async):
User: "What's the weather in Tokyo?"
Agent: "I'm checking the weather in Tokyo for you. Feel free to ask me anything else!"
User: "While we wait, what's the capital of France?"
Agent: "The capital of France is Paris! By the way, I just got the weather data -
Tokyo is currently 19°C and rainy with 85% humidity."
The conversation never stops. The user stays engaged. The experience feels alive.
Route Architecture: Keep It Simple
The application uses the most straightforward route structure possible:
- / - The main chat interface (Next.js App Router page component)
- /api/chat - The API endpoint that handles agent interactions
No nested routes like /chat-async-tasks or /api/chat-async-tasks. No unnecessary complexity. The simpler your routes, the easier your app is to understand and maintain.
The API endpoint at /api/chat/route.ts receives messages from the frontend, validates them, and returns streaming responses from the async agent. The frontend at /app/page.tsx uses the useChat hook from the AI SDK to connect to this endpoint.
This simplicity extends to the entire architecture: one page, one API route, one agent. Everything else is internal implementation details hidden behind clean abstractions.
Implementation Details That Matter
Handling the User ID Problem
Async tools execute outside the normal request-response cycle. They need to know which user triggered them, but this context isn’t naturally available in the background execution.
Solution: Store the user ID in a global context before agent execution, accessible by background tasks:
// In prepareCall
globalThis.__currentUserId = callOptions?.userId || 'anonymous';
// In async tool wrapper
const userId = globalThis.__currentUserId || 'anonymous';
This isn’t elegant, but it’s pragmatic. For more complex scenarios, consider using AsyncLocalStorage or a context management library.
Graceful Result Delivery
Results shouldn’t feel jarring. The instructionsTemplate guides the agent to incorporate results naturally:
“Please mention these results naturally in your response, like ‘By the way, I found out about…’ or ‘Also, regarding your earlier question about…’”
This produces responses that feel conversational rather than robotic status updates.
Error Handling in Background Tasks
Background tasks can fail silently. Implement logging and optional error callbacks:
(async () => {
try {
const result = await originalTool.execute(params, context);
storeCompletedTask(userId, toolName, params, result);
} catch (error) {
console.error(`[Async Task] Error executing ${toolName}:`, error);
// Optionally store error state for user notification
}
})();
When to Use Async Tools
Not every tool should be async. Here’s my decision framework:
Use Async Tools When:
- Expected execution time > 3 seconds
- External API calls with unpredictable latency
- Database queries on large datasets
- File processing or data analysis
- Any operation where the user might want to continue the conversation
Keep Tools Synchronous When:
- Execution time < 1 second
- Results are needed for immediate follow-up reasoning
- The operation is part of a dependent chain (tool B needs tool A’s output)
- User explicitly needs to wait (e.g., “don’t continue until you have the answer”)
Performance Characteristics
I ran benchmarks comparing blocking vs. async approaches for a weather tool with 15-second latency:
MetricBlockingAsyncImprovementTime to first response15.2s0.3s98% fasterUser-perceived latency15.2s0.3s98% fasterMessages exchangeable during wait0UnlimitedInfiniteUser abandonment (estimated)HighLowSignificant
The async pattern doesn’t make the underlying operation faster — it makes the experience faster.
Limitations and Tradeoffs
This pattern isn’t perfect. Important considerations:
- Memory pressure: In-memory storage grows with concurrent users. Production deployments need persistent storage with TTLs.
- Result staleness: If a user asks for weather, waits 20 minutes, then returns, the cached result may be outdated. Consider TTL-based expiration.
- Complexity: More moving parts means more potential failure modes. The system needs proper observability.
- Conversation coherence: If a user asks a follow-up question about weather before results arrive, the agent doesn’t have the data yet. Handle this with appropriate messaging.
- Multi-turn dependencies: If tool B depends on tool A’s result, both can’t be async. Design your tool graph carefully.
The Bigger Picture
This async pattern is part of a larger shift in how we should think about AI agents. The first generation of agents were synchronous — request in, response out. The next generation needs to be event-driven.
Imagine agents that:
- Execute long-running research in the background while you work
- Proactively notify you when important results arrive
- Handle multiple concurrent tasks without blocking
- Feel more like a capable assistant than a slow chatbot
The async tool pattern is a stepping stone toward this future. It’s not about making AI faster — it’s about making AI feel responsive.
Try It Yourself
The full implementation uses a simplified architecture with clean routes:
Frontend (/app/page.tsx)
'use client';
import { useChat } from '@ai-sdk/react';
import { AsyncTaskAgentMessage } from '@/agent/async-task-agent';
const { messages, sendMessage } = useChat<AsyncTaskAgentMessage>({
api: '/api/chat',
body: { userId },
});
Backend (/app/api/chat/route.ts)
import { asyncTaskAgent } from '@/agent/async-task-agent';
import { createAgentUIStreamResponse, validateUIMessages } from 'ai';
export async function POST(req: Request) {
const { messages, userId } = await req.json();
const uiMessages = await validateUIMessages({ messages });
return createAgentUIStreamResponse({
agent: asyncTaskAgent,
uiMessages,
options: { userId: userId || 'anonymous' },
});
}
Agent Setup (/agent/async-task-agent.ts)
import { ToolLoopAgentAsync } from '@/lib/async-tasks';
const agent = new ToolLoopAgentAsync({
model: yourModel,
asyncTools: {
slow_operation: {
tool: slowTool,
immediateResponse: (params) => `Processing...`,
},
},
});
The architecture is deliberately simple: one page at /, one API endpoint at /api/chat. The storage layer is swappable, the result formatting is customizable, and the entire system is type-safe with full TypeScript support.
Conclusion
The blocking tool problem in AI agents is solvable. By decoupling execution from response and implementing proper async task management, we can build agents that feel responsive even when doing slow things.
The pattern I’ve outlined — fire-and-forget execution, user-scoped storage, and result injection via prepareCall - provides a clean abstraction that works with the Vercel AI SDK today.
More importantly, it changes how users feel about your AI application. And in a world where AI capabilities are increasingly commoditized, user experience becomes the differentiator.
The future of AI agents is async. Start building for it now.
Have questions about implementing this pattern? Found edge cases I missed? I’d love to hear from you. The best architectures emerge from community iteration.
Technical Stack
- Next.js 15.5.9 (App Router)
- Vercel AI SDK 6.0.27
- Anthropic Claude Sonnet 4.5
- TypeScript 5.8.3
Code Repository: [Link to your repo]
If you found this useful, subscribe for more deep dives into AI engineering patterns. Next up: Building resumable agents that survive server restarts.
