Back to KB
Difficulty
Intermediate
Read Time
8 min

Cómo construir un agente de IA con LangChain.js y NestJS: tutorial completo

By Codcompass Team··8 min read

Architecting Production-Ready AI Agents: A Queue-Driven Approach with NestJS and LangChain

Current Situation Analysis

Integrating large language models into web applications introduces a fundamental architectural mismatch. Traditional HTTP frameworks are built around synchronous request-response cycles, expecting predictable latency and stateless interactions. LLMs, by contrast, are inherently asynchronous, stateful, and highly variable in execution time. When developers route AI calls directly through REST endpoints, they quickly encounter gateway timeouts, event loop blocking, and unmanageable scaling bottlenecks.

This problem is frequently overlooked because early-stage prototypes work flawlessly under low concurrency. A single developer testing gpt-4o via a direct HTTP call sees responses in 2-4 seconds and assumes the pattern will hold. In production, however, tool-calling agents introduce compounding latency. Each tool invocation requires a round-trip to the model, schema validation, and response parsing. With OpenAI's GPT-4o priced at approximately $5 per million tokens, a single multi-tool interaction typically consumes ~2,000 tokens. Multiply that by concurrent users, and you face three critical failures:

  1. Timeout cascades: Load balancers terminate connections after 30-60 seconds, dropping in-flight AI jobs.
  2. Resource exhaustion: Node.js event loops stall while waiting for external API responses, degrading all other endpoints.
  3. Cost blindness: Without structured job tracking, token consumption becomes untraceable, leading to unexpected billing spikes.

The industry standard solution is to decouple the HTTP gateway from the AI execution layer using a message queue. This transforms unpredictable AI workloads into durable, retryable, and observable background tasks.

WOW Moment: Key Findings

Shifting from synchronous HTTP handling to a queue-driven architecture fundamentally changes how AI agents behave in production. The table below contrasts the two approaches across critical operational dimensions:

ApproachRequest LatencyHorizontal ScalabilityFailure RecoveryToken Cost Visibility
Direct HTTP2-8s (blocks thread)Limited by worker poolLost on crashHard to track per session
Queue-Driven<200ms (async)Infinite via worker scalingBuilt-in retries & backoffGranular per-job logging

Why this matters: Queue-driven execution converts AI interactions from a blocking liability into a managed workload. BullMQ provides exponential backoff, automatic retries, and job persistence via Redis. This means a temporary OpenAI rate limit or network hiccup no longer crashes the user experience. Instead, the job pauses, retries, and completes asynchronously. More importantly, every job carries metadata (session ID, token count, tool calls), enabling precise cost attribution and debugging. You stop guessing why an endpoint timed out and start tracing exactly which tool invocation consumed the budget.

Core Solution

The architecture follows a clean separation of concerns:

HTTP Client → NestJS Gateway → BullMQ Queue → LangChain Worker
                                                    ↓
                                           Zod-Validated Tools
                                                    ↓
                                           PostgreSQL (History) / Redis (Cache)

Step 1: Queue Registration & Module Setup

BullMQ requires a Redis connection and explicit queue configuration. We register the queue with production-safe defaults: exponential backoff for transient

🎉 Mid-Year Sale — Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register — Start Free Trial

7-day free trial · Cancel anytime · 30-day money-back