1 Introduction: What to Do Before Writing Code?
Imagine an executive or enterprise stakeholder approaches you with enthusiasm:
“We want an AI system that automatically reads all incoming supplier invoices and enters the data straight into our accounting software!”
A junior developer might immediately begin brainstorming implementation syntax:
A Senior AI Engineer, however, never rushes into code. Instead, they step back and interrogate the problem across 11 diagnostic dimensions:
11 Diagnostic Questions Every AI Engineer Asks Before Coding:
Without answers to these questions, selecting an architecture is mere guesswork. Multiple viable architectures exist for every problem; the right choice is dictated strictly by constraints, risk, and unit economics.
Core Tenet: Never start with the technology. Start with the problem, analyze the constraints, and let the requirements dictate the architecture.
2 From Business Problem to Technical Solution: The 5 Layers
Building an enterprise AI application requires transitioning sequentially through 5 distinct layers of abstraction:
Business Problem (The pain point)
↓
Business Requirements (Desired outcomes & ROI)
↓
Technical Requirements (System specs & behavior)
↓
Architecture Decisions (Component topologies & patterns)
↓
Implementation (Code, models, testing & deployment)
What organizational bottleneck exists? Example: Accounts payable employees spend 3 hours daily manually typing invoice figures, causing billing delays and duplicate payment errors.
What measurable metrics define success? Example: Reduce manual entry time by 80%, shorten processing turnaround from 24 hours to 10 minutes, and keep data entry discrepancy rates below 1%.
What must the software system do? Example: Ingest PDFs/images, extract structured fields into strict schemas, validate arithmetic relationships, and persist approved records in PostgreSQL.
How will the components be arranged? Example: Secure S3 bucket, Redis message queue, background Celery workers, multimodal LLM extraction, deterministic validator, and human review split-screen.
Executing the blueprint. Example: FastAPI backend, Next.js frontend, Pydantic schema validation, OpenTelemetry distributed tracing, Docker containers, and CI/CD pipelines.
3 Should You Use AI in the First Place? (The Decision Framework)
No! AI is not the solution for every software problem. Forcing an LLM or neural network onto a problem that standard code can solve introduces unnecessary latency, financial waste, and non-deterministic fragility.
A senior engineer always matches the task to the most efficient and reliable computational mechanism:
| Problem Type | Optimal Solution | Rationale |
|---|---|---|
| Tax calculations or currency sums | Standard Code (Python / JS) | Math is 100% deterministic; native code runs in microseconds with zero hallucinations. |
| User permission / RBAC verification | Authorization Middleware | Security requires strict boolean guarantees; never delegate authorization to probabilistic prompts. |
| Querying a customer order by ID | Indexed SQL Database Query | Database queries return exact records in 1ms with ACID guarantees. |
| Filtering server logs for error codes | Keyword / Regex Search | Exact string matching is trivial and free; using vector embeddings or LLMs is wasteful. |
| Extracting data from unpredictable layouts | OCR + AI Vision Extraction | Document layouts vary endlessly; neural vision models excel at contextual comprehension. |
| Synthesizing answers across corporate handbooks | RAG (Hybrid Search + LLM) | Synthesizing natural language summaries with exact source citations requires language models. |
| Dynamic multi-step goal execution | AI Agent / State Machine | Autonomous tool selection and recovery from unexpected tool responses require agentic loops. |
| Forecasting next month's sales revenue | Statistical ML (LightGBM/ARIMA) | Numeric time-series forecasting is best solved by classical gradient boosted trees or statistical models. |
5-Question Decision Framework
If yes → Write standard procedural code. Never use AI where deterministic logic works.
If key-value or indexed lookup suffices → Query SQL or Redis directly.
If parsing human text, semantic meaning, or layout images → AI models are the right tool.
If grounded in private company handbooks → Integrate a Retrieval-Augmented Generation (RAG) pipeline.
If steps are fixed → Use deterministic state machines. If runtime decision-making is necessary → Employ an AI agent.
4 The 4 Categories of Requirements
Production AI engineering demands categorizing specifications across 4 distinct layers:
4.1 Business Requirements
Focus: ROI & OutcomesThe core economic rationale. Example: Reduce manual entry hours by 70%, lower processing turnaround from 24 hours to 5 minutes, and ensure operating costs stay within defined budget caps.
4.2 Functional Requirements (FRs)
Focus: System Actions & Behaviors4.3 Non-Functional Requirements (NFRs)
Focus: Performance, Security & Reliability4.4 AI-Specific Requirements
Focus: Quality, Validation & Safety5 User Stories & Acceptance Criteria
To bridge human user intent with technical execution, software engineering utilizes User Stories paired with verifiable Acceptance Criteria.
Standard User Story Format:
I want [feature / capability],
So that [business benefit].
Concrete Example: “As an accounts payable clerk, I want to drag and drop PDF invoices onto the portal, so that I don't have to manually re-type invoice line items into the ERP system.”
Gherkin Acceptance Criteria (Given-When-Then)
Scenario: Successful file upload and worker dispatch
Given an authenticated user with accounting permissions
When they submit a valid PDF invoice under 10MB
Then the system saves the file to encrypted object storage
And issues a unique `job_id` with state "QUEUED"
And dispatches a background task for AI extraction.
6 Measuring Quality in an AI System (The 6 Core Metrics)
“The app works well” is not an engineering metric. Operating AI systems in production demands continuous measurement across 6 concrete KPIs:
The percentage of target fields extracted correctly across an evaluation batch.
For critical identifiers (Invoice Number, Tax ID), partial semantic similarity is worthless; outputs must match character-for-character.
Total elapsed time from file submission to finalized database record. Measure total user experience, not just the isolated LLM inference duration.
Total blended infrastructure spend per successfully processed invoice.
The fraction of tasks requiring manual intervention. (Target: under 10–15% for scalable systems).
Classifying errors into root causes: (1) Provider timeouts/outages, (2) Schema validation errors, (3) Corrupt/unreadable source documents.
7 System Constraints: Boundaries of Viability
Every software architecture operates within strict boundary conditions:
Real-time chat requires sub-second token streaming; background document extraction easily tolerates 15–30 seconds.
50 invoices daily run fine on a single server; 100,000 invoices demand distributed message queues and auto-scaling worker nodes.
If an automated invoice saves $0.20 of human labor but costs $0.25 in API tokens, the application is economically unviable.
Digital vector PDFs, handwritten receipts, multilingual tables, and low-res mobile scans require resilient preprocessing pipelines.
Adhering to strict enterprise data residency rules, Zero Data Retention (ZDR) agreements, and rigorous multi-tenant data isolation.
8 Architectural Archetypes for AI Products (3 Core Patterns)
In real-world systems, requirements and scale dictate which of 3 primary architectural topologies to implement:
Option A: Synchronous Request-Response
Low Volume / Simple ToolsOption B: Queue-Based Asynchronous Architecture
Mid to High ScaleOption C: Document Pipeline with Human Review
Enterprise Standard9 Architecture Decision Matrix
| Evaluation Criteria | Option A: Synchronous | Option B: Queue-Based | Option C: Pipeline + Review |
|---|---|---|---|
| Initial Setup Complexity | Minimal (1–2 days) | Moderate (1–2 weeks) | High (3–4 weeks) |
| Heavy Files / Long Inference | Poor (Timeout risk) | Excellent | Excellent |
| Background Retries & Resilience | Negligible | Native Support | Built-in Circuit Breakers |
| Status Tracking & Progress | Browser Spinner | Polling / WebSockets | Comprehensive Audit Trail |
| Human-in-the-Loop Safety | Unsuitable | Requires Custom Addons | Core Architectural Pillar |
10 MVP vs. Production System: The Maturation Curve
An MVP (Minimum Viable Product) validates core technical hypotheses with minimal code. An MVP, however, is not a hardened production platform.
- Basic file upload form and simple UI.
- Direct backend-to-model API calls.
- Core Pydantic schema validation.
- Single relational database storage.
- Basic try-catch exception handling.
- Encrypted S3 object storage with RBAC controls.
- Asynchronous queue workers with exponential backoff.
- FinOps token metering and real-time cost tracking.
- OpenTelemetry distributed tracing and Slack alerting.
- Automated CI evaluation suites on golden datasets.
- Rate limit throttling and multi-provider failovers.
11 Architecture Decision Records (ADRs)
Six months after launch, a new engineer might ask: “Why did we introduce Redis queues instead of calling the LLM directly in the HTTP handler?” An Architecture Decision Record (ADR) preserves that historical context.
Multi-page PDF parsing, OCR, and multimodal LLM inference take between 8 and 30 seconds. Synchronous HTTP requests risk cloud load balancer timeouts (HTTP 504) and cause severe thread starvation under concurrent traffic.
We will decouple file submission from processing by issuing a unique `job_id` immediately from FastAPI and offloading execution to Redis and Celery/BullMQ workers.
Client requests return in under 200ms; zero dropped connections; workers automatically retry failed API calls with exponential backoff.
Requires managing a Redis cluster and implementing frontend job status polling or Server-Sent Events.
12 Comprehensive Case Study: Enterprise AI Invoice Processing Architecture
Below is the end-to-end architecture dataflow for an enterprise processing 10,000 monthly supplier invoices:
Accounting Employees
|
v
Frontend (Next.js Dashboard)
| HTTPS Upload
v
Backend API (FastAPI)
|
+----------------+----------------+
| |
v v
Authentication (RBAC) S3 Object Storage
Session / Audit Log | (File Saved)
v
Redis Task Queue
|
v
Background Workers
|
PDF Text / OCR Engine
|
Structured AI Extraction
(GPT-4o / Claude Vision)
|
Pydantic Schema Check
|
Math Rules Check
(Subtotal + Tax == Total)
|
+------------------------+------------------------+
| (Validation PASSED) | (Validation FAILED)
v v
Automatic Approval Human Review Screen
| (Side-by-side Diff)
| |
+------------------------+------------------------+
|
v
PostgreSQL ERP Database
|
v
External Accounting System
13 Hands-on Exercise: Blueprint Your Own AI Product Requirements
Apply the 6-part specification framework to design your chosen application (e.g., Customer Support Copilot, Legal Research Assistant, or Coding Agent):
14 Self-Assessment: Knowledge Check
Question 1: Why is analyzing requirements before writing code paramount in AI engineering?
Question 2: Which of the following is a Functional Requirement?
Question 3: Which of the following is a Non-Functional Requirement (NFR)?
Question 4: How should an engineer decide whether AI is necessary for a problem?
Question 5: What is the primary purpose of Acceptance Criteria?
Question 6: Why are Architecture Decision Records (ADRs) maintained?
Lesson Summary & Key Takeaways
- ✓ Problem First, Technology Second: Clarify business pain points and answer 11 diagnostic questions before writing code.
- ✓ Deterministic vs. AI: Keep arithmetic and permissions in standard code; deploy AI only for unstructured language and vision tasks.
- ✓ 4-Tier Requirements: Frame Business, Functional, Non-Functional, and AI-Specific requirements with verifiable metrics.
- ✓ Architecture Selection: Evaluate synchronous, queue-based, and human-in-the-loop review topologies against volume and risk constraints.
- ✓ ADR Stewardship: Institutionalize technical choices and trade-offs to ensure long-term architectural integrity.
Core Takeaway
“Never start with the technology—start with the requirements. First understand what must be built, why it must be built, what constraints exist, and how success will be measured. Only then select the architecture and models.”