Repository navigation
System Architecture
Deep dive into the architecture and design decisions.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User's Browser β
β (React Frontend) β
β http://localhost:3000 β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β HTTP/REST
β
ββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ
β FastAPI Backend β
β http://localhost:8000 β
β ββββββββββββββ ββββββββββββββ ββββββββββββββββ β
β β Query β β Ollama β β Database β β
β β Handler ββββ Client β β Client β β
β ββββββββββββββ ββββββββββββββ ββββββββββββββββ β
ββββββββββ¬ββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββ
β β β
β β β
ββββββββββΌββββββ ββββββΌβββββββ ββββββββββΌβββββββββ
β Ollama β β Ollama β β PostgreSQL β
β Service β β Models β β + pgvector β
β (LLM Runtime)β β (Local) β β β
ββββββββββββββββ βββββββββββββ βββββββββββββββββββ
Technology Stack:
- React 18
- Vite (build tool)
- Modern CSS (no frameworks)
- Fetch API for HTTP requests
Key Files:
-
App.jsx- Main component -
App.css- Styling -
main.jsx- Entry point
Responsibilities:
- User interface rendering
- User input handling
- API communication
- Result visualization
- Error handling
Design Patterns:
- Functional components with hooks
- State management with useState
- Side effects with useEffect
- Component composition
Technology Stack:
- FastAPI (web framework)
- Uvicorn (ASGI server)
- psycopg3 (PostgreSQL driver)
- Requests (HTTP client for Ollama)
Key Components:
- FastAPI App: HTTP endpoint definitions
- CORS Middleware: Cross-origin request handling
- Pydantic Models: Request/response validation
User Question
β
Schema Context Retrieval
β
LLM Prompt Construction
β
Ollama API Call
β
SQL Generation
β
Safety Validation
β
Query Execution
β
Result Formatting
β
Natural Language Answer- Keyword blocking (DROP, DELETE, etc.)
- Query type validation (SELECT only)
- SQL injection prevention
- Input sanitization
Schema:
employees ββ¬β departments
ββ jobs
ββ managers (self-reference)
projects βββ departments
performance_reviews βββ employees
salary_history βββ employees
ai_query_history (logs)
employee_embeddings βββ employees (optional)
department_embeddings βββ departments (optional)
Indexes:
- Primary keys (automatic)
- Foreign keys (automatic)
- Custom indexes on frequently queried columns
- HNSW indexes for vector search (optional)
Connection Management:
- Connection per request (simple)
- Future: Connection pooling for production
Architecture:
ββββββββββββββββββββ
β Ollama Service β
β (HTTP Server) β
ββββββββββ¬ββββββββββ
β
ββββββΌβββββ
β Model β
β Runtime β
ββββββ¬βββββ
β
ββββββΌβββββ
β Models β
β (Local) β
βββββββββββ
Models:
- Llama 3.2 (2GB) - Fast, efficient
- Mistral (4GB) - Good accuracy
- Gemma4 (9.6GB) - High quality
- Qwen3.6 (23GB) - Very capable
API Endpoints Used:
-
POST /api/generate- Text generation -
GET /api/tags- List models -
POST /api/embeddings- Generate embeddings (optional)
1. User enters question in frontend
β
2. Frontend sends POST /query request
β
3. Backend receives request
β
4. Get database schema
β
5. Construct prompt with schema + question
β
6. Send to Ollama for SQL generation
β
7. Receive generated SQL
β
8. Validate SQL (safety checks)
β
9. Execute SQL on PostgreSQL
β
10. Receive query results
β
11. Format results with Ollama
β
12. Return response to frontend
β
13. Frontend displays results
- Frontend β Backend: ~10ms
- Schema retrieval: ~50ms
- Ollama SQL generation: 1-5s
- Query execution: ~100ms
- Ollama result formatting: 1-3s
- Backend β Frontend: ~10ms
Total: 2-8 seconds (varies by model and query complexity)
Layer 1: Frontend
- Input sanitization
- HTTPS (production)
- CORS restrictions
Layer 2: Backend
- Query validation
- Keyword blocking
- Rate limiting (production)
- Authentication (production)
Layer 3: Database
- Read-only user (recommended)
- Connection encryption
- Network isolation
Layer 4: Infrastructure
- Firewall rules
- SSH tunnels
- VPN (production)
Limitations:
- Single point of failure
- Limited concurrent users (~10-20)
- No load balancing
Suitable For:
- Development
- Small teams
- Personal use
Horizontal Scaling:
ββββ Backend 1 ββββ
β β
Load βββββββΌβββ Backend 2 ββββΌββββ Database
Balancer β β
ββββ Backend N ββββ
Vertical Scaling:
- More RAM for PostgreSQL
- Faster CPU for Ollama
- SSD for better I/O
Caching:
- Redis for query results
- Schema caching
- Ollama response caching
-
Indexes
CREATE INDEX idx_employees_dept ON employees(dept_id); CREATE INDEX idx_employees_salary ON employees(salary DESC);
-
Connection Pooling
from psycopg_pool import ConnectionPool pool = ConnectionPool(conninfo=DB_CONFIG)
-
Query Caching
from functools import lru_cache @lru_cache(maxsize=100) def get_schema_context(): # ...
-
Async Operations
async def execute_query(): # Non-blocking I/O
-
Response Compression
from fastapi.middleware.gzip import GZipMiddleware app.add_middleware(GZipMiddleware)
- Code Splitting
- Lazy Loading
- Asset Optimization
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)- Query count
- Response times
- Error rates
- Database connections
- Ollama performance
@app.get("/health")
async def health():
return {
"database": check_db(),
"ollama": check_ollama()
}Laptop
βββ Frontend (npm run dev)
βββ Backend (python main.py)
βββ Ollama (local)
βββ PostgreSQL (local or SSH tunnel)
ββββ Nginx ββββ
Internet ββββββββββ β (SSL/TLS) β
βββββββ¬ββββββββ
β
βββββββΌββββββββ
β Load Balanceβ
βββββββ¬ββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β β β
ββββββΌβββββ ββββββΌβββββ ββββββΌβββββ
βBackend 1β βBackend 2β βBackend 3β
ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ
β β β
ββββββββββββββββββΌβββββββββββββββββ
β
βββββββΌββββββββ
β PostgreSQL β
β (Managed) β
βββββββββββββββ
β
Modern, fast, async support
β
Automatic API documentation
β
Type safety with Pydantic
β
Easy to learn and use
β
Component-based architecture
β
Large ecosystem
β
Fast rendering
β
Easy state management
β
100% local (privacy)
β
No API costs
β
Easy to use
β
Multiple model support
β
Robust and reliable
β
pgvector for embeddings
β
Advanced query features
β
Open source
- WebSocket support for streaming
- GraphQL API option
- Microservices architecture
- Event-driven design
- Kubernetes deployment
- Multi-database support