Peti brings physical mail and digital documents into one workspace. Mailroom staff register and scan incoming letters, while customers can upload, search, and share documents such as invoices, bank statements, and government notices. The engineering challenge was to make documents searchable without holding open an upload request while keeping processing recoverable and access scoped to the right organisation.
Architecture and tech stack
| Layer | Stack | Role |
|---|---|---|
| Monorepo | Node.js 24, pnpm, Turborepo, strict TypeScript | Shared dependencies, tooling, and packages across three applications |
| Customer and staff apps | Next.js 16 App Router, React 19, Tailwind CSS 4, Motion, next-intl | Customer workspace and staff mailroom console with shared UI primitives. The customer app supports English, Malay, Simplified Chinese, and German. |
| API | NestJS 11, Express, Zod, Swagger/OpenAPI | Versioned domain endpoints, request validation, and a consistent response envelope with request IDs |
| Data and files | PostgreSQL 16, Prisma 6, local filesystem | Organization-scoped metadata, full-text search, and private file storage |
| Background jobs | pg-boss and BullMQ with Redis 7 | pg-boss runs OCR, extraction, and automation. BullMQ handles workloads including notifications, invoice generation, and trash purging. |
| Document processing | OCRmyPDF, Tesseract, Poppler, FFmpeg, optional Ollama | Searchable PDFs, page previews, text coordinates, and structured field extraction |
| Operations and testing | Docker Compose, Vitest, Node test runner, Playwright | Local infrastructure, worker health checks, integration tests, and browser flows |
Workspace catalogue · API dependencies · Docker Compose
How a document moves through the system
- Accept the upload. The API checks subscription access, usage, file size, and file signatures. It stores the original and creates the document record and processing run in the same database transaction.
- Make the document searchable. A dedicated CPU worker produces a searchable PDF, page text, previews, and word coordinates. It persists the results and updates the PostgreSQL search index before advancing the run to extraction.
- Extract and route. Search works in manual extraction mode. With Ollama enabled, the system extracts structured fields, checks them against source text, and flags results that need review. Configured automation rules can then queue downstream actions.
Upload service · Document pipeline · Field extraction · Automation engine
Critical engineering decisions
| Failure mode | How the system handles it |
|---|---|
| A job fails to publish or a worker stops processing | A recovery sweep republishes pending work and recovers expired leases. Deterministic job IDs limit duplicate scheduling, bounded backoff controls retries, and a lease token prevents a stale worker from committing results. Processing runs |
| OCR fails partway through a document | The worker stages new files before committing their references in a lease-checked transaction. It attempts to clean up staged files on failure. Subprocess timeouts and container resource limits bound the work. Document pipeline · OCR operations |
| An upload exceeds limits or fails after reserving quota | Batches allow up to 10 files at 25 MiB each. The service validates file signatures, returns per-file rejections for invalid inputs, and reserves usage under a database row lock. If persistence fails, it attempts to release the reservation and remove the stored file. Upload service · Quota enforcement |
| A recipient attempts to use expired or revoked access | Document access checks use organization membership and active sharing grants. Staff use a separate session. Session cookies are HttpOnly and SameSite=Lax, with Secure enabled in production. Document grants · Sessions |
| A payment provider sends the same callback again. | Stripe and Billplz adapters verify signatures. The webhook handler records provider event IDs, and the payment update uses a provider-reference upsert and an invoice row lock. Provider adapters · Payment handling |
Validation
The local Docker smoke test processed a one-page scanned PNG in 6.2 seconds, a two-page digital PDF in 4.0 seconds, and a two-page mixed PDF in 6.1 seconds. It verified page text, previews, searchable PDFs, and PostgreSQL search. These timings came from small synthetic English fixtures. Production throughput and multilingual OCR accuracy still need separate measurement. OCR smoke test results
What I would prioritise before scaling
- Payment reconciliation and API access. The current billing path logs underpayments while still marking the invoice paid. Verify the amount, currency, and provider reference before settlement. Restrict credentialed CORS to the intended customer and staff origins. Billing state changes · API bootstrap
- Upload capacity and storage durability. Multipart parsing buffers uploads, and the storage driver currently uses a local filesystem. Bound concurrent uploads, validate shared durable storage across workers, and exercise a restore of the database and original files together. Upload route · Storage driver
- Worker sizing. Benchmark by pages per document, scan quality, language mix, and peak arrival rate. Use queue age, worker memory, and database connection usage to determine replica counts. OCR scaling runbook
