Skip to content
luchersouPublic

About

SaaS for document analysis with RAG — Next.js, NestJS microservices (choreographed saga over RabbitMQ), and a Python/FastAPI service for retrieval and chat.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Clarus

Turn financial documents into precise, structured answers.

Clarus is a SaaS platform for financial document analysis. Users upload contracts, invoices, and reports, then either run structured actions (Summary, Extract values, Deadlines, Comparison) or chat with their documents. Answers are generated with retrieval-augmented generation (RAG), grounded in the content of the user's own files.

Live demo

clarus-delta.vercel.app

Watch a walkthrough video

The backend services run on Render's free tier, which puts them to sleep after a period of inactivity. Before trying the demo, open each health check link below once — this wakes up the services, which can take 30-60 seconds. Without this, the first request may fail with an error page.

Service Health check
API Gateway clarus-api-gateway.onrender.com/health
documents-service clarus-documents-service.onrender.com/health
analysis-service clarus-analysis-service.onrender.com/health
rag-service clarus-rag-services.onrender.com/health

Features

  • Document upload with asynchronous processing (text extraction, chunking, embeddings)
  • Four structured analyses per document, with status tracking (pending, completed, failed) and retry
  • Daily analysis quota per user, with the credit refunded when an analysis fails
  • Streaming chat over the user's documents (Server-Sent Events)
  • Sign-in with Google, GitHub, or email and password
  • Account management: profile, email, password, connected accounts, sessions, account deletion
  • Per-user data isolation

Architecture

flowchart LR
    Web["Web<br/>Next.js"] -->|REST| GW["API Gateway<br/>NestJS"]
    GW -->|"HTTP (upload)"| DOC["documents-service<br/>NestJS"]
    GW -->|RPC| DOC
    GW -->|RPC| ANA["analysis-service<br/>NestJS"]
    GW -->|"HTTP + SSE (chat)"| RAG["rag-service<br/>FastAPI"]
    DOC <-->|events| MQ{{RabbitMQ}}
    ANA <-->|events| MQ
    RAG <-->|events| MQ
    DOC --> PG[("PostgreSQL<br/>+ pgvector")]
    ANA --> PG
    RAG --> PG
    Web -.->|auth| SB["Supabase Auth"]
    GW -.->|JWT validation| SB
    DOC -.->|files| ST["Supabase Storage"]
    RAG -.->|files| ST
    RAG -.->|completions| LLM["Groq"]
    RAG -.->|embeddings| EMB["Google Gemini"]
Loading

Event flows

sequenceDiagram
    participant DOC as documents-service
    participant MQ as RabbitMQ
    participant RAG as rag-service
    participant ANA as analysis-service

    Note over DOC,RAG: Document processing
    DOC->>MQ: document.uploaded
    MQ->>RAG: document.uploaded
    RAG->>MQ: document.embedded / document.embedding_failed
    MQ->>DOC: mark as PROCESSED / FAILED

    Note over ANA,RAG: Analysis (reserve credit, validate, run, consume or refund)
    ANA->>ANA: create PENDING, reserve 1 quota credit
    ANA->>MQ: analysis.requested (via outbox)
    MQ->>DOC: analysis.requested
    DOC->>MQ: analysis.document_validated / analysis.rejected
    MQ->>RAG: analysis.document_validated
    RAG->>MQ: analysis.completed / analysis.failed
    MQ->>ANA: COMPLETED + consume credit / FAILED + refund credit
    Note over ANA: no reply within the timeout: FAILED + refund credit

    Note over DOC,ANA: Document deletion
    DOC->>MQ: document.deleted
    MQ->>ANA: delete the document's analyses
    MQ->>RAG: delete the document's chunks
Loading

Services

Service Stack Responsibility
web Next.js (App Router), TypeScript, Tailwind CSS v4, shadcn/ui Landing page, authentication, dashboard
api-gateway NestJS Single entry point: validates the Supabase JWT and routes requests to the services. No database
documents-service NestJS, Prisma Document lifecycle: upload, listing, status, soft delete. Validates analysis requests (saga step)
analysis-service NestJS, Prisma Analysis requests and results, daily quota, outbox and saga timeout
rag-service Python, FastAPI, Pydantic, SQLAlchemy, Alembic, PgVector Text extraction, embeddings, retrieval, LLM calls, chat
event-contracts TypeScript, Zod Shared messaging topology and event schemas

Design decisions

Distributed on purpose. Clarus is split into services to practice what that requires: a choreographed saga with compensation, a transactional outbox, at-least-once delivery, and contracts shared across two languages. At its current size, a real product wouldn't need this. I'd build one API (documents, analyses, quota, chat retrieval) on a single database, plus a worker behind a queue for the slow, costly AI work (text extraction, embeddings, analyses). The saga would become a transaction and the gateway would disappear. I'd only split further if there were separate teams, very different scaling needs, or isolation requirements.

Choreographed saga instead of orchestration. The flows (upload to embedding, analysis request to result) are short and linear, so each service just publishes an event when its step finishes and the next one reacts. There is no central coordinator to build and keep in sync with every service, and no extra hop between steps, which keeps latency low. The trade-off is that the full flow isn't defined in one place; with few services and events, all named in a single shared package, that cost stays small.

The analysis saga has real compensation. Each analysis reserves one credit of the user's daily quota. documents-service checks the document before anything runs; if it rejects the request, if rag-service fails, or if no reply arrives before the timeout, analysis-service fails the analysis and refunds the credit. A completed analysis consumes it.

Reliable publishing. analysis-service writes analysis.requested to a transactional outbox together with the analysis, and a relay publishes it after the commit, so a broker outage can't leave an analysis that was never announced. Delivery is at-least-once: rag-service records the analyses it ran and skips redelivered ones, and analysis-service rejects stale writes with an optimistic status check.

Three communication styles, each where it fits.

  • Events over RabbitMQ (topic exchange) for saga steps between services.
  • RPC over RabbitMQ, using the same library, for reads and commands from the gateway to the NestJS services.
  • Plain HTTP where the payload is not message-shaped: multipart upload from the gateway to documents-service, and streamed chat responses (SSE) from rag-service.

Clean Architecture in the NestJS domain services. Each service is split into domain, application, infrastructure, and presentation, with dependencies pointing inward. Entities hold the business rules, and use cases depend on ports (repositories, plus file storage and an event publisher in documents-service) that Prisma, RabbitMQ, and Supabase Storage implement, so business logic never depends on them and each one can be swapped without touching it. In analysis-service, events are recorded by the entity and saved to the outbox by the repository, so its use cases need no publisher port.

Shared contracts across two languages. @clarus/event-contracts holds the exchange, queue, and routing key names and the Zod schemas for events, used by every TypeScript service. For the structured events that cross into Python, the same shapes are also published as JSON Schema, and the Pydantic models in rag-service are generated from them instead of being written by hand. The Python side still declares its own exchange, queue, and routing key names, and builds the two simple *_failed payloads as plain dicts, so those must be kept in sync manually.

Per-user isolation. Each user is their own tenant. The gateway derives the user ID from the validated Supabase JWT and never trusts one sent by the client. Use cases verify ownership and return "not found" instead of "forbidden" on a mismatch, so the existence of other users' resources isn't revealed.

One PostgreSQL instance, one schema per service. Logical isolation without running a database per service: schemas are managed independently, and services reference each other by ID only, with no cross-schema foreign keys. NestJS services use Prisma's multi-schema support; rag-service uses SQLAlchemy and Alembic, with pgvector for embeddings.

Repository structure

.
├── apps/
│   ├── web/                  # Next.js frontend
│   ├── api-gateway/          # NestJS gateway
│   ├── documents-service/    # NestJS + Prisma
│   ├── analysis-service/     # NestJS + Prisma
│   └── rag-service/          # FastAPI
├── packages/
│   └── event-contracts/      # Shared topology and event schemas
├── docker-compose.yml        # RabbitMQ + PostgreSQL (pgvector) for local development
├── init-schemas.sql          # Creates one schema per service
└── pnpm-workspace.yaml

Getting started

Prerequisites

  • Node.js (LTS) and pnpm
  • Python and uv
  • Docker
  • A Supabase project with Google and GitHub providers enabled, plus a Storage bucket named documents for uploaded files
  • API keys for the LLM and embedding providers used by rag-service

Run locally

# 1. Start RabbitMQ and PostgreSQL (schemas are created automatically on first run)
docker compose up -d

# 2. Create a .env file in each service (each service's README lists its variables)

# 3. Install dependencies, run the Prisma migrations, and apply the rag-service migrations
pnpm run setup

# 4. Build the shared contracts (the NestJS services import the compiled output)
pnpm build:contracts

# 5. Start every service in a single terminal
pnpm dev

pnpm dev runs the web app, the API gateway, and the three domain services together. The web app is served at http://localhost:3000, the gateway at http://localhost:3001, and RabbitMQ's management UI at http://localhost:15672 (guest / guest). Run pnpm build:contracts again whenever packages/event-contracts changes.

Use pnpm run setup, not pnpm setup, which is a built-in pnpm command.

Tests

documents-service and analysis-service have integration tests that run against a real PostgreSQL and RabbitMQ started with Testcontainers (Docker must be running):

pnpm --filter documents-service test:integration
pnpm --filter analysis-service test:integration

About

SaaS for document analysis with RAG — Next.js, NestJS microservices (choreographed saga over RabbitMQ), and a Python/FastAPI service for retrieval and chat.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages