Toggle Theme

Choosing an AI Application Tech Stack: Nine Layers from Demo to Production

Easton editorial illustration: one coherent nine-layer modular bridge with embedded model, orchestration, data, cache, queue, file, observability, permission, and deployment symbols

"The OpenAI Platform documentation groups model calls, tools, structured output, files, retrieval, and batch processing as platform capabilities, illustrating that a model API is only one layer of a production AI application."

Your Next.js backend has a single /api/chat route. It worked a few times in development, so it looked ready. On the first day with real users, four problems arrived together: requests timed out, the bill jumped, answers varied, and there were no useful logs.

A working demo is not a production system. That does not mean every project needs LangChain, RAG, a vector database, and a multi-model gateway on day one. The useful question is which layers you need now and which ones can wait.

1. From demo to real users: four failures at once

1.1 A successful API call is not production readiness

In development, you probably tested only a handful of your own requests. There was no concurrency, cost ceiling, retry policy, or active log monitoring. Real traffic exposes all four gaps at the same time.

Timeouts are the most obvious. Model latency varies, and an unset web API timeout leaves users with a blank screen or an error. A cost spike can be more abrupt: without usage monitoring or per-user limits, one long-document request can consume far more tokens than expected in a day.

Inconsistent answers confuse users as well. The same question produces different results, while an unmanaged prompt change may not apply to an older conversation. Then, when something fails, missing logs make it impossible to see the input, model output, or failing step.

These are not simply model-selection mistakes. They are missing layers in the application stack. Trace the whole request: entry, model call, response, logging, and cost accounting. Each part needs a minimum level of engineering.

1.2 A layered map of the stack

An AI application stack is more than a model plus a framework. It has nine layers, each responsible for a different class of problem.

AI application stack by layer

LayerProblem it solvesAdd it whenWait when
Model/APIModel access and capabilitiesEvery application—
OrchestrationMulti-step flows, state, long tasksWorkflows and agentsSingle requests or simple chat
Data and knowledgeStorage and retrievalBusiness data or RAGNo retrieval requirement
CachingCost and latency reductionRepeated calls or stable prefixesPersonalized or time-sensitive output
Asynchronous workLong-running processingFile parsing or batch workOnly real-time chat
File processingMultimodal inputFiles, images, or audioText-only input
ObservabilityCost, quality, and failure monitoringProduction trafficEarly demo
PermissionsMultiple users and data isolationMulti-tenant productsSingle-user tool
DeploymentReleases, rollback, and canariesProduction operationEarly demo

You do not need every layer at once. First identify the stage of the product, then add the capabilities that stage cannot safely operate without.

2. The minimum viable AI stack: demo to MVP

2.1 Seven capabilities an MVP needs

The threshold from demo to MVP is straightforward: the product should support a small amount of real traffic with basic monitoring and cost control. It does not need a complete enterprise architecture, but it does need the following baseline.

Demo, MVP, production, and enterprise stack

ComponentDemoMVPProductionEnterprise
Frontend/backend✅✅✅✅
Model API✅ One model✅ One model✅ Multi-model fallback✅ Multi-model routing
Request logs❌✅✅✅
Basic database❌✅✅✅
Error handling❌✅ Retries✅ Retries + fallback✅ Retries + fallback + degradation
Cost ceiling❌✅ Simple limits✅ Budget circuit breaker✅ Per-user budgets
Baseline monitoring❌✅ Logs + cost✅ Logs + cost + quality✅ Full observability
Orchestration framework❌❌Optional✅
Vector database❌❌When RAG needs it✅
AI gateway❌❌Optional✅
Permission isolation❌❌✅✅
Canary/rollback❌❌✅✅

A demo only proves that the model call works. An MVP adds logs, a database, error handling, a cost ceiling, and baseline monitoring. Production adds fallbacks, budget circuit breakers, permission isolation, and rollback. Enterprise systems usually add complete observability, routing, and formal orchestration.

2.2 What a demo can postpone

A demo can postpone an orchestration framework such as LangChain or LangGraph. Use a provider SDK for a single request, then add a framework when the workflow gains multiple steps.

A vector database is needed for semantic retrieval, not for every AI feature. A standalone AI gateway can wait while one provider is sufficient. Start observability with request logs and cost totals; quality evaluation and alerting can arrive before production traffic grows.

Move from simple foundations—logs, costs, limits, and error handling—to more complex layers such as orchestration, vector retrieval, and gateways. Building the heaviest possible architecture first usually slows the product down.

3. Model and API layer: choose a capability mix

3.1 Model capability matrix

Do not ask which model is universally best. Match capabilities to the work the application performs.

Model capability decisions

TaskCapability to select
General conversationA current general-purpose model from a major provider
Long-document summaryA model with a sufficiently large context window
Low-cost batch workA lower-cost model for classification, tagging, or simple Q&A
Semantic retrievalAn embedding model that converts text to vectors
Image or audio understandingA multimodal model with visual or audio input
Structured outputFunction calling or structured output support
Tool executionTool-use support

3.2 Selection rules, not a recommendation list

General-purpose models from major providers fit most conversational products because their ecosystems and documentation are mature. For long documents, choose enough context for the actual input. At high volume, cheaper models can handle classification, tagging, and simple Q&A, but they may be unreliable for complex reasoning or creative generation.

Semantic retrieval and similarity calculations require embeddings. That does not make embeddings a requirement for every application. Use multimodal models when the product must understand images or audio, such as OCR, chart analysis, or meeting transcription.

For JSON responses, choose a model with function calling or structured output so the application is less likely to fail during parsing. For external API calls or actions, use tool support, but still design the tool interface, authorization, retries, and failure handling in the application.

Model names, context windows, prices, and rate limits change. Check each provider’s current official documentation when making the actual selection.

3.3 When not to use a multi-model gateway

You can postpone a gateway when one provider meets the requirements, traffic does not need load balancing or failover, and centralized prompt management is not yet necessary.

Call the provider SDK directly in that case. Add a gateway later when the product needs routing, unified monitoring, or provider failover. The later article “AI Gateway in Practice” covers that design in detail.

4. Orchestration layer: when LangChain or LangGraph helps

4.1 An orchestration decision tree

Start with four questions.

Does the request need multiple steps—for example retrieval, reasoning, a tool call, and final generation? If yes, consider an orchestration framework. If not, continue.

Does it need state such as conversation context or tool-call history? If yes, consider a framework. If not, continue.

Does it run for minutes rather than seconds? If yes, it needs durable execution, which can be provided by an agent runtime such as LangGraph. If not, continue.

For a single request, use the OpenAI, Anthropic, or Google AI SDK directly. If all answers are no, the SDK is the lighter choice; a framework would add abstraction and dependencies without solving a current problem.

4.2 When a framework is unnecessary

Translation, summarization, and classification often follow a single request-response pattern and do not require an orchestration framework. Neither do applications without tools, multi-step reasoning, or complex state management. Conversation history can remain in the database.

Direct SDK calls keep those systems smaller. Frameworks earn their cost when the workflow is genuinely complex.

4.3 The trap in long-running, stateful agents

Do not bind a long-running model job to a web API process. It will time out, occupy resources, and be difficult to retry. Persist task state so the work can pause, resume, and recover from failure.

LangGraph and an Agent Server can provide durable execution for that class of workload. The important capability is persistence for long tasks, not the framework name itself. Short requests do not need it.

The boundaries, deployment commands, and hosted capabilities of LangChain, LangGraph, and LangSmith change over time. Verify the current official documentation before implementation.

5. Data and knowledge layer: vector storage is optional

5.1 Database capability matrix

AI applications need more than vector storage. Different data belongs in different systems.

Database types

Database typeProblem it solvesAdd it when
Relational database (PostgreSQL)Business entities, users, and conversation historyMost applications
Object storage (S3/R2)Files, documents, images, and audioThe product accepts files
Vector database (Pinecone/Weaviate/Vectorize)Semantic and knowledge-base retrievalRAG requires it
Search engine (Elasticsearch/MeiliSearch)Keywords and filtersExact keyword matching matters
Graph database (Neo4j)Relationship reasoning and knowledge graphsRelationship inference is required

A relational database stores business records, users, and conversation history. Object storage holds files and media. Vector storage supports semantic retrieval. A search engine handles keyword matching, while a graph database serves the narrower case of relationship reasoning.

5.2 When you do not need a vector database

Classification, translation, and summarization do not inherently need retrieval. General chat and code completion may not need external knowledge either. When the dataset is small and keyword search is sufficient, semantic retrieval adds complexity without enough benefit.

Use a vector database when the product actually needs RAG. For implementation details, see RAG with Workers AI and Vectorize and How RAG and agents evolve together.

6. Caching layer: three caches with different risks

6.1 Cache comparison

Caching can reduce token cost and latency, but only under the right conditions.

Three cache types

CacheProblem it solvesGood fitInvalidation risk
Prompt cache (prompt caching/context caching)Repeated prompt processing costStable prefixes, repeated calls, unchanged tool definitionsKey changes, TTL expiry, permission isolation
Embedding cacheRepeated embedding callsThe same text is retrieved repeatedlyText changes or model upgrades
Result cacheFull model-call latency and costIdentical questions with stable answersPersonalization, time sensitivity, permission isolation

A prompt cache works when system instructions, tool definitions, or long context stay stable. An embedding cache avoids vectorizing the same text repeatedly. A result cache can skip the model call, but it is unsafe for personalized or time-sensitive output unless the cache boundary is designed carefully.

6.2 Caching does not save money automatically

Cache hits require stable prefixes, repeated work, and correct permission boundaries. If the prompt changes on every request, the hit rate will remain low. Personalized and time-sensitive output needs careful invalidation, and every cache adds storage and maintenance cost.

Caching prices, supported models, TTLs, and billing fields from Anthropic, Gemini, and OpenAI change. Verify current provider documentation before implementation. The later article “Caching Strategies and Cost Control” goes deeper.

7. Async and batch layer: keep long work out of requests

7.1 Online requests versus asynchronous jobs

Separate work the user is waiting for from background processing.

Online requests include interactive chat, quick Q&A, and simple classification. They should return quickly after the user submits input.

Asynchronous jobs include PDF, image, or audio parsing; multi-document summaries; embedding recomputation; offline model evaluation; and knowledge-base indexing. Run them in the background and notify the user or expose progress.

7.2 Five jobs that belong in a queue

File parsing covers PDF extraction, OCR, and transcription. Batch summarization processes many documents. Recomputation updates embeddings or generated labels. Model evaluation runs offline on a schedule. Knowledge-base indexing vectorizes and stores new material.

None of these should be tied to a synchronous request. Users will hit timeouts, and failed jobs need an independent retry path.

7.3 Async failure modes

Users need callbacks or polling instead of an endless loading state. The queue must persist jobs and retry transient failures. Concurrency limits and priorities keep a backlog from consuming every worker.

Batch API service targets, prices, and supported models change. Gemini’s current documentation, for example, gives Batch API a target turnaround time of 24 hours. That makes it suitable for non-urgent work, not an online request path.

8. File and multimodal input layer: input is not always text

8.1 A file-ingestion checklist

Real products often accept PDFs, images, audio, and web pages. That requires a complete ingestion path.

The path includes upload rules for file types and size; malware and safety scanning; parsing such as PDF extraction, OCR, or transcription; chunking that preserves context; object storage for the source and parsed output; optional vector indexing; and source references in the generated answer.

File input is more than an upload field. For a deeper walkthrough, see the multimodal AI application development guide.

8.2 Common multimodal cases

Image understanding includes OCR and chart analysis. Audio input covers transcription for meetings or subtitles. Document parsing extracts text from PDF and Word files. URL input requires fetching and parsing web pages.

These capabilities add complexity, but many real products need them. The later article “File Processing and Multimodal Input” covers the implementation path.

9. Observability and evaluation: HTTP 500 is not enough

9.1 Three classes of metrics

Production monitoring must cover more than server errors.

Observability metrics

Metric classExamplesWhy it matters
CostPrompt tokens, completion tokens, cost by model, cost by userBudget control and alerts
QualityUser ratings, human feedback, output quality, relevanceQuality monitoring and model tuning
ReliabilityLatency, model errors, timeouts, rate-limit events, budget circuit breakersFailure detection and alerting

Cost metrics keep spending visible. Quality metrics show whether the output is useful. Reliability metrics reveal failures. A production AI application needs all three.

9.2 Baseline versus advanced observability

Baseline observability records prompts and responses, per-request token cost, model errors, and timeouts.

Advanced observability adds automated quality scoring, A/B tests, user feedback, and scheduled offline evaluation. Start the baseline at MVP, then add advanced evaluation before production complexity demands it. For a related implementation, see AI Gateway monitoring, caching, and failover.

10. Permissions and tenancy: multiple users create leakage risk

10.1 Permission risks

API keys need secrets management and rotation. User abuse needs per-user limits and budgets. Team spaces need isolated knowledge bases and conversation histories. RAG retrieval needs permission filters, caches need tenant-aware keys, and audit logs must record calls and results.

10.2 Isolate caches and RAG

Include the user or team ID in cache keys, and check authorization on cache hits. Filter RAG retrieval before returning documents so users see only material they can access. Separate tenants in both relational and vector storage.

Permission isolation is an architectural requirement, not a patch for later. For a related example, see Hyper’s company knowledge base and agentic memory.

11. Deployment and rollback: AI releases carry different risks

11.1 Pre-production checklist

Check these ten components before production.

Ten components to add before launch

ComponentWhy it mattersDemoMVPProduction
Environment variablesAPI key securityLocal .env is acceptableSecrets managementSecret rotation
Model fallbackDegrade when one model failsNot requiredOptionalRequired
Timeouts and retriesSlow or failed model responsesMay be omittedRecommendedRequired
Rate limitsPrevent abuseNot requiredRecommendedRequired
Cost trackingControl the budgetNot requiredRequiredRequired
Budget circuit breakerStop runaway billsNot requiredRecommendedRequired
Canary releaseReduce release riskNot requiredNot requiredRequired
Rollback planRecover quicklyNot requiredRecommendedRequired
Logs and monitoringDetect problemsOptionalRequiredRequired
AlertsNotify the teamNot requiredRecommendedRequired

A demo can remain simple. An MVP must add logs, cost tracking, and error handling. Production needs the full checklist.

11.2 Risks specific to AI releases

Model output is non-deterministic, so releases need evaluation and quality monitoring. Costs can jump, so a budget circuit breaker protects the account. A provider can fail, so production may need a model fallback. Long-running work can fail midway, so it needs persistence and retries.

An AI release is not just a code change. Review output quality, cost, and reliability as well. The later article “AI Application Launch Checks and Rollback” provides a deeper checklist.

12. Where to go next

This article is the entry point to the AI application stack. Each follow-up focuses on one layer.

AI Gateway in Practice: when to add a gateway, multi-model routing, unified monitoring, and failover.

Model Routing and Load Balancing: choose models by task, control cost, and degrade safely.

Asynchronous Tasks and Queue Design: retries, callbacks, and progress tracking for long jobs.

Caching Strategies and Cost Control: prompt, embedding, and result caches.

Observability, Monitoring, and Alerts: cost tracking, quality evaluation, failures, and user feedback.

Permission Isolation and Multi-Tenant Design: API keys, quotas, knowledge-base permissions, and cache isolation.

File Processing and Multimodal Input: upload, parsing, chunking, storage, indexing, and source references.

AI Application Launch Checks and Rollback: ten launch components, canary releases, and recovery.

AI Application Engineering Problems: recurring issues in cost, latency, quality, security, and maintainability.

Together, these topics build the path from a demo to a production system.

Summary

An AI application stack is a nine-layer request path: model/API, orchestration, data and knowledge, caching, asynchronous work, file processing, observability, permissions, and deployment.

From demo to MVP, add foundations first: logs, cost tracking, rate limits, and error handling. Add orchestration, vector retrieval, or a gateway only when the product needs them. Caching saves money only with stable prefixes, proper permission boundaries, and an invalidation strategy. Before launch, verify secrets, fallback, timeouts, retries, rate limits, cost tracking, budget circuit breakers, logs, and alerts.

Identify the product’s current stage, add the missing baseline layers, and expand the stack as real requirements appear.

Choose an AI application stack in six steps

Start with the real request path and decide which model, data, async, observability, permission, and deployment capabilities the product needs.

⏱️ Estimated time: 45 min

  1. 1

    Step 1: Map the request path

    List the request entry point, model calls, data reads and writes, response path, logs, and cost accounting, then identify the missing baseline capabilities.
  2. 2

    Step 2: Define model and API needs

    Select capabilities for conversation, long documents, structured output, tool calls, or multimodal input before adding more model providers.
  3. 3

    Step 3: Set the data and retrieval boundary

    Put business records in a relational database and files in object storage; introduce a vector database only when semantic retrieval is required.
  4. 4

    Step 4: Separate synchronous and asynchronous work

    Keep interactive chat on the online path, and move file parsing, batch summaries, recomputation, evaluations, and knowledge-base indexing to queues or batch jobs.
  5. 5

    Step 5: Add observability and permissions

    Track cost, quality, and failures, and isolate databases, RAG retrieval, and caches by user or tenant.
  6. 6

    Step 6: Design deployment and rollback

    Before production, add secrets management, timeouts, retries, rate limits, budget circuit breakers, canaries, alerts, and a tested rollback path.

FAQ

What does a minimum viable AI application stack need?
A minimum viable stack usually needs an application frontend and backend, one model API, a basic database, request logs, error handling, a rate or cost limit, and a deployment that can be rolled back.
Does every AI application need LangChain or LangGraph?
No. A provider SDK is lighter for single requests and simple conversations. Evaluate orchestration and durable execution when you add multi-step state machines, complex tool calls, or long-running agent tasks.
Does every AI application need a vector database?
No. Classification, translation, summarization, general chat, and keyword search often work without one. Vector storage becomes important for semantic retrieval, knowledge-base Q&A, or similarity search.
How do prompt, embedding, and result caches differ?
A prompt cache reuses stable context, an embedding cache reuses text vectors, and a result cache reuses complete answers. All three need expiration rules, clear key boundaries, and permission isolation.
When should an AI application use an asynchronous queue?
File parsing, batch summarization, long-running inference, offline evaluation, data recomputation, and knowledge-base indexing belong in an asynchronous queue rather than a user-facing request.
Which layers should you add first when moving from demo to production?
Start with request logs, error tracking, timeouts, retries, rate limits, cost budgets, data permissions, and rollback. Add multi-model gateways, complex orchestration, and automated evaluation as traffic and complexity justify them.

15 min read · Published on: Nov 24, 2026

Comments

Sign in with GitHub to leave a comment

Easton BlogEaston Blog