How I Built TarkaBot: A Multi-Tenant WhatsApp Restaurant SaaS Using FastAPI, PostgreSQL & AI
1. Introduction
Most small to medium-sized restaurants in Pakistan rely heavily on WhatsApp to process customer orders. The standard operating procedure usually looks something like this: a customer sends a message, a staff member manually reads it, types out a confirmation, calculates the total bill on a calculator, updates the kitchen team by shouting or handing over a handwritten slip, and then manually records the transaction. The problem is that this deeply manual workflow leads to extreme delays during peak hours, human errors in order taking, and massive operational bottlenecks.
I wanted to explore whether a restaurant could operate primarily through WhatsApp while drastically reducing manual work through intelligent automation. I envisioned an AI WhatsApp Bot that wouldn't just send generic automated replies, but would actually act as a fully autonomous order-taking agent connected directly to a backend Restaurant POS.
That idea eventually became TarkaBot. TarkaBot is a robust Restaurant SaaS platform designed specifically for the Pakistani market. It functions as an end-to-end restaurant operating system that leverages a FastAPI Backend to process natural language WhatsApp messages, parse them into structured orders, and instantly beam them to a real-time kitchen dashboard.
2. The Problem I Wanted To Solve
When I started observing how local fast-food joints, dhabas, and cloud kitchens operated, the inefficiencies were glaring. The restaurant industry suffers from several recurring pain points:
- Missed Orders: During weekend rushes, staff simply cannot reply to every WhatsApp message fast enough, resulting in lost revenue.
- Slow Replies: Customers expect instant gratification. Waiting 15 minutes just to get an order confirmed leads to customer churn.
- Staff Dependency: Relying on human agents means the restaurant is limited by the typing speed and availability of its staff.
- Manual Kitchen Communication: Passing paper tickets to the kitchen is prone to getting lost or misread, delaying food prep times.
- Expensive POS Systems: Traditional Point of Sale software is often bulky, expensive, and takes a significant cut of the profits through commissions, which hurts small business margins.
During my research, I noticed that many small restaurants receive a massive volume of orders through WhatsApp but completely lack a structured workflow to convert those raw, unstructured text conversations into actionable operational tasks. They needed a system that could understand unstructured human text and output structured JSON data for the kitchen. They needed WhatsApp Automation.
3. Designing The Solution
To solve this, I needed to design an architecture that could bridge the gap between a consumer chat app and an enterprise-grade POS system. I architected a highly decoupled, event-driven flow.
The system overview looks like this: Customer → WhatsApp → AI/NLP Layer → Order Parser → Kitchen Dashboard → POS → Receipt Printing
Let's break down exactly what happens in this SaaS Architecture:
- Customer: Sends a message via WhatsApp (e.g., "bhai 2 zinger aur ek pepsi bhej do").
- WhatsApp API: Forwards the webhook payload to our backend server.
- AI/NLP Layer: Processes the Roman Urdu text, identifies the intent (ordering), and extracts entities (quantities, items, modifiers).
- Order Parser: Matches the extracted entities against the restaurant's specific database menu to validate pricing and availability.
- Kitchen Dashboard (KDS): If valid, the system instantly pushes the order via WebSockets to a live screen in the kitchen so chefs can start cooking.
- POS: The order is simultaneously logged into the Point of Sale system for accounting and analytics.
- Receipt Printing: Once complete, a receipt is generated and the customer receives an instant WhatsApp confirmation with their total bill.
4. Why I Chose FastAPI
When designing a modern web backend, the framework choice is critical. This is a system where milliseconds matter because customers expect instant chat replies.
Why didn't I use Django? Django is fantastic, but it comes with a lot of synchronous baggage and batteries I simply didn't need for a highly specialized microservice. Why not Node.js? While Node is great for async I/O, the Python ecosystem is unequivocally the king of AI integration, making it much easier to build NLP pipelines without jumping between languages.
I engineered the backend using FastAPI. FastAPI provided exactly what I needed:
- Asynchronous by Default: Since the app heavily relies on waiting for external APIs (WhatsApp Meta API, LLMs, Database), Python's async/await paired with ASGI (Uvicorn) ensures the server doesn't block while waiting for network requests.
- High Performance: Built on Starlette and Pydantic, it offers Node.js/Go-like performance.
- Clean APIs: Data validation via Pydantic means I don't have to manually write code to verify incoming WhatsApp webhook payloads; FastAPI does it automatically and returns clean 422 errors if the payload is malformed.
- Easy AI Integration: Being a Python framework, integrating libraries like RapidFuzz, LangChain, or direct LLM SDKs was seamless.
5. Building The NLP Pipeline
This was arguably the most complex and interesting engineering challenge. The AI Agent needed to understand Pakistani customers who type in Roman Urdu, using highly irregular spellings and slang.
The Challenge: People don't type like robots. They write things like:
- "2 zinger"
- "1 large pizza extra cheese"
- "coke bhi bhej dena sath"
- "bhai 2 burger aur fries laga do jaldi"
The system must accurately parse the items, match them to the exact database menu items, extract quantities, and understand modifiers.
The Solution: I designed a hybrid NLP Pipeline to ensure both speed and accuracy while keeping inference costs low.
- RapidFuzz & Fuzzy Matching: I didn't want to call an expensive LLM for every single message. First, I implemented a fast fuzzy matching algorithm using RapidFuzz. If a user types "zngr", the algorithm calculates the Levenshtein distance against the restaurant's menu items. If the confidence score is above a certain threshold (e.g., 85%), it bypasses the LLM entirely, instantly matching it to "Zinger Burger".
- LLM Fallback: However, when the user sends a complex sentence ("2 zinger baghair mayo ke aur ek extra fries"), fuzzy matching fails to capture the relationships and modifiers. When the confidence score is low, the pipeline falls back to a Large Language Model.
- DeepSeek / OpenAI: I utilized powerful LLMs to handle complex reasoning. The LLM is provided with the specific restaurant's menu context and instructed to output a strict JSON payload containing the parsed order.
6. Multi-Tenant Architecture
Because TarkaBot is a B2B Restaurant SaaS, multiple restaurants needed to use the same underlying application instance. This required a robust Multi-Tenant SaaS architecture.
The Problem: Data leakage in a SaaS environment is a catastrophic failure. One restaurant absolutely cannot, under any circumstances, see another restaurant's customer data, menus, or financial records.
The Solution: I implemented logical isolation using PostgreSQL Row Level Security (RLS) via Supabase.
Instead of deploying separate databases for each client (which is expensive and hard to maintain), I used a single PostgreSQL database with strict tenant boundaries. Every table in the database has a tenant_id column. I designed JWT mapping so that whenever a user (or the backend API) authenticates, the JWT token contains their specific tenant_id.
7. Real-Time Kitchen Dashboard
A modern restaurant cannot wait for staff to manually refresh a webpage to see new orders. The kitchen needs to know the second a customer sends a WhatsApp message.
To achieve this, I engineered a highly responsive real-time system using Supabase Realtime and WebSockets. I utilized an event-driven architecture. The moment the FastAPI backend inserts a new verified order into the PostgreSQL database, Supabase instantly broadcasts a WebSocket event to the React frontend. The Kitchen Dashboard UI seamlessly animates the new order into the "New" column without a single page reload.
8. Security Decisions
- Webhook Validation: Meta (WhatsApp) sends webhooks to the server. To ensure malicious actors don't spoof these requests, I implemented HMAC signature validation.
- Rate Limiting & Redis Caching: A public WhatsApp bot is a prime target for spam. I integrated Redis caching to keep track of user sessions and implement strict rate limiting.
- Replay Attack Protection: I implemented nonce tracking in Redis to ensure that delayed or intercepted webhook requests cannot be replayed to create duplicate orders.
9. Challenges I Faced
- Roman Urdu Inputs: Roman Urdu has no standardized spelling. Training the fuzzy matching algorithm to handle extreme variances required custom dictionaries.
- Menu Matching Collisions: Restaurants have similar menu items (e.g., Chicken Burger vs Chicken Cheese Burger). Handling this required complex dialogue state management.
- Webhook Reliability: WhatsApp webhooks can arrive out of order. I had to build a robust queueing system.
- Multi-Tenant Isolation: Writing RLS policies in PostgreSQL for relational data was incredibly complex but resulted in a bulletproof backend.
10. What I Learned
Building TarkaBot was an intense masterclass in both software engineering and product development. I learned the immense value of designing scalable APIs from the ground up, and that building software is easier than getting customers. Validation matters immensely. A beautifully written React component is useless if the restaurant owner finds the UX confusing during a lunch rush.
11. Future Roadmap
- Voice Ordering: Allowing customers to send a WhatsApp voice note, using Whisper AI to transcribe and parse it.
- Advanced Analytics: Providing restaurants with deep customer segmentation data.
- Docker Deployment: Containerizing the entire stack for easier on-premise deployments.
12. Conclusion
TarkaBot started as a localized experiment around WhatsApp Automation, but it rapidly evolved into a production-grade restaurant operating system. Building it taught me profound lessons in AI engineering, SaaS architecture, and backend scalability that go far beyond writing code.