Problem & constraints
MSME documents arrive where business already happens: WhatsApp. The input may be a photographed invoice, a PDF, a spreadsheet, or a Hinglish voice note. A useful answer has to cite the original document, respect tenant boundaries, and survive messy inputs.
The design constraint was strict: no GPU service, one primary database, and a query target under 4.5 seconds. That pushed the system toward PostgreSQL-centered retrieval, object storage for raw files, and narrow workers with explicit failure behavior.
System architecture
The service uses FastAPI with ARQ workers. PostgreSQL 16 carries relational state, pg_trgm, and pgvector embeddings stored as halfvec(1024). Row-level security scopes tenant access in the database rather than leaving isolation to application discipline.
Redis groups WhatsApp bursts inside an eight-second debounce window. Cloudflare R2 stores raw files and 150-DPI WebP page images. Extraction follows a VLM ladder: Gemini 2.5 Flash, Groq Llama-4-Scout, then OpenRouter Qwen2.5-VL through LiteLLM. Sarvam saaras:v3 handles Hinglish voice notes.
Query handling splits SQL analytics from document search. Hybrid reciprocal rank fusion combines lexical and vector evidence. The answer path returns a red-boxed citation crop from the original page image, so the user can inspect the source rather than trust a generated summary.
| Layer | Choice | Reason |
|---|---|---|
| Ingestion | WhatsApp Cloud API + Redis debouncer | Bursty forwarding does not create duplicate jobs |
| Storage | PostgreSQL + R2 | Search state stays in one database; binaries stay out of it |
| Extraction | Tiered VLM ladder | Provider failure does not stop the document pipeline |
| Query | SQL analytics + hybrid RRF | Numeric questions and document questions take different paths |
Evaluation & guardrails
The ingestion path checks legibility before extraction. Laplacian variance catches blur; resolution checks catch images too small for reliable OCR. Workers recycle after 25 jobs to contain parser memory growth. PostgreSQL RLS is treated as a hard boundary, not a cleanup step.
The repository includes a weekly promoter audit script and inspectable SQL migrations. The retrieval function is a database object, so the ranking logic can be read, tested, and versioned with the schema.
Production outcomes
The engine exists as a buildable FastAPI system with migrations, workers, webhook seams, Docker Compose services, and Linear-tracked MVP scope. I am not claiming paid usage or accuracy percentages until those are measured against client document sets.
The important outcome is architectural: document intake, extraction fallback, tenant isolation, retrieval, and visual citation are specified as one operating path. That is the part most document demos leave out.