# Devang Gandhi > Devang Gandhi designs, builds and ships custom CRMs, SaaS platforms, AI agents and Flutter apps end to end — for startups and enterprises in the US, UK, Australia, UAE and India. Devang Gandhi is an AI & Full Stack Developer based in Ahmedabad, India (IST, UTC+5:30). He works full-time at Passdn Technologies as a core engineer on Antoc AI, and takes freelance builds for clients in the United States, United Kingdom, Australia, the UAE and India. - Website: https://webdevang.com/ - Email: devanggandhi2222@gmail.com - WhatsApp: +917016896136 - GitHub: https://github.com/devang99999 - LinkedIn: https://www.linkedin.com/in/webdevanggandhi/ - Instagram: https://instagram.com/web.devang - Availability: Freelance · Full-time · Remote Key numbers: 300K+ leads managed in Antoc; 100+ firms run on software I built; 2 apps live on Play & App Store; 8 products shipped end to end. ## Experience ### AI & Full Stack Developer — Passdn Technologies (2024 — Present) Core engineer on Antoc AI, a real-estate CRM used by 100+ firms. Top committer on the web client; built WhatsApp automation, AI voice calling, an MCP connector for Claude, a government-tender intelligence bot, and hardened the database through a 300K-lead scale-up. Tags: Antoc AI, AI agents, Next.js, Node.js, MongoDB, GCP ### Independent Developer — Freelance (2024 — Present) Product builds for clients in India and Australia: Client Mitra, a studio CRM with apps on both stores; an audit and compliance portal for an Australian accounting firm on Azure; and HNEFA, a gaming cafe POS, with the Exlaso team. Tags: Client Mitra, Audit Portal, HNEFA, Flutter, Azure ### Software Engineer — MagellanCx (2025 — Part-time) Part-time work on MagellanCx, a scheduling and commissioning platform for large AI-infrastructure projects — helping teams plan tests, track progress and sign off every system. Tags: Scheduling, Next.js ### Open Source — Nights & weekends (Always on) Small tools I wanted to exist: Sublet for sharing AI subscriptions, PocketBridge for LAN file transfer, and Peek, an Android video player built in a day. Tags: Sublet, PocketBridge, Peek ## Tech stack - Frontend: Next.js, React, Tailwind CSS, Framer Motion, shadcn/ui - Mobile: Flutter, Android, iOS / App Store, Firebase / FCM - Backend: Node.js, Express, FastAPI, Socket.IO, Prisma - Data: MongoDB, PostgreSQL, Supabase, Redis - AI & Automation: Claude, Gemini, MCP, Groq LLaMA, WhatsApp API - Cloud & DevOps: GCP, AWS, Azure, Docker, Nginx, GitHub Actions ## Case studies ### Antoc AI — The CRM 100+ real-estate firms run on. URL: https://webdevang.com/work/antoc · Live: https://antoc.ai Platform: Web · Mobile · Category: Real-estate CRM · Role: Core engineer at Passdn Technologies; top committer on the web client. Pulls leads from Meta, Google Ads, portals and sheets into one pipeline, then works them with WhatsApp flows and an AI calling agent — for brokers and developers across India. Problem: Indian real-estate teams juggle leads from Meta ads, Google, property portals and spreadsheets, then lose them to slow follow-up. Generic CRMs don’t model projects, units or channel partners. What was built: - Unified lead capture from Meta lead ads, Google Ads, portals, Google Sheets, webhooks and public forms, with duplicate detection and auto-assignment - WhatsApp flow builder with triggers (new lead, message, reminder, stage) and an AI agent node - AI voice agent (Hinglish) that calls leads and updates stages through tool calls - OAuth-protected MCP server so Claude can work a business’s CRM data - Inventory, site-visit and call reporting, attendance, plan-based feature locking Hard parts: - Scaling past 300K leads: Index design, safe bulk operations with filter validation and database hardening as data grew. - Voice latency: VAD tuning, prompt compression and streaming to keep calls natural. - Safe AI actions: Narrow, validated tools for both the voice agent and the MCP connector. Architecture: Next.js web client → Node.js / Express API + Socket.IO → MongoDB → WhatsApp Business API → Gemini + Claude + voice stack → GCP VMs with PM2 + Nginx Stack: Next.js, Node.js, MongoDB, Socket.IO, Gemini, Claude, GCP ### MagellanCx — Commissioning without the complexity. URL: https://webdevang.com/work/magellan · Live: https://magellancx.com Platform: Web · Category: Scheduling & commissioning · Role: Part-time engineer. A scheduling and commissioning platform for large AI-infrastructure builds. Teams plan every system test, track who is doing what and when, and see progress across the whole commissioning lifecycle in one place. Problem: Commissioning a large data-centre build means thousands of system tests across levels, contractors and weeks — usually tracked in spreadsheets that are out of date the moment they are shared. What was built: - Scheduling views for commissioning tests across systems and levels - Progress tracking from first test to integrated systems testing - Checklists, sign-offs and issue tracking with an audit trail - A shared view of the whole project for owners, contractors and engineers Hard parts: - Scale: Hundreds of systems and thousands of tests per hall, all needing to stay in sync. - Many stakeholders: Owners, contractors and commissioning agents each need the right view of the same schedule. - Audit-ready records: Every test and sign-off has to be traceable later. Architecture: Next.js / React web app → Node.js services → Scheduling & progress model → Role-based access Stack: Next.js, React, Node.js, TypeScript ### Client Mitra — For studios that run on WhatsApp & UPI. URL: https://webdevang.com/work/clientmitra · Live: https://clientmitra.in Platform: Android · iOS · Web · Category: Studio CRM · Role: Solo — design to deployment. A multi-tenant CRM for Indian photography studios — enquiry to booking to payment, crew calendars for multi-day weddings, GST invoices with UPI QR, and native apps on both stores. Problem: Studios sell over WhatsApp, collect advances over UPI and schedule crews across multi-day weddings — usually across notebooks and spreadsheets. What was built: - Multi-tenant CRM: enquiry → booking → payment, per studio - Crew calendar for multi-day events, tasks and reminders - GST invoices and quotations with logo and UPI QR (PDF) - Owner / manager / staff permissions (e.g. hide money from staff) - Flutter wrapper with Sign in with Apple, IAP, FCM push and Crashlytics - Razorpay subscriptions on web; Apple in-app purchase verified server-side Hard parts: - App Store review: Added native sign-in, an IAP paywall and server-side receipt verification so the WebView app offered real native value. - Tenant isolation: Studio scoping enforced in middleware on every request. - Device quirks: Patched WebView issues on specific Android devices. Architecture: Next.js app + admin → Node.js / Express API → MongoDB → Flutter (iOS + Android) → Razorpay + Apple IAP → Firebase (FCM) → Cloudinary Stack: Next.js, Express, MongoDB, Flutter, Razorpay, FCM ### Audit Portal — Trust-account audits, minus the spreadsheets. URL: https://webdevang.com/work/audit · Live: https://app.thea1group.com.au Platform: Web · Category: Compliance · Australia · Role: Solo build for an Australian accounting firm. Built for an Australian accounting firm. Agents upload documents, auditors review and raise queries, sample 5% of properties, reconcile trust accounts and release the final report — hosted in Australia. Problem: Trust-account audits ran on email, spreadsheets and folders — hard to track, hard to sample fairly and hard to evidence. What was built: - Agent and auditor portals with document workflows and query threads - Random ~5% property sampling with saved selection runs - Bank vs ledger import with exact / strong / fuzzy auto-matching and variance tracking - Audit programme engine: sections, requirements, tests and evidence - Final report and audit pack export - Password → email OTP → TOTP sign-in Hard parts: - Data residency: Everything hosted in Azure Australia East — DB, blobs, email, backups. - Spreadsheets to engine: Turned the firm’s audit programmes into structured, testable data. - Reconciliation heuristics: Matching rules that auditors can trust and override. Architecture: Next.js (agent + admin portals) → Express API + Socket.IO → Prisma + PostgreSQL → Azure App Service, Blob Storage, Communication Email → GitHub Actions CI/CD Stack: Next.js, Express, Prisma, PostgreSQL, Azure, Socket.IO ### HNEFA — The floor, the till and the GST — one screen. URL: https://webdevang.com/work/hnefa · Live: https://hnefa.cloud Platform: Web · Category: Gaming cafe POS · Role: Contributor in the Exlaso team. Billing, stations and reports for gaming cafes in one dashboard: a live machine floor with timed sessions, touch-friendly POS for play time and snacks, bookings, inventory and a full GST-ready reports suite. Problem: Gaming cafes track machine time, snacks, prepaid balances and tax across separate tools — or paper. What was built: - Live machine floor with realtime timed sessions and bookings - Touch POS: sessions and products in one cart; cash, card, UPI - Prepaid wallets computed by database functions - FIFO inventory batches, purchases and returns - Around 15 reports including GST/HSN and P&L Hard parts: - Multi-tenancy: Postgres row-level security per tenant with role-based access. - Balance correctness: Replaced stored balance columns with computed RPCs to avoid drift. - Safe migrations: 47 versioned SQL migrations validated in CI. Architecture: Next.js + TypeScript → Supabase (Postgres, RLS, RPCs, realtime) → TanStack Query → Playwright e2e → Coolify deploys Stack: Next.js, Supabase, PostgreSQL, TanStack Query, Playwright ### Sublet — Rent AI by the hour, not the month. URL: https://webdevang.com/work/sublet · Live: https://sublet.webdevang.com Platform: Web · Category: Open source · Role: Solo · open source. An open classifieds board for sharing spare Claude and ChatGPT capacity. Post an offer or a request, chat 1:1, settle it yourselves — no payments or API keys ever touch the platform. Problem: People pay for monthly AI plans they barely use, while others need a few hours of access for one task. What was built: - Offer / seek board filtered by platform - 1:1 chat via Socket.IO with REST polling fallback on serverless - Firebase Auth + FCM push - No payments or API keys on the platform Hard parts: - Realtime on serverless: Socket.IO on a VM with automatic polling fallback on Netlify. Architecture: Next.js 16 → MongoDB → Socket.IO → Firebase Stack: Next.js 16, MongoDB, Socket.IO, Firebase ### PocketBridge — Phone to laptop over Wi-Fi. No cables, no cloud. URL: https://webdevang.com/work/pocketbridge · Live: https://github.com/devang99999/PocketBridge Platform: Web · Self-hosted · Category: Open source · Role: Solo · open source. A self-hosted web UI that writes straight to a folder on your machine. Open a URL on your phone and move files — up to 20 GB, streamed to disk, behind a PIN. Problem: Moving big files between phone and laptop shouldn’t need cables or a cloud upload. What was built: - Streaming uploads up to 20 GB written straight to disk - Progress bars and ETA - PIN protection for production - Browser streaming for large downloads Hard parts: - Huge files: Stream to disk instead of buffering in memory. Architecture: Next.js → TypeScript → Node streams → PM2 Stack: Next.js, TypeScript, Node streams, PM2 ### Peek — A fast, no-nonsense video player. URL: https://webdevang.com/work/peek · Live: https://github.com/devang99999/peek Platform: Android · Category: Open source · Role: Solo · built in a day. Flutter on top of libVLC, so it plays almost anything. Picture-in-picture, lock-screen controls, subtitles, audio tracks and resume — tuned for mid-range phones. Problem: Most Android players are bloated with ads; I wanted a fast one that plays everything. What was built: - libVLC playback through a vendored 16KB-page-safe plugin - Picture-in-picture and MediaSession lock-screen controls - SRT/VTT subtitles and audio-track switching - Gestures, resume and history Hard parts: - Android 15 16KB pages: Vendored and patched the VLC plugin for 16KB page-size devices. Architecture: Flutter → libVLC → Kotlin MediaSession service Stack: Flutter, libVLC, Kotlin, MediaSession ## AI lead follow-up & booking automation Every lead gets a reply in under a minute, gets followed up automatically, and gets booked onto your calendar — set up in 7 days. - Instant replies, 24/7: No more leads going cold overnight. Every enquiry from your website, WhatsApp, email or SMS gets a helpful reply in under a minute — in your tone, with your prices and your booking link. - Follow-up that never forgets: More of the leads you already pay for turn into bookings. If someone doesn’t book straight away, they get a short, friendly nudge on day 1, day 3 and day 7. It stops the moment they book or say no. - Booked and onboarded on autopilot: Fewer no-shows and no admin. Leads pick a time on your calendar. Confirmations, reminders, intake forms and welcome messages go out automatically. Pricing: setup from [$X], monthly from [$Y]. ### AI lead follow-up automation that replies in under a minute URL: https://webdevang.com/ai-lead-follow-up-automation Most small businesses don’t have a lead problem. They have a reply problem. The enquiries come in — then sit in an inbox until someone has a spare moment. This service makes sure every lead hears back in under a minute and keeps hearing from you until they book. #### Why slow replies cost you bookings People who enquire are usually asking two or three businesses at once. The first one to reply with a clear answer and an easy way to book tends to win. If your reply arrives the next morning, the customer has often already booked somewhere else. Then there are the leads who don’t book straight away. They meant to. They got busy. Without a follow-up, they quietly disappear — and with them, the money you spent on ads, your website and your reputation to get them to enquire in the first place. Doing this by hand is hard. You’re with clients all day. Evenings and weekends are when many people enquire. And remembering to follow up with dozens of people on day 3 and day 7 is nobody’s favourite job. #### How it works - Every channel, one place: Website forms, WhatsApp, email, SMS and Facebook or Instagram lead forms all feed into the same system, so nothing gets missed. - A helpful reply in seconds: The reply answers their actual question — prices, availability, what to expect — in your tone, and offers a link to book. It knows your services, policies and opening hours. - Polite follow-ups if they go quiet: If someone doesn’t book, they get a short, friendly nudge — usually on day 1, day 3 and day 7. Every follow-up stops the moment they book or reply. - You step in when it matters: Anything unusual — a complaint, a complex question, a big job — is handed straight to you with the full conversation, by email or WhatsApp. #### Example: a physio clinic on a Tuesday night - 9:14 pm: Sarah fills in the website form: “Lower back pain, do you take new patients this week?” - 9:14 pm: She gets a reply: yes, new patients are welcome, the first session is 45 minutes, here are three times this week and a link to book. - Wed 10:00 am: She hasn’t booked. A short message asks if any of those times work, or if she’d like a quick call first. - Wed 10:12 am: Sarah books Thursday 5:30 pm. The follow-ups stop and the clinic gets a notification. - Thu 9:00 am: A reminder with the address and what to bring goes out. Sarah turns up. ### FAQ **Will customers know it’s automated?** Replies are written in your voice and sound like a helpful receptionist. You can choose to sign them with your business name or a team member’s name, and anything tricky goes to a real person. **Which channels can it reply on?** Email, WhatsApp Business, SMS, website chat and forms, and Facebook or Instagram lead forms. **How many follow-ups will people get?** Usually three over a week, and you approve the wording. Follow-ups stop immediately when someone books, replies, or asks you to stop. ### Automated appointment booking that fills your calendar for you URL: https://webdevang.com/automated-appointment-booking The back-and-forth of “does Tuesday work? how about Thursday?” costs you time and costs you customers. Automated appointment booking lets every lead pick a time that suits them, straight onto your real calendar, with reminders that keep no-shows down. #### The hidden cost of manual booking Every booking you arrange by hand takes several messages. Each message is a chance for the customer to lose interest, get distracted or book with someone faster. Multiply that by every enquiry each week and it adds up to hours of admin and a steady leak of lost bookings. Then there are no-shows. A booking made a week ago is easy to forget. Without a reminder at the right time, people simply don’t turn up — and that slot is lost for good. Most businesses already have a calendar tool. The problem is that it isn’t connected to the moment someone enquires, so customers still wait for a human to send them the link. #### How it works - Your real availability: Bookings come straight from your Google Calendar, Outlook, Calendly or Cal.com, with your opening hours, buffers between appointments and staff rotas respected. - Booking offered at the right moment: The instant reply to every lead includes times that are actually free, or a one-tap booking link, so they can book while they’re still interested. - Confirmations and reminders: Customers get a confirmation straight away and reminders 24 hours and 2 hours before, by SMS, WhatsApp or email — with an easy way to reschedule instead of not showing up. - Deposits and rescheduling (optional): Take a deposit when they book, and let them move their appointment themselves within your rules. #### Example: a salon fills a cancellation - Mon 8:40 am: A client cancels her 2 pm colour appointment by replying to her reminder. - Mon 8:41 am: The slot opens on the calendar and goes to the top of the booking options. - Mon 9:05 am: A new enquiry asks about a cut and colour this week. The reply offers today at 2 pm. - Mon 9:07 am: She books it and pays a small deposit. Confirmation sent. - Mon 12:00 pm: A 2-hour reminder goes out. The chair is full instead of empty. ### FAQ **Do I need to change my calendar?** No. It works with Google Calendar, Outlook, Calendly and Cal.com. If you use a booking system built for your industry, we can usually connect to it. **Can it handle multiple staff?** Yes. Bookings can go to a specific person, the first available team member, or be split by service. **Does it reduce no-shows?** Timely reminders with an easy reschedule option are one of the most reliable ways to reduce no-shows, and deposits help even more for high-value appointments. ### Client onboarding automation so every client arrives ready URL: https://webdevang.com/client-onboarding-automation What happens after someone books says a lot about your business. Client onboarding automation sends the right welcome, forms and instructions at the right time — so clients feel looked after and you stop chasing paperwork. #### Where onboarding goes wrong A client books, and then… nothing until the day. They’re not sure where to park, what to bring or whether they need to fill anything in. Some arrive late. Some arrive without the information you need. A few cancel because they got cold feet. Meanwhile you’re sending the same welcome email, intake form and agreement by hand for every new client, and chasing the ones who forget to fill them in. A smooth start builds trust, gets you better information and makes clients far more likely to come back and refer friends. #### How it works - Welcome the moment they book: A warm welcome message goes out straight away with what happens next, who they’ll see and how to get in touch. - Forms and agreements, done before the day: Intake questionnaires, consent forms or contracts are sent automatically, with gentle reminders until they’re complete. You see the answers before the appointment. - Prep information at the right time: Directions, parking, what to bring, how to prepare — sent the day before, not buried in an email from last week. - After the first visit: A thank-you, a review request, and a nudge to rebook — so one booking turns into a relationship. #### Example: a business coach onboards a new client - Booking: A new client books a 90-minute strategy session. - +1 minute: Welcome email with what the session covers, plus a short questionnaire about their goals. - +1 day: Agreement and invoice sent for e-signature and payment. - -1 day: Reminder with the video-call link and two questions to think about. Questionnaire answers arrive in the coach’s inbox. - +1 day after: Thank-you, session notes link, a review request and an easy way to book the next session. ### FAQ **Can I use my existing forms?** Yes. Google Forms, Typeform, Jotform or the forms built into your booking or practice software all work. **Can it collect payments or signatures?** Yes — invoices, deposits and e-signatures can be part of onboarding, using tools like Stripe and your preferred e-signature service. **What about returning clients?** Returning clients can skip the forms they’ve already completed and get a shorter, friendlier flow. ### AI lead follow-up and booking for clinics URL: https://webdevang.com/for/clinics New patients enquire when they’re in pain or worried — often at night. The clinic that answers first, clearly and kindly, usually gets the booking. This sets that up for you. - Enquiries arrive after hours: Your front desk closes at 6, but people search for help at 10 pm. By morning they’ve booked elsewhere. - Reception is stretched: Your team is checking patients in, taking payments and answering the phone. Website enquiries wait. - No-shows and late cancellations: Empty appointments cost you directly, and they’re often down to a forgotten booking. - Paperwork on the day: Patients fill in forms in the waiting room, which delays appointments and frustrates everyone. - When New patient enquiry (form, WhatsApp, Google) → Instant reply with first-visit price, what to expect and the next three free times → Patients book while they’re still looking - When Patient books → Confirmation plus a medical history and consent form → Forms done before they arrive - When 24 hours and 2 hours before → Reminder with address, parking and an easy reschedule link → Fewer no-shows, more rescheduled slots - When After the first visit → Thank-you, exercise sheet or aftercare, and a prompt to book the follow-up → More patients complete their treatment plan ### FAQ **Does it work with my practice management software?** In most cases, yes — many clinic systems connect to calendars or have booking links we can use. We check this on the first call. **Will it give medical advice?** No. It answers practical questions — prices, availability, what to expect — and passes anything clinical to your team. **Is patient data kept private?** Data stays in your own systems. I sign a data-processing agreement on request. ### AI booking and follow-up automation for salons URL: https://webdevang.com/for/salons Your hands are busy with clients all day, but your phone keeps buzzing with “do you have anything Saturday?” This answers those messages instantly, books the appointment and keeps your chairs full. - DMs you can’t answer mid-appointment: Instagram and WhatsApp messages pile up while you’re working. By the time you reply, they’ve booked somewhere else. - Last-minute cancellations: A cancelled slot at short notice usually stays empty, even though someone would have taken it. - No-shows: Without a well-timed reminder, people forget — and you lose the slot and the money. - Clients who don’t rebook: A happy client means to come back in six weeks. Without a nudge, it turns into twelve. - When New DM, WhatsApp or website enquiry → Instant reply with prices, stylist availability and a booking link → Bookings made while you’re working - When Appointment booked → Confirmation, deposit request and patch-test info where needed → Committed clients, fewer surprises - When Cancellation → Slot offered to waitlist and new enquiries first → Cancellations refilled instead of lost - When 5–6 weeks after a visit → Friendly rebooking reminder with their usual stylist → Regulars come back on time ### FAQ **Can it reply to Instagram messages?** Yes — Instagram and Facebook messages can be connected through Meta’s official tools, alongside WhatsApp, SMS and your website. **Does it work with my salon software?** Most salon booking systems have booking links or calendar sync we can use. We confirm this before we start. **Can I still reply myself?** Of course. You can jump into any conversation, and the automation steps back. ### AI follow-up and discovery-call booking for coaches URL: https://webdevang.com/for/coaches You spend time and money building an audience. When someone finally raises their hand, they deserve a fast, personal reply and an easy way to talk to you. This makes sure they get one — every time. - Interested people go quiet: Someone downloads your guide or asks about pricing, then never hears back at the right moment. - Calendar ping-pong: Arranging discovery calls by email takes days and loses momentum. - Messy onboarding: Agreements, invoices and questionnaires go out by hand and get chased by hand. - You’re the whole team: Every hour spent on admin is an hour not spent coaching or creating. - When Enquiry, lead magnet download or DM → Personal-sounding reply that answers the question and offers a discovery call → More calls booked from the same audience - When No booking after 2 days → Short, helpful follow-up with a useful resource and the booking link → Warm leads stay warm - When Discovery call booked → Confirmation, a 3-question pre-call form and a reminder with the video link → Better-prepared calls - When Client signs up → Welcome pack, agreement, invoice and kickoff questionnaire → A professional start without the admin ### FAQ **Will it sound like me?** Yes. We write the messages together, using your words and your offers, and you approve them before anything goes live. **Does it work with Calendly or Cal.com?** Yes, and with Google Calendar or Outlook directly. **Can it handle group programs and launches?** Yes — different enquiries can follow different paths, such as a waitlist for a group program or a call for one-to-one coaching. ### AI lead reply and booking automation for home services URL: https://webdevang.com/for/home-services When someone needs a cleaner, plumber or pest controller, they contact a few businesses and go with whoever answers first. You’re on a job with your hands full. This answers for you and books the visit. - You’re on the tools all day: Calls go to voicemail and web enquiries wait until the evening. The job goes to whoever replied first. - Quotes that go nowhere: You send a quote and never hear back, because nobody followed up. - Site visits are hard to arrange: Finding a time that works means a string of texts back and forth. - Missing job details: You arrive without photos, access codes or the right parts. - When Quote request (form, SMS, Google, WhatsApp) → Instant reply asking for photos and a few details, plus times for a site visit → You win more of the jobs you’re asked about - When Missed call → Automatic text back: “Sorry I missed you — how can I help?” → Missed calls become conversations - When Quote sent, no reply in 3 days → Friendly follow-up answering common questions → More quotes accepted - When Job booked → Confirmation, access details request and an on-the-way message on the day → Smoother jobs and happier customers ### FAQ **Can it text back missed calls?** Yes. Missed calls can trigger an automatic SMS so the customer knows you’ll help, and the conversation continues from there. **Does it work with my job management software?** Many job management tools can connect. If yours can’t, bookings can go to your calendar and details to your email. **Can it give exact prices?** It can give your standard prices or ranges and ask for photos for anything that needs a proper quote. ### Automation FAQ **How long does setup take?** Seven days from our kickoff call. We map how you handle enquiries today, write your messages, connect your tools, test everything with you, then switch it on. **Which tools does it work with?** Gmail and Outlook, WhatsApp Business, SMS, website forms, Facebook and Instagram lead forms, Calendly, Cal.com, Google Calendar, and most CRMs (HubSpot, GoHighLevel, Zoho, Pipedrive and others). If you use something unusual, ask — most tools can be connected. **What happens to my customers’ data?** It stays in your own accounts — your inbox, your calendar, your CRM. I only use the access needed to send replies and book appointments, and I sign an NDA or data-processing agreement on request. **What if I want to cancel?** Cancel the monthly plan any time with 30 days’ notice. Everything I set up in your own accounts stays yours. **Do I need any technical skills?** No. You tell me how you like to talk to customers and when you’re available. I handle the setup, testing and monthly tuning. **Will the replies sound like a robot?** No. Messages are written in your tone, use your real prices and policies, and hand the conversation to you whenever a question needs a human. ## Services ### Custom CRM & SaaS development URL: https://webdevang.com/services/custom-crm-development I build CRMs and multi-tenant SaaS platforms end to end — data model, API, web app, mobile shell, billing and the servers underneath. The same playbook already runs a real-estate CRM handling 300K+ leads for 100+ firms, a studio CRM on both app stores, and an audit platform for an Australian accounting firm. ### When a custom CRM beats an off-the-shelf one Off-the-shelf CRMs are great until your process stops fitting their objects. Real-estate desks need units and channel partners, studios need multi-day shoots and crew, auditors need evidence and sign-off. Bending a generic CRM to that usually ends in spreadsheets on the side. A custom build makes sense when the workflow is your edge, when per-seat pricing is crushing margins, or when you need integrations (WhatsApp, portals, payments, voice) that generic tools only half-support. - Your pipeline has domain objects a generic CRM can’t model cleanly - You pay for 50+ seats of a tool your team works around - You need WhatsApp, voice, portal or payment flows wired into the record itself - You want to resell the system to your own customers (true SaaS) ### What I deliver Everything needed to run the product in production, not just a demo: | Layer | What you get | | --- | --- | | Data model | Tenant-isolated schema (MongoDB or Postgres with row-level security), audit trail, safe bulk operations | | Access | Owner / manager / staff roles, field-level permissions, OTP / Google / Apple sign-in, optional TOTP | | Product | Next.js web app that feels like an app — pipelines, calendars, invoices, reports, search | | Integrations | WhatsApp Business API, Meta lead ads, Google Sheets, webhooks, Razorpay / Stripe, email | | Mobile | Flutter shell for Play Store + App Store with push, in-app purchase and native sign-in | | Ops | CI/CD, monitoring, backups, hardening on GCP, AWS or Azure | ### How an engagement runs Week one is a working session on your real process and data — I map entities, roles and the reports leadership actually reads. From there I ship in weekly increments to a staging URL you can click, with the first usable slice (usually leads → follow-ups → bookings) live in three to four weeks. You own the code and infrastructure from day one. I document the data model and deployment so your team or another developer can take over without me. - Discovery + data model (week 1) - First usable slice on staging (weeks 2–4) - Integrations, billing, reports (weeks 4–8) - Mobile apps + store submission (as needed) - Handover docs, monitoring, support window ### FAQ **How much does a custom CRM cost?** It depends on roles, integrations and mobile needs. A focused CRM MVP is typically a matter of weeks, not months; I scope a fixed first milestone after a discovery call so you know the cost before committing. **Can you migrate our data from spreadsheets or another CRM?** Yes. I write import pipelines with duplicate detection and validation so leads, clients and history come across cleanly, and run a dry-run import before go-live. **Do I own the source code?** Yes — the repository, cloud accounts and data are yours from day one. **Can the CRM be resold to other businesses as SaaS?** Yes. I build multi-tenant from the start when that is the plan: tenant isolation, per-tenant roles, subscriptions and a super-admin panel. **Which stack do you use?** Usually Next.js, Node.js and MongoDB or PostgreSQL, with Flutter for mobile and GCP, AWS or Azure for hosting — chosen to fit your team and compliance needs. ### AI agents & automation URL: https://webdevang.com/services/ai-agent-development I build AI that sits inside your workflow instead of next to it: WhatsApp flows with an AI agent step, voice agents that call leads and update the CRM, MCP connectors so Claude can operate your data safely, and LLM pipelines for classification and extraction. ### Where AI agents pay off first The best first agent is boring: it answers the same questions, qualifies the same leads or moves the same records your team handles a hundred times a day. That is where response time and consistency improve immediately. - WhatsApp: instant replies, Day 0 / 2 / 7 nurture, hand-off to a human with full context - Voice: outbound qualification calls that log outcomes and update lead stages via tool calls - MCP: let Claude search, summarise and act on CRM data with scoped OAuth permissions - Pipelines: classify documents, tenders or tickets and route them automatically ### How I build agents that are safe to ship Agents fail in production when they can do too much or know too little. I design narrow tools with validated inputs, keep the model on retrieval from your real records, and log every action so a human can audit it. | Concern | How it’s handled | | --- | --- | | Hallucinated actions | Typed tool schemas, server-side validation, confirm steps for destructive actions | | Latency (voice) | Streaming STT/TTS, VAD tuning, compressed prompts | | Data access | Per-tenant scoping, OAuth for MCP, least-privilege API keys | | Cost | Model routing (Gemini / Claude / Groq) by task, caching, token budgets | | Observability | Every tool call logged against the record it touched | ### Typical engagement We pick one workflow, measure the baseline (response time, contact rate, hours spent), and ship a first agent in two to four weeks behind a feature flag. Then we widen scope based on what the logs show. ### FAQ **Which AI models do you use?** Claude, Gemini and Groq-hosted Llama, chosen per task for quality, latency and cost. The architecture keeps the model swappable. **Can the agent work in Hindi or Hinglish?** Yes. I have shipped a Hinglish voice sales agent using Indian-language speech models, and WhatsApp flows work in any language the model supports. **What is an MCP connector?** Model Context Protocol lets assistants like Claude call your system’s tools. I build OAuth-protected MCP servers so Claude can read and update your CRM with the same permissions as the signed-in user. **Do you need access to our WhatsApp Business account?** Yes, through Meta’s official WhatsApp Business Platform. I help with number setup, templates and approvals. ### Flutter app development URL: https://webdevang.com/services/flutter-app-development I ship Flutter apps for iOS and Android from one codebase — either fully native screens or a hardened wrapper around your existing web app — with the pieces reviewers check for: Sign in with Apple, in-app purchase, push, crash reporting and account deletion. ### Native app or web-app wrapper? If you already have a solid web app, a well-built Flutter wrapper gets you onto both stores in weeks — as long as it adds real native value. If the app is offline-heavy or media-heavy, native Flutter screens are the better call. | | Flutter wrapper | Native Flutter screens | | --- | --- | --- | | Time to store | Weeks | Months | | Reuses web app | Yes | Partly (API) | | Offline / media heavy | Limited | Yes | | Store review risk | Needs native features | Low | ### What’s included Every app ships with the boring parts that block launches: - Sign in with Apple + Google, OTP - In-app purchase with server-side receipt verification - FCM push + local notifications - Crashlytics + analytics - Account deletion flow and privacy labels - Store listing, screenshots and submission ### FAQ **Will Apple approve a WebView app?** Only if it offers app-like value beyond the website. I add native sign-in, IAP where required, push and offline-aware behaviour — that is how Client Mitra passed review. **How long does a Flutter app take?** A wrapper around an existing web app is usually a few weeks including store review; a native app depends on scope and is scoped per milestone. **Do you handle App Store and Play Store submission?** Yes — listings, screenshots, privacy forms, review replies and release management. ### Cloud & DevOps URL: https://webdevang.com/services/cloud-devops I set up and run production infrastructure for Node.js and Next.js products on GCP, AWS and Azure — CI/CD with GitHub Actions, PM2 and Nginx or containers, database hardening, backups and region choices that satisfy compliance (for example, Australian data residency). ### What I set up A production baseline you can hand to any engineer: - GitHub Actions pipelines (hosted or self-hosted runners) - PM2 + Nginx or Docker, zero-downtime reloads, SSL - MongoDB / PostgreSQL hardening: auth, network rules, indexes, backups - Object storage with signed URLs (S3, GCS, Azure Blob, Cloudinary) - Monitoring and alerts (Sentry, uptime, logs) - Region and residency choices for compliance ### Picking a cloud I use what fits the client rather than a favourite: | Cloud | Good fit when | | --- | --- | | GCP | Cost-efficient VMs in India / Asia, Playwright and scraping workloads | | AWS | Marketplace and enterprise buyers, SES email, EC2 + Elastic IP setups | | Azure | Microsoft-centric clients, Australian data residency (Australia East) | ### FAQ **Can you take over an existing server?** Yes. I start with an audit — access, open ports, database auth, backups, deploy process — and fix the risky items first. **Do you use Kubernetes?** Only when the scale needs it. Most products run more reliably and cheaply on well-managed VMs or a PaaS. **Can you host data in Australia or the UK?** Yes — region selection, storage and backups can all stay in-region. I have delivered an Australian-resident platform on Azure. ## Industries ### Real estate URL: https://webdevang.com/industries/real-estate Real estate runs on speed-to-lead. I engineer Antoc AI, a CRM used by 100+ real-estate firms, which pulls leads from Meta, Google Ads, portals and sheets into one pipeline and works them with WhatsApp flows and an AI calling agent. ### Problems I solve for real-estate teams Most desks lose deals between the ad click and the first call. The fixes are specific: - Leads scattered across portals, Meta forms and Excel → one de-duplicated pipeline - Slow first response → instant WhatsApp reply and AI qualification call - No visibility on site visits → field reporting, attendance and call logs - Inventory in PDFs → projects, buildings and units with shareable live links ### What I can build for you Either a custom system or integrations around your existing CRM: | Module | Notes | | --- | --- | | Lead capture | Meta lead ads, Google Ads, portals, webhooks, Sheets with dedupe + auto-assign | | WhatsApp automation | Flow builder, nurture drips, AI agent step, hand-off | | AI calling | Qualification calls that update lead stage and notes | | Inventory | Units, pricing, availability, public share links, brochures | | Reporting | Source ROI, stage momentum, team activity | ### FAQ **Can you integrate with property portals?** Yes — through portal webhooks, email parsing or exports, depending on what the portal offers, with duplicate detection across sources. **Do you build for developers as well as brokers?** Yes. Developers need project/unit inventory and channel-partner tracking; brokers need fast lead routing. The data model handles both. **Can you add AI calling to our existing CRM?** Usually yes, via its API: the voice agent places calls and writes outcomes back to the lead record. ### Photography & creative studios URL: https://webdevang.com/industries/photography-studios I built Client Mitra solo — a multi-tenant CRM for photography studios and creative businesses that tracks every enquiry to booking to payment, schedules crews across multi-day weddings, and ships as native apps on both stores. ### What studios actually need Generic CRMs don’t understand shoots, crews or advances. Studios need: - Enquiry → follow-up → booking pipeline that matches WhatsApp-first sales - Multi-day event calendar with crew assignment - Advance and balance tracking across UPI, cash and bank - Invoices and quotations with logo, GST and UPI QR - Staff who can see schedules without seeing money ### FAQ **Can I get a custom version of a studio CRM?** Yes — I can build a white-label or custom studio system with your packages, roles and branding. **Does it work offline?** The apps cache recent data so staff can check schedules with patchy signal; writes sync when back online. ### Accounting & compliance URL: https://webdevang.com/industries/accounting-compliance For an Australian accounting firm I built an audit platform end to end: agents upload documents, auditors review and raise queries, the system samples properties, reconciles trust accounts and produces the final report — all hosted in Australia. ### Capabilities Built around how auditors work, not around a generic document store: - Document workflows: uploaded → in review → verified / rejected / query raised - Random property sampling with saved selection runs - Bank vs ledger import and auto-matching (exact, strong, fuzzy) with variance tracking - Audit programme engine: sections, requirements, tests, evidence - Final report and audit pack export (PDF / Excel) - Two portals: client and auditor, with activity logs ### FAQ **Can the platform meet data residency rules?** Yes. Database, file storage, email and backups can all stay in the required region — the Australian build runs entirely in Azure Australia East. **Can you digitise our existing audit programmes?** Yes — I convert spreadsheet programmes into a data-driven engine so tests and evidence are tracked per engagement. ### Gaming cafes & retail POS URL: https://webdevang.com/industries/gaming-cafes HNEFA is a gaming-cafe POS and ERP I helped build with the Exlaso team: a live machine floor with timed sessions, billing for play time and snacks, prepaid wallets, inventory and a full GST-ready reports suite. ### Modules Everything a cafe or counter business runs on, in one dashboard: - Machine floor with start / pause / end sessions and bookings - Touch POS with sessions + products in one cart; cash, card, UPI - Cash drawer with denomination counting - Inventory batches, purchases, returns, stock alerts - Day summary, P&L, GST/HSN and cash reports - Roles: owner, admin, cashier ### FAQ **Can it run across multiple branches?** Yes — each location is a tenant with row-level security, with roll-up reporting for owners. **Does it print receipts?** Yes, thermal receipt printing is supported along with PDF and Excel exports. ## Hiring by market ### USA URL: https://webdevang.com/hire/full-stack-developer-usa I work with US founders and product teams as an embedded engineer: I own features end to end, ship daily to staging, and overlap with your morning standup. Same output as a senior hire, billed in USD, with no recruiting cycle. Working-hours overlap: | Your time | My time (IST) | Use it for | | --- | --- | --- | | 8:00–10:00 EST | 6:30–8:30 PM | Standup, reviews, pairing | | 6:00–8:00 AM PST | 6:30–8:30 PM | Async hand-off + live calls | | Overnight (US) | Daytime | Heads-down build — you wake up to progress | ### Why US teams hire me US buyers usually come to me for one of three reasons: - Ship an MVP or v2 fast with one accountable engineer - Add AI agents (voice, WhatsApp, MCP) to an existing product - Stabilise infra and deploys before a raise or enterprise deal ### Engagement models USD invoicing via Wise / Payoneer / wire. Contracts under your template or mine; IP assignment is standard. | Model | Best for | | --- | --- | | Fixed milestone | Defined MVP or feature | | Monthly retainer | Ongoing product work, 20–40 h/week | | Audit sprint | 1–2 week architecture / security review | ### FAQ **Can you sign NDAs and IP assignment agreements?** Yes — standard for every engagement. All code, accounts and IP belong to you. **How do you handle the time difference?** I keep a fixed 2-hour overlap with US mornings for calls and run the rest async with daily written updates and staging links. **Do you work through Upwork or directly?** Either. Direct contracts are simpler and cheaper for both sides. ### UK URL: https://webdevang.com/hire/full-stack-developer-uk UK time and India time overlap for most of your working day, which makes collaboration feel local. I build and run web apps, CRMs and AI integrations for UK businesses with GBP invoicing and GDPR-minded data handling. Working-hours overlap: | Your time (GMT/BST) | My time (IST) | Use it for | | --- | --- | --- | | 9:00 AM–1:00 PM | 1:30–5:30 PM (GMT) · 2:30–6:30 PM (BST) | Calls, reviews, live debugging | | Afternoon | Evening | Async build + end-of-day update | ### Data and compliance For UK clients I default to UK or EU regions (London on GCP/AWS, UK South on Azure), keep personal data minimal, and document processing for your DPA. - UK / EU hosting regions - Role-based access and audit logs - Data export and deletion flows ### Engagement models GBP invoices; fixed milestones or monthly retainers. I can work under your contract templates. ### FAQ **Can you host our data in the UK?** Yes — London or UK South regions for compute, database, storage and backups. **How much overlap do we get?** Typically four to five hours of your morning and early afternoon, every weekday. **Do you invoice in GBP?** Yes, via bank transfer or Wise. ### Australia URL: https://webdevang.com/hire/full-stack-developer-australia I built and delivered an audit and compliance platform for an Australian accounting firm — hosted entirely in Australia on Azure, with MFA, document workflows and trust-account reconciliation. Australian mornings overlap with my working day, so collaboration is easy. Working-hours overlap: | Your time (AEST/AEDT) | My time (IST) | Use it for | | --- | --- | --- | | 1:00–6:00 PM AEST | 8:30 AM–1:30 PM | Calls, reviews, pairing | | Evening | Afternoon | Async build + daily update | ### Australian data residency, done properly Compliance-sensitive Australian projects need more than a region dropdown. On the audit platform, database, blob storage, email and backups all stay in Azure Australia East, with signed time-limited file links and MFA on every account. - Azure Australia East / AWS Sydney / GCP Sydney - MFA (OTP + TOTP), short-lived tokens - Audit logs suitable for regulated work ### Engagement models AUD invoicing; fixed scope with a written change-request process, or monthly retainer. ### FAQ **Have you worked with Australian clients before?** Yes — I delivered a compliance audit platform for an Australian accounting firm, hosted in Australia. **Can all our data stay in Australia?** Yes: compute, database, storage, email and backups can all be pinned to Australian regions. **What hours do you overlap with?** Roughly 1–6 PM AEST every weekday, which covers most meetings. ### Dubai / UAE URL: https://webdevang.com/hire/full-stack-developer-dubai Gulf Standard Time is just 90 minutes behind India, so your whole working day overlaps with mine. Real-estate and service businesses in the UAE run on WhatsApp — exactly the automation and CRM work I ship every week. Working-hours overlap: | Your time (GST) | My time (IST) | Use it for | | --- | --- | --- | | 9:00 AM–6:00 PM | 10:30 AM–7:30 PM | Full working-day overlap | ### What UAE businesses hire me for The most common projects: - Real-estate CRMs with portal + Meta lead capture - WhatsApp Business API automation with AI replies - Booking and service management SaaS - Arabic/English-ready interfaces ### Engagement models USD or AED invoicing; fixed milestones or retainers; on-site visits for kickoff can be arranged. ### FAQ **Do you build real-estate CRMs for the UAE market?** Yes — I engineer a real-estate CRM used by 100+ firms, and the same lead capture, WhatsApp and inventory modules apply to UAE brokers and developers. **Can interfaces support Arabic?** Yes, with right-to-left layouts and bilingual content. **How much overlap is there?** Your full working day — GST is 1.5 hours behind IST. ### India URL: https://webdevang.com/hire/full-stack-developer-india Based in Ahmedabad (IST (UTC+5:30)), I build products for Indian businesses with the local pieces built in: Razorpay and UPI, GST invoices, WhatsApp-first sales, OTP via Indian SMS gateways, and Hinglish voice AI. Working-hours overlap: | Your time | My time | Notes | | --- | --- | --- | | Same time zone | IST (UTC+5:30) | In-person meetings in Ahmedabad / Gujarat possible | ### Built-in Indian stack Things I’ve already shipped in production for Indian users: - Razorpay subscriptions + UPI QR on invoices - GST invoices and quotations - WhatsApp OTP and DLT-compliant SMS OTP - Hinglish AI voice agents - Apps on Play Store and App Store ### Engagement models INR invoicing with GST; fixed milestones or monthly retainers. ### FAQ **Are you available for in-person meetings?** Yes, in Ahmedabad and across Gujarat; elsewhere in India by arrangement. **Do you handle Razorpay and GST setup?** Yes — subscriptions, webhooks, GST invoices and UPI QR are part of my standard builds. **Can you build in Hindi or Gujarati?** Yes — interfaces and AI agents can be localised, including Hinglish voice. ## General FAQ **What kind of projects do you take on?** Custom CRMs and multi-tenant SaaS, AI agents (WhatsApp, voice, MCP), Flutter apps for iOS and Android, and the cloud infrastructure underneath — usually end to end, sometimes one hard piece of an existing product. **Do you work with clients outside India?** Yes. I work with teams in the US, UK, Australia and the UAE, with a fixed daily overlap for calls and billing in USD, GBP, AUD or AED. **How do engagements usually start?** A short call about your goals and constraints, then a written scope with a fixed first milestone. You get a staging link within the first couple of weeks and weekly releases after that. **Who owns the code?** You do. Repositories, cloud accounts and data belong to you from day one, and I document everything so another developer can take over. **Are you available full-time?** I work full-time at Passdn Technologies and take a small number of freelance builds alongside. I am also open to full-time roles that are a strong fit. ## Articles --- # How Much Does Custom CRM Development Cost in 2026? URL: https://webdevang.com/blog/custom-crm-development-cost · Category: CRM & SaaS development · Updated: 2026-11-03 The question I get most from founders is some version of "what will this cost?" The honest answer is that custom crm development cost depends on a handful of specific decisions, and once you know what they are, you can predict your budget far better than any generic price list. I have worked on CRMs at very different scales: a real-estate CRM used by 100+ firms managing around 300K leads, and a solo-built multi-tenant CRM for photography studios with native iOS and Android apps. This post breaks down what actually moves the number, using those builds as reference points. ## TL;DR A focused CRM MVP for one team typically lands in the low five figures USD. A multi-tenant CRM product with integrations, automation and mobile apps is a phased investment that can run well into six figures over its life. The biggest cost drivers are integrations, automation logic, permission models and data volume, not the number of pages. Scope one workflow end to end first and the budget stays predictable. ## Key takeaways - Custom CRM development cost is driven far more by integrations, automation and permissions than by the number of screens. - A focused CRM MVP for one team and one lead source is a very different budget from a multi-tenant product sold to hundreds of businesses. - Hosting is usually cheap; ongoing maintenance, integration upkeep and data growth are the recurring costs that matter. - Scoping the first release around one workflow end to end is the most reliable way to keep the budget predictable. ## Realistic cost tiers in 2026 These are ranges from my experience as an independent developer working with clients in the US, UK, Australia, UAE and India. Agency pricing is often higher; offshore body-shop pricing can be lower but usually needs more management on your side. | Tier | Typical scope | Rough timeline | Indicative budget (USD) | |---|---|---|---| | Internal MVP | One team, 1–2 lead sources, pipeline, tasks, basic reports | 6–10 weeks | Low five figures | | Growth CRM | Multiple lead sources, dedupe, auto-assignment, WhatsApp or email automation, roles | 3–5 months | Mid five figures | | SaaS CRM product | Multi-tenant, billing, plan-based feature locks, admin panel, mobile apps | 6+ months, phased | High five to six figures | | AI-enabled CRM | Above plus AI agents, voice calling, MCP or LLM integrations | Ongoing | Depends heavily on usage and scope | Treat these as planning ranges, not quotes. The point of the table is the shape: each tier roughly doubles the complexity of the one before it. ## What actually drives the price ### Integrations Every lead source is its own small project. Meta lead ads, Google Ads, property portals, Google Sheets, generic webhooks and public forms each have their own authentication, payload format and failure modes. On Antoc, lead capture from all of those sources sits behind duplicate detection and auto-assignment rules, and that pipeline is a meaningful share of the engineering effort. When you count features, count integrations separately. Five integrations is not "one feature." ### Automation and messaging A WhatsApp nurture sequence sounds simple: send a message on Day 0, Day 2 and Day 7. In practice you need templates approved under the [WhatsApp Business Platform rules](https://developers.facebook.com/docs/whatsapp), trigger types (incoming message, new lead, reminder, pipeline stage), opt-out handling and a way for non-technical users to edit flows. A visual flow builder is one of the more expensive single features you can request, and also one of the most valuable. ### Permissions and multi-tenancy A CRM for your own team needs a couple of roles. A CRM you sell to other businesses needs tenant isolation, per-tenant roles and often plan-based feature locking. That affects every query and every API route, so it is a cross-cutting cost rather than a line item. ### Data volume At a few thousand records, almost any schema works. Past a few hundred thousand, you need deliberate indexes, safe bulk operations and access hardening. Budget for a performance pass once real usage arrives. ### Mobile apps If your team works in the field, you will want mobile. A Flutter wrapper around a well-built web app is far cheaper than two native apps, but App Store review still requires native sign-in options, in-app purchase for subscriptions and server-side receipt checks. ## Costs founders forget to budget 1. **Data migration** from spreadsheets or an old CRM, including cleanup and deduplication. 2. **Third-party usage fees** for WhatsApp conversations, SMS OTPs, voice minutes and LLM tokens. 3. **Error monitoring and logging**, such as Sentry, from day one. 4. **App Store and Play Store** accounts, review cycles and compliance changes. 5. **Maintenance retainer** for API changes, browser updates and small requests after launch. 6. **Onboarding and training** time for your team, which often decides whether the CRM gets used at all. ## How I built this in practice On [the Antoc case study](/work/antoc), I work as a core engineer on a real-estate CRM built by Passdn Technologies and used by 100+ firms in India. The cost centers there match the list above almost exactly. Lead capture from Meta, Google Ads, portals, Sheets and webhooks needed dedupe and assignment rules. The WhatsApp flow builder with an AI agent node, the Hinglish AI voice calling agent and a remote MCP server with OAuth were each substantial projects on their own. The less glamorous work mattered too. As leads grew past 300K, we added indexes, made bulk operations validate their filters before running, and tightened auth and network restrictions on the database. None of that shows up in a feature list, but it is real engineering time. Client Mitra, which I built solo, is the opposite end: one developer, a clear niche, about 30 app pages and 15 data models. Using one Flutter wrapper for both mobile platforms instead of two native apps kept the budget sane. ## Common mistakes - Comparing quotes that assume completely different scopes. - Asking for "AI features" without defining a single concrete job for the AI to do. - Building every integration before the first one is proven to bring in leads. - Skipping a data migration estimate and discovering the old data is messy in week ten. - Treating launch as the end of the budget instead of the start of maintenance. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Antoc real-estate CRM case study](/work/antoc) - [Hire a full stack developer for US teams](/hire/full-stack-developer-usa) - [Build vs buy CRM: when custom software pays off](/blog/build-vs-buy-crm) - [Multi-tenant SaaS architecture guide](/blog/multi-tenant-saas-architecture) - [Real estate CRM development features](/blog/real-estate-crm-development) - [Building a CRM for photography studios](/blog/crm-for-photography-studios) ## FAQ ### How much does a basic custom CRM cost to build? A focused CRM for a single team, with lead capture, a pipeline, tasks and basic reports, typically sits in the low five figures USD when built by an experienced freelancer or small team. Prices climb quickly once you add multiple integrations, automation and mobile apps. ### Why do CRM quotes vary so much between vendors? Vendors are often quoting different scopes without saying so. One quote may assume a single lead source and no automation, while another includes WhatsApp flows, role permissions and data migration. Ask every vendor for a line-item scope so you can compare like for like. ### Is it cheaper to customize Salesforce or HubSpot instead? For standard sales workflows, usually yes in the first year. Custom builds start to win when per-seat licensing grows large, your workflow is unusual, or you want to sell the CRM itself as a product. ### What are the ongoing costs after launch? Expect hosting, error monitoring, third-party API fees such as WhatsApp or SMS, and a maintenance retainer for fixes and small features. In my experience the retainer is the largest recurring line, not the servers. ### How long does it take to build a custom CRM? A tightly scoped MVP can ship in roughly 8 to 12 weeks. A multi-tenant CRM with automation, voice or AI features and mobile apps is an ongoing product, built in phases over many months. ## Next step If you want a line-item estimate for your CRM instead of a guess, [get in touch](/#contact) with your current workflow and lead sources. You can also see how I approach scoping on my [custom CRM development](/services/custom-crm-development) page. --- # Build vs Buy CRM: When Custom Software Pays Off URL: https://webdevang.com/blog/build-vs-buy-crm · Category: CRM & SaaS development · Updated: 2026-11-03 Most build vs buy CRM debates I see are framed wrong. People compare feature lists, when the real question is how well a tool fits the way your team actually works every day, and what it costs you when it does not. I have built CRMs from scratch, including Client Mitra for photography studios, and I have also told prospective clients to just buy HubSpot. This post is the framework I use to decide which advice to give. ## TL;DR Buy when your process is a standard sales pipeline, your team is small and you do not need unusual integrations. Build when your workflow is industry-specific, generic tools force workarounds, per-seat costs add up, or you want to own the product and its data. If you are unsure, buy first, learn what your team really uses, then build around that. ## Key takeaways - Buy a CRM when your workflow looks like a standard sales pipeline and your team is small enough that per-seat pricing stays reasonable. - Build when the workflow is specific to your industry, such as bookings, crew scheduling or local invoicing, and generic tools force constant workarounds. - Integration needs and data ownership are often the real deciding factor, not feature checklists. - A hybrid path, buying first and building once the workflow is proven, is often the lowest-risk option. ## The real cost of buying Off-the-shelf CRMs look cheap on the pricing page. The costs show up later, in three places. **Seat creep.** Per-user pricing is fine for five salespeople. It hurts when you want field staff, crew members or part-time assistants to log in, because each of them becomes a paid seat. **Workaround tax.** When the tool does not model your business, people work around it. Bookings live in a spreadsheet, invoices in a separate app, crew schedules in WhatsApp groups. The CRM becomes one of five places where truth lives. **Add-on pricing.** Automation, advanced permissions, custom objects and API access are often gated behind higher tiers. You end up paying enterprise prices for one feature. The [Salesforce pricing page](https://www.salesforce.com/pricing/) is a useful benchmark for how tiers and per-seat costs stack up as a team grows. ## The real cost of building Building is not free either, and I would be doing you a disservice to pretend it is. - You pay upfront for design and engineering before anyone uses it. - You own maintenance: dependency updates, API changes, app store policy changes. - You need someone who understands the domain well enough to model it correctly the first time. The question is not "which is cheaper" but "which costs less over the period you care about, including the hidden costs." ## A decision checklist Score each statement as true or false for your business. The more "true" answers, the stronger the case for building. 1. Our core workflow is not a sales pipeline (for example, enquiry to booking to delivery to payment). 2. We need to give logins to many non-sales users, such as crew, field agents or staff. 3. We rely on local integrations that global CRMs handle poorly, like WhatsApp OTP login, UPI payments or GST invoices. 4. We already pay for three or more tools that a single system could replace. 5. We want to sell the CRM to other businesses in our industry. 6. Our data is sensitive enough that we want control over where it is hosted. 7. We have tried at least one off-the-shelf CRM and abandoned it because of fit. | Score | Recommendation | |---|---| | 0–2 true | Buy. Configure a mainstream CRM well. | | 3–4 true | Hybrid. Buy now, document gaps, plan a build. | | 5–7 true | Build. A focused custom CRM will likely pay off. | ## Where industry-specific CRMs win Generic CRMs are built around a deal moving through stages. Plenty of businesses do not work that way. A real-estate firm needs inventory (projects, buildings, units) tied to leads, site-visit tracking and portal lead capture. You can see how that plays out on my [real estate industry page](/industries/real-estate). A photography studio needs multi-day event scheduling, crew assignment and invoices with a UPI QR code. An accounting firm needs document review and evidence trails. When the "deal" is actually a wedding with five shoot days, three crew members and a payment schedule, forcing it into a sales pipeline costs more than building the right model. ## How I built this in practice [Client Mitra](/work/clientmitra) is a good example of a case where building was clearly right. Indian photography studios were juggling enquiries in WhatsApp, bookings in notebooks and invoices in separate tools. No mainstream CRM handled the full flow: enquiry to booking to payment, crew calendars for multi-day weddings, GST invoices and quotations with the studio's logo and UPI QR, expenses and a profit view. I built it solo as a multi-tenant product. Owners, managers and staff have different permissions, so staff can do their jobs without seeing money. Login works by WhatsApp OTP or Google, plus Sign in with Apple on iOS, because that is how this audience actually signs in. Subscriptions run through Razorpay on the web and Apple in-app purchase on iOS with server-side receipt verification. One Flutter wrapper ships the web app as native Android and iOS apps with push notifications. None of those requirements are exotic, but together they describe a product no global CRM would build for a niche market. That gap is exactly where a custom build pays off. For the opposite case, I have advised small B2B teams with a single sales motion to stay on a mainstream CRM. Their workflow fit the tool, and building would have been an expensive hobby. ## Common mistakes - Deciding based on a feature checklist instead of a walkthrough of a real day's work. - Building a custom CRM that copies Salesforce instead of modeling your actual business. - Ignoring maintenance when comparing the cost of building against a subscription. - Buying an enterprise tier for a single feature that a small integration could provide. - Migrating to a custom build without cleaning and deduplicating existing data first. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Client Mitra photography CRM case study](/work/clientmitra) - [CRM and software for real estate firms](/industries/real-estate) - [Multi-tenant SaaS architecture guide](/blog/multi-tenant-saas-architecture) - [Real estate CRM development features](/blog/real-estate-crm-development) - [Building a CRM for photography studios](/blog/crm-for-photography-studios) - [MongoDB vs PostgreSQL for SaaS](/blog/mongodb-vs-postgresql-for-saas) ## FAQ ### When should a small business build its own CRM? Build when your core workflow does not fit a generic pipeline, when you are paying for many seats you barely use, or when you need deep local integrations like WhatsApp, UPI or GST invoicing. If a standard tool covers 90% of your needs, buy it. ### Is a custom CRM more expensive than Salesforce or HubSpot? Upfront, yes. Over three to five years it can be cheaper for larger teams because you avoid per-seat licensing and paid add-ons. The break-even point depends on seat count and how much customization you would otherwise pay for. ### Can I start with an off-the-shelf CRM and switch later? Yes, and it is often the smartest route. Use the bought tool to learn which fields and stages your team actually uses, then build a custom CRM around that proven workflow and migrate the data. ### What are the risks of building a custom CRM? The main risks are unclear scope, no plan for maintenance, and building features nobody uses. A narrow first release and a developer who has shipped CRMs before reduce all three. ## Next step If you are stuck on the build vs buy decision, [get in touch](/#contact) and walk me through how your team works today. I will tell you honestly whether to buy or build, and you can read more about my approach on the [custom CRM development](/services/custom-crm-development) page. --- # Multi-Tenant SaaS Architecture: A Practical Guide URL: https://webdevang.com/blog/multi-tenant-saas-architecture · Category: CRM & SaaS development · Updated: 2026-11-03 Getting multi-tenant SaaS architecture right early saves you from the worst kind of bug: one customer seeing another customer's data. It also decides how easily you can add billing plans, roles and per-tenant features later. I have built and worked on multi-tenant systems on both MongoDB and Postgres: Client Mitra for photography studios, the Antoc real-estate CRM, and the HNEFA gaming cafe POS. Here is the practical playbook I follow, without the theory-heavy diagrams. ## TL;DR Start with a shared database and a tenant ID on every tenant-owned record. Enforce tenant scope in one central layer (middleware in a Node/MongoDB stack, row-level security in Postgres), never by remembering to add a filter. Attach roles, plans and feature flags to the tenant. Then audit the places isolation usually leaks: background jobs, file storage, caches and admin tools. ## Key takeaways - For most early-stage SaaS products, a shared database with a tenant ID on every row is the right default. - Tenant scoping must be enforced in one central place, such as middleware or database policies, never remembered per query. - Roles, billing plans and feature flags all hang off the tenant, so model the tenant entity carefully from day one. - Background jobs, file storage and caches are where tenant isolation most often leaks. ## Choosing an isolation model There are three common models. The right one depends on your customers, not on what sounds most secure. | Model | How it works | Best for | Main cost | |---|---|---|---| | Shared database, shared schema | Every row carries a `tenantId` | Most SMB SaaS, early stage | Discipline in enforcing scope | | Schema per tenant | Each tenant gets its own schema in one database | Moderate tenant counts with custom fields | Migrations multiply per tenant | | Database per tenant | Separate database per customer | Regulated or very large enterprise tenants | Operational overhead, connection limits | For Client Mitra, Antoc and HNEFA, the shared model was the right call. Hundreds of small businesses with similar data shapes fit it perfectly, and one migration updates everyone. If you later land an enterprise customer who needs dedicated infrastructure, you can carve them out. Starting with database-per-tenant "just in case" mostly buys you pain. ## Enforcing tenant scope centrally The rule I follow: no developer should ever have to remember to add `tenantId` to a query. If they have to remember, someone eventually forgets. ### In a Node and MongoDB stack The request flow looks like this: 1. Auth middleware verifies the JWT and loads the user. 2. Tenant middleware resolves the active tenant from the token or an organization header and verifies the user's membership. 3. The tenant ID is attached to the request context. 4. Data access goes through helpers or Mongoose plugins that inject `{ tenantId }` into every find, update and delete, and stamp it on every insert. 5. Role checks run after tenant resolution, so permissions are always evaluated within a tenant. Add a compound index that starts with `tenantId` on every hot collection. It keeps queries fast and makes the access pattern explicit. The [MongoDB indexing docs](https://www.mongodb.com/docs/manual/indexes/) cover compound index ordering well. ### In Postgres Postgres gives you a stronger option: row-level security. Policies attached to each table filter rows by the current tenant, so even a buggy query cannot cross tenants. I cover this in detail in [row-level security for multi-tenant apps](/blog/row-level-security-multi-tenant). ## Modeling tenants, users and memberships The most common modeling mistake is putting `tenantId` and `role` directly on the user. It works until someone needs access to two organizations. A cleaner model: - **Tenant**: name, plan, subscription status, settings, branding (logo, invoice details). - **User**: identity only, such as email, phone, auth providers. - **Membership**: `userId`, `tenantId`, `role`, `permissions`, `status`. Antoc supports multi-business organization switching for exactly this reason. Owners who run more than one business switch context without logging out, and every request carries the active tenant. ## Plans, billing and feature locks Once tenants exist, billing attaches to them. A plan defines limits (seats, records, messages) and which features are unlocked. Every gated feature should check the plan on the server, not just hide a button in the UI. Antoc uses plan-based feature locking so higher tiers expose more modules. Client Mitra ties subscriptions to the tenant whether they come from Razorpay on the web or Apple in-app purchase on iOS, with server-side receipt verification deciding the tenant's status. ## Where isolation leaks - **Cron jobs and queues.** A reminder job that loads "all pending tasks" must still process them per tenant and never mix recipients. - **File storage.** Prefix object keys by tenant and use time-limited signed URLs rather than public links. - **Caches.** Include the tenant ID in every cache key, including client-side query caches. - **Search and exports.** CSV exports and reports are frequent offenders because they are written as one-off queries. - **Admin panels.** Super-admin tools bypass tenant scope by design, so give them separate auth and logging. ## How I built this in practice [Client Mitra](/work/clientmitra) is a multi-tenant CRM I built solo for photography studios. Tenant isolation lives in Express middleware: after JWT verification, the tenant is resolved and every data access across the 15 Mongoose models is scoped to it. Roles (owner, manager, staff) are evaluated inside the tenant, which is how staff can manage bookings without seeing financials. Cron reminders via node-cron iterate per tenant. Invoices generated with PDFKit pull the tenant's logo and UPI details, so branding never crosses accounts. On the frontend, TanStack Query's persisted cache is keyed per tenant and cleared on logout or organization switch. On HNEFA, built with the Exlaso team, the same goals are met differently: Supabase Postgres with row-level security per tenant, so isolation is enforced by the database itself. ## Common mistakes - Storing role and tenant on the user record instead of a membership. - Filtering by tenant in the UI layer and trusting the client. - Forgetting tenant scope in cron jobs, exports and webhooks. - Choosing database-per-tenant before there is a customer who needs it. - Not writing tests that try to read another tenant's data on purpose. ## Internal links - [Custom CRM and SaaS development services](/services/custom-crm-development) - [Client Mitra multi-tenant CRM case study](/work/clientmitra) - [Hire a full stack developer for UK teams](/hire/full-stack-developer-uk) - [Real estate CRM development features](/blog/real-estate-crm-development) - [Building a CRM for photography studios](/blog/crm-for-photography-studios) - [MongoDB vs PostgreSQL for SaaS](/blog/mongodb-vs-postgresql-for-saas) - [Row-level security for multi-tenant apps](/blog/row-level-security-multi-tenant) ## FAQ ### What is multi-tenant SaaS architecture? It is a design where one running application and usually one database serve many customer organizations, called tenants. Each tenant sees only its own data, users and settings, even though the infrastructure is shared. ### Should each tenant get its own database? Usually not at the start. Database-per-tenant adds operational overhead for migrations, backups and connections. It makes sense for regulated enterprise customers or when a single tenant is very large. ### How do you prevent one tenant from seeing another tenant's data? Enforce scoping centrally. In MongoDB I use middleware that injects the tenant ID into every query; in Postgres, row-level security policies do this at the database level. Then test it with automated cross-tenant access checks. ### How do you handle users who belong to multiple organizations? Separate the user from the membership. A user can have memberships in several tenants, each with its own role, and the active tenant is chosen at login or via an organization switcher. ### Does multi-tenancy affect billing? Yes. Subscriptions, plan limits and feature locks attach to the tenant, not the individual user. Every gated feature should check the tenant's current plan on the server. ## Next step If you are planning a SaaS product and want the tenant model right from the first commit, [get in touch](/#contact). My [custom CRM development](/services/custom-crm-development) page explains how I scope and build multi-tenant products. --- # Real Estate CRM Development: Features That Matter URL: https://webdevang.com/blog/real-estate-crm-development · Category: CRM & SaaS development · Updated: 2026-11-03 Real estate crm development is a different job from building a generic sales CRM. Leads arrive from a dozen sources at once, buyers expect replies on WhatsApp within minutes, and every lead is tied to physical inventory: a specific project, tower and unit. I am a core engineer on Antoc, a real-estate CRM used by 100+ firms in India with roughly 300K leads under management. These are the features that turned out to matter, and the ones that sound good but can wait. ## TL;DR Build the lead engine first: capture from Meta, Google Ads, portals, Sheets and forms, then dedupe and auto-assign. Add WhatsApp automation next, because that is where buyers respond. Then model inventory and site visits so agents can tie leads to units. AI calling and AI chat are powerful additions once that foundation is solid. ## Key takeaways - In real estate, speed to lead decides deals, so multi-source lead capture with dedupe and auto-assignment is the foundation. - WhatsApp automation matters more than email for real estate buyers in markets like India and the UAE. - Inventory, site visits and field team tracking are what separate a real estate CRM from a generic sales CRM. - AI voice agents and AI chat nodes are useful once the lead and inventory data underneath them is clean. ## The feature priority list Not every feature deserves to be in version one. Here is how I would sequence a real estate CRM build. | Priority | Feature | Why it matters | |---|---|---| | 1 | Multi-source lead capture | Ads and portals are where leads come from | | 1 | Duplicate detection | The same buyer enquires on three portals | | 1 | Auto-assignment rules | Unassigned leads go cold within hours | | 2 | WhatsApp templates and drips | Buyers answer WhatsApp, not email | | 2 | Pipeline and reminders | Follow-ups are where most deals are won | | 2 | Inventory (projects, buildings, units) | Agents need to pitch real availability | | 3 | Site-visit and call reporting | Managers need activity visibility | | 3 | Attendance and field team tools | Sales teams work on site, not at desks | | 4 | AI voice calling and AI chat | Scales first-touch qualification | ## Lead capture, dedupe and assignment A typical developer or brokerage runs Meta lead ads, Google Ads, listings on 99acres or OLX-style portals, a website form, and maybe a Google Sheet a partner fills in. Each source needs its own connector. - **Meta lead ads**: subscribe to the leadgen webhook and fetch lead details via the Graph API. - **Google Ads**: lead form extensions deliver to a webhook URL. - **Portals**: depending on the portal, webhooks, email parsing or scheduled pulls. - **Sheets and forms**: polling or Apps Script pushes, plus a public form endpoint with spam protection. Then comes dedupe. Normalize phone numbers to E.164, match on phone and email, and decide whether a duplicate updates the existing lead or creates a fresh enquiry on it. Assignment rules (round robin, by project, by source, by agent availability) run immediately after. ## WhatsApp automation For Indian real estate buyers, WhatsApp is the primary channel. A good CRM lets a sales manager build flows without a developer. Antoc's visual flow builder supports triggers like incoming message, new lead, reminder and pipeline stage change, with nurture drips at Day 0, Day 2 and Day 7. Everything runs on the official [WhatsApp Business Platform](https://developers.facebook.com/docs/whatsapp), using approved templates for outbound messages outside the 24-hour window. Unofficial tools are cheaper until the number gets banned. The flow builder also includes an AI agent node, which can answer common questions about a project and hand off to a human when the buyer is ready. ## Inventory and site visits This is where generic CRMs fall short. Real estate inventory is hierarchical: projects contain buildings, buildings contain units, and each unit has a status, price and configuration. Agents need to link a lead to the units they are interested in. Antoc includes public share links for inventory, so an agent can send a buyer a live availability page instead of a stale PDF. Site visits are logged against leads and projects, and managers get site-visit and call reports per agent. Attendance and field team tools cover the fact that real estate sales happens on location. ## AI voice calling The most technically demanding feature I have worked on here is an AI voice calling agent. It is a Hinglish sales agent built with Sarvam for speech-to-text and text-to-speech and Gemini for reasoning, running through a voice platform. After the call, it updates the lead through tool calls: interest level, budget, preferred callback time. The hard part is latency. Natural conversation breaks down if replies lag, so a lot of the work went into voice activity detection tuning and prompt compression to shave response time. ## How I built this in practice On [the Antoc case study](/work/antoc) you can see the full scope. I am the top committer on the web client, built on Next.js and React, with a Node and Express backend, MongoDB through Mongoose, and Socket.IO for realtime updates. Other pieces include a remote MCP server with OAuth so Claude can act on a business's CRM data, plan-based feature locking, and multi-business organization switching for groups that run several firms. Scale shaped the engineering. As leads grew past 300K, we added targeted indexes, required filter validation before bulk updates or deletes could run, and tightened database auth and network restrictions. Errors are tracked in Sentry, and the app runs on GCP VMs in asia-south1 with PM2 and Nginx. ## Common mistakes - Treating all lead sources as one integration and underestimating the work. - Skipping phone normalization, which quietly breaks dedupe. - Using unofficial WhatsApp bulk senders and losing the business number. - Modeling inventory as a free-text field on the lead. - Adding AI features before agents trust the underlying lead data. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Antoc real-estate CRM case study](/work/antoc) - [Software for real estate firms](/industries/real-estate) - [Building a CRM for photography studios](/blog/crm-for-photography-studios) - [MongoDB vs PostgreSQL for SaaS](/blog/mongodb-vs-postgresql-for-saas) - [Row-level security for multi-tenant apps](/blog/row-level-security-multi-tenant) - [How to build a lead management system that scales](/blog/lead-management-system-development) ## FAQ ### What features should a real estate CRM have? At minimum: lead capture from ads and property portals, duplicate detection, auto-assignment, a pipeline, follow-up reminders, WhatsApp messaging, inventory linked to leads and site-visit tracking. Reporting on calls and visits per agent comes next. ### How do real estate CRMs capture leads from property portals? Through a mix of official integrations, webhooks, email parsing and scheduled imports, depending on what each portal supports. Every source then flows into the same pipeline with dedupe and assignment rules. ### Is WhatsApp automation allowed for real estate marketing? Yes, through the official WhatsApp Business Platform with approved message templates and user opt-in. Unofficial bulk tools risk number bans, so I only build on the official API. ### Can AI really make sales calls for real estate? AI voice agents can handle first-touch qualification calls, confirm interest and budget, and update the lead record. They work best as a filter before a human agent, and latency tuning is critical for natural conversation. ## Next step If you run a real estate business and your leads are scattered across portals, ads and spreadsheets, [get in touch](/#contact). My [custom CRM development](/services/custom-crm-development) page covers how I build CRMs like this end to end. --- # Building a CRM for Photography Studios URL: https://webdevang.com/blog/crm-for-photography-studios · Category: CRM & SaaS development · Updated: 2026-11-03 Most studio owners I spoke to before building a crm for photography studios had the same setup: enquiries in WhatsApp, bookings in a diary, crew schedules in a group chat, invoices in a separate app and money tracked in a spreadsheet. Nothing talked to anything else. I built Client Mitra solo to fix that for Indian photography studios and creative service businesses. Here is what the product needed, why, and how the technical pieces fit together. ## TL;DR A studio CRM must model events, not deals: enquiry to booking to payment, with multi-day crew calendars. It needs branded GST invoices and quotations with a UPI QR, expense and profit tracking, and permissions that hide money from staff. Because photographers work from their phones, native mobile apps with reminders are part of the core product, not an extra. ## Key takeaways - A CRM for photography studios must model events and bookings, not sales deals, because a wedding can span several days and crew assignments. - Invoices and quotations with the studio's logo, GST details and a UPI QR code remove a whole separate tool from the owner's day. - Role permissions that hide money from staff are a must-have, not a nice-to-have, for studio owners. - Mobile apps with push reminders matter because photographers live on their phones, not at desks. ## Modeling a studio's real workflow The core flow is enquiry, then booking, then payment, then delivery. Each step has data a generic CRM does not expect. ### Enquiries An enquiry captures the client, event type (wedding, pre-wedding, corporate, product shoot), tentative dates and budget. Most come from Instagram or WhatsApp, so the enquiry form has to be fast to fill on a phone while you are still chatting with the client. ### Bookings and events A confirmed booking becomes one or more events. An Indian wedding can easily include a haldi, mehendi, sangeet, wedding day and reception, each on a different date and sometimes in a different city. Each event has its own crew, call time and deliverables. ### Crew calendar This is the feature studio owners care about most. The crew calendar shows who is assigned where across multi-day weddings, and prevents double-booking a second shooter or videographer on the same day. ### Payments, expenses and profit Bookings carry a payment schedule: advance, mid-payment, balance. Expenses (travel, freelancers, equipment rental) are logged against bookings, which gives the owner a per-booking and monthly profit view. ## Data model at a glance Client Mitra has 15 data models in total. Here is a simplified view of the central entities and the fields that matter most, which is a good starting point if you are planning a similar product: | Model | Key fields | Notes | |---|---|---| | Studio (tenant) | name, logo, GSTIN, UPI ID, plan | Branding flows into every PDF | | Member | userId, studioId, role | owner, manager or staff | | Client | name, phone, email, notes | Shared across bookings | | Enquiry | clientId, eventType, dates, status | Converts into a booking | | Booking | clientId, packageAmount, schedule | Parent of events and payments | | Event | bookingId, date, venue, crew[] | Drives the crew calendar | | Invoice / Quotation | lineItems, taxes, totals | Rendered with PDFKit | | Expense | bookingId, category, amount | Feeds the profit view | | Task | assignee, dueAt, bookingId | Reminders via node-cron | ## Invoices with GST and UPI QR Indian clients expect a GST invoice. Clients also prefer paying by UPI. So invoices and quotations are generated as PDFs with PDFKit, include the studio's logo and GST details, and embed a UPI QR code with the amount prefilled. The client scans and pays directly from the invoice. Logos and other uploads are stored on Cloudinary. Because branding is tenant data, each studio's PDFs pull only their own assets. ## Permissions that protect the owner Studio owners have a specific fear: staff seeing package prices and profit. Client Mitra has three roles. Owners see everything. Managers handle operations. Staff see their assigned events, tasks and client contact details, but not money. I go deeper on this pattern in [role-based access control for SaaS teams](/blog/role-based-access-control-saas). ## Mobile apps and App Store realities Photographers are on location most of the day, so the mobile experience is the main experience. Rather than build two native apps, I wrapped the web app in one Flutter shell using flutter_inappwebview, then added native capabilities on top: Google and Apple sign-in, in-app purchase, FCM push notifications with local notifications for reminders, and Crashlytics. App Store review had firm requirements. Because the app offers Google login, Apple's [Sign in with Apple guidelines](https://developer.apple.com/sign-in-with-apple/) required native Apple sign-in. Digital subscriptions on iOS had to go through in-app purchase with a paywall, and I verify receipts server-side with Apple's app-store-server-library. On the web and Android, subscriptions run through Razorpay. ## How I built this in practice [Client Mitra](/work/clientmitra) runs on a Next.js App Router frontend in JavaScript with Tailwind, and TanStack Query with a persisted cache so the app feels instant when reopened on a patchy mobile connection. The backend is Node and Express with MongoDB and Mongoose, JWT auth, and tenant isolation enforced in middleware. Login is by WhatsApp OTP or Google, with Sign in with Apple on iOS. That choice came directly from the audience: many studio owners do not check email regularly but answer WhatsApp instantly. Reminders for tasks and payments run on node-cron and arrive as push notifications through Firebase Admin. The product spans about 30 app pages plus an admin panel. ## Common mistakes - Forcing events into a sales pipeline with stages like "proposal" and "closed won." - Treating a multi-day wedding as a single calendar entry. - Letting every logged-in user see package prices and profit. - Building invoices as plain tables without tax details or a payment method. - Shipping an iOS app with Google login but no Sign in with Apple, and failing review. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Client Mitra case study](/work/clientmitra) - [Software for photography studios](/industries/photography-studios) - [MongoDB vs PostgreSQL for SaaS](/blog/mongodb-vs-postgresql-for-saas) - [Row-level security for multi-tenant apps](/blog/row-level-security-multi-tenant) - [How to build a lead management system that scales](/blog/lead-management-system-development) - [A realistic 12-week SaaS MVP timeline](/blog/saas-mvp-development-timeline) ## FAQ ### What should a CRM for photography studios include? Enquiry tracking, bookings with payment schedules, a crew calendar for multi-day events, client records, tasks, quotations and invoices, expenses and a profit view. Role permissions and mobile access round it out. ### Why not use a generic CRM for a photography business? Generic CRMs model a deal moving through stages. A studio manages events with dates, crew, deliverables and staged payments, so a generic pipeline forces spreadsheets and WhatsApp groups to fill the gaps. ### Can a studio CRM generate GST invoices? Yes. Client Mitra generates GST invoices and quotations as PDFs with the studio's logo and a UPI QR code so clients can pay directly from the invoice. ### Does it work on iPhone and Android? Yes. The web app ships as native Android and iOS apps through a Flutter wrapper, with native sign-in, push notifications and in-app subscriptions on iOS. ## Next step If you run a studio or creative services business and want software built around how you actually work, [get in touch](/#contact). The [photography studios](/industries/photography-studios) page and my [custom CRM development](/services/custom-crm-development) service page have more detail. --- # MongoDB vs PostgreSQL for SaaS: How I Choose URL: https://webdevang.com/blog/mongodb-vs-postgresql-for-saas · Category: CRM & SaaS development · Updated: 2026-11-03 The mongodb vs postgresql for saas debate usually gets argued on vibes: "Mongo is web scale," "Postgres is just better." Neither helps you decide. What helps is looking at the shape of your data, the money flowing through it and the questions you will need to answer from it. I have shipped production SaaS on both. The Antoc real-estate CRM and Client Mitra run on MongoDB. The audit portal I built for an Australian accounting firm and the HNEFA gaming cafe POS run on PostgreSQL. Here is how I decide. ## TL;DR Pick PostgreSQL when data is relational, financial or audit-heavy, and correctness and reporting matter most. Pick MongoDB when data is document-shaped, schemas evolve fast and integrations send varied payloads. Both handle multi-tenant SaaS fine. Your team's experience is a legitimate tiebreaker, and indexes, migrations and access controls matter more than the logo. ## Key takeaways - Choose PostgreSQL when the data is relational, financial or audit-heavy and correctness matters more than schema flexibility. - Choose MongoDB when records are document-shaped, schemas evolve quickly and integrations push varied payloads. - Both databases can run a serious multi-tenant SaaS; the choice is about fit and team skills, not raw capability. - Whichever you pick, indexes, migrations and access controls decide how well it holds up at scale. ## The questions I actually ask 1. **Does money move through this system?** If the app records payments, balances, ledgers or stock, I lean strongly toward Postgres. 2. **Will auditors or regulators look at it?** Constraints, foreign keys and transactional guarantees make audits easier. 3. **How varied is incoming data?** Leads from Meta, Google Ads, portals and webhooks all carry different fields. Documents absorb that easily. 4. **How fast will the schema change?** Early CRMs change weekly. MongoDB with Mongoose schemas lets you move fast without a migration per field. 5. **What reports are needed?** Multi-table joins and aggregations like P&L or tax reports are natural in SQL. 6. **What does the team know?** A team fluent in one database will ship faster and make fewer mistakes with it. ## Side-by-side comparison | Factor | MongoDB | PostgreSQL | |---|---|---| | Data shape | Documents, nested, variable fields | Tables, relations, strict types | | Schema changes | Flexible, app-level validation | Migrations, enforced by the database | | Transactions | Supported, used sparingly | Core strength | | Multi-tenant isolation | Middleware and query scoping | Row-level security policies | | Reporting | Aggregation pipeline | SQL joins, views, functions | | Typical ORM | Mongoose | Prisma, or Supabase client and RPCs | | Best fit in my work | CRMs, lead engines, automation | Audit, accounting, POS, inventory | ## When PostgreSQL wins The audit portal is the clearest case. Auditors reconcile trust accounts by importing bank and ledger lines from CSV and XLSX files and matching them, then verify and lock the reconciliation. Every document, query and test result must link to a specific audit, property and requirement. That is deeply relational data where a broken reference is a real problem. I used PostgreSQL with Prisma across about 31 models. Foreign keys guarantee evidence always points at a real requirement. Transactions make "verify then lock" atomic. The [PostgreSQL documentation on constraints](https://www.postgresql.org/docs/current/ddl-constraints.html) is worth reading if you are building anything financial. HNEFA follows the same logic. Prepaid customer wallets are computed by database functions rather than stored as a balance column, so the balance can never drift from the transactions. FIFO inventory batches and GST/HSN tax reports are natural in SQL. ## When MongoDB wins Antoc is the clearest case the other way. Leads arrive from Meta lead ads, Google Ads, property portals, Google Sheets, webhooks and forms, each with different fields. Custom fields vary by business. WhatsApp flows are stored as graph documents of nodes and edges. MongoDB stores all of that naturally, and Mongoose gives us validation where we want it. Client Mitra is similar: bookings with nested events, crew arrays and payment schedules map cleanly to documents. Development speed mattered for a solo build, and MongoDB kept iteration fast. ## Scaling either one The database choice matters less than the discipline around it. - **MongoDB at 300K+ leads**: compound indexes starting with tenant, bulk operations that validate their filters before running so a bad filter cannot touch every document, and database auth plus network restrictions. - **PostgreSQL in production**: versioned migrations validated in CI. HNEFA has 47 SQL migrations checked automatically on each change, and the audit portal deploys through GitHub Actions. ### A note on using both Occasionally a product genuinely needs both, for example a relational core for billing plus a document store for raw webhook payloads or chat logs. I treat that as a last resort. Two databases mean two backup strategies, two sets of access controls and two places for data to disagree. For an MVP, pick one and push it as far as it will go before adding the other. ## How I built this in practice [The audit portal case study](/work/audit) shows the PostgreSQL side in detail. It runs on Azure Database for PostgreSQL in Australia East, so the firm's data stays in Australia, alongside Azure App Service, Blob Storage with time-limited signed URLs and Azure Communication Email. Prisma handles the schema and migrations, and spreadsheet-based audit programmes became data-driven sections, requirements and tests in relational tables. On the MongoDB side, Antoc and Client Mitra both use Mongoose with tenant-scoped middleware. I would choose the same way again for each: relational correctness where money and audits are involved, document flexibility where the data is messy and fast-changing. ## Common mistakes - Choosing MongoDB for a ledger and reinventing foreign keys in application code. - Choosing Postgres and then storing everything in one giant JSONB column. - Storing computed balances that drift from the underlying transactions. - Skipping indexes until the first slow query in production. - Running schema changes by hand instead of through versioned migrations. ## Internal links - [Custom CRM and SaaS development services](/services/custom-crm-development) - [Audit portal case study on PostgreSQL and Azure](/work/audit) - [Hire a full stack developer in Australia](/hire/full-stack-developer-australia) - [Row-level security for multi-tenant apps](/blog/row-level-security-multi-tenant) - [How to build a lead management system that scales](/blog/lead-management-system-development) - [A realistic 12-week SaaS MVP timeline](/blog/saas-mvp-development-timeline) - [Role-based access control for SaaS teams](/blog/role-based-access-control-saas) ## FAQ ### Is MongoDB or PostgreSQL better for a SaaS startup? Neither is universally better. PostgreSQL suits relational, financial or compliance-heavy products; MongoDB suits document-shaped data with fast-changing schemas. Pick the one that matches your data and your team's experience. ### Can MongoDB handle multi-tenant SaaS? Yes. A tenant ID on every document, compound indexes starting with that ID and middleware that enforces scope give you solid multi-tenancy. I have run multi-tenant CRMs on MongoDB with hundreds of thousands of records. ### Why use PostgreSQL for accounting or audit software? Accounting data is relational and must reconcile exactly. PostgreSQL's transactions, foreign keys, constraints and row-level security make it easier to guarantee correctness and isolation. ### Is it hard to switch databases later? It is expensive. Queries, data models, ORMs and reports all depend on the database. It is worth spending a day on the decision upfront rather than migrating after launch. ## Next step If you are about to pick a database for a new product, [get in touch](/#contact) and I will look at your data model with you. My [custom CRM development](/services/custom-crm-development) page explains how I approach architecture decisions like this. --- # Row-Level Security for Multi-Tenant Apps in Postgres URL: https://webdevang.com/blog/row-level-security-multi-tenant · Category: CRM & SaaS development · Updated: 2026-11-03 The most dangerous bug in a SaaS product is one tenant seeing another tenant's data. Using row level security multi tenant policies in Postgres turns that from "a bug waiting to happen in some query" into something the database refuses to do. I contributed to HNEFA, a multi-tenant gaming cafe POS and ERP built with the Exlaso team on Supabase Postgres, where every tenant's data is isolated by row-level security. This guide covers the patterns that matter when you put RLS into a real product. ## TL;DR Enable RLS on every tenant-owned table and write policies that compare the row's `tenant_id` to a trusted claim from the user's JWT or session. Layer role checks (admin, cashier) on top. Use database functions for sensitive operations, keep service-role keys off the client, index the tenant column, and test cross-tenant access automatically in CI with every migration. ## Key takeaways - Row-level security moves tenant isolation from application code into the database, so a forgotten filter cannot leak data. - Policies should read the tenant from a trusted claim or session setting, never from a value the client can freely change. - Roles like admin and cashier layer on top of tenant policies, restricting which rows and operations each user can touch. - RLS is only as good as its tests, so cross-tenant access checks belong in CI alongside versioned migrations. ## How RLS works for tenancy Without RLS, every query has to include `WHERE tenant_id = ...`. With hundreds of queries across a POS (sessions, orders, inventory, wallets, reports), someone eventually forgets one. With RLS enabled, Postgres appends the policy condition to every query on that table. Here is the shape of a basic tenant policy: ```sql alter table orders enable row level security; create policy tenant_isolation on orders using (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid) with check (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); ``` `using` controls which rows a user can read, update or delete. `with check` controls which rows they can insert or update into. Leaving out `with check` is a classic mistake: users cannot read another tenant's rows but could write into them. The [PostgreSQL row security docs](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) explain both clauses in detail. ## Where the tenant ID comes from The policy is only as trustworthy as its source of `tenant_id`. | Source | Trust level | Notes | |---|---|---| | Signed JWT claim | High | Set server-side at login; client cannot alter it | | Session setting via `set_config` | High, if set by your server | Common in non-Supabase setups with a pooled connection per request | | Lookup from a memberships table | High | Flexible for multi-org users; needs an index | | Request body or query param | Never | Client-controlled, defeats the purpose | For users who belong to more than one organization, I prefer a memberships lookup in the policy, or a short helper function that returns the tenant IDs the current user can access. ## Layering roles on top Tenant isolation answers "which business's data?" Roles answer "what can this person do inside it?" HNEFA has super admin, admin and cashier roles, and a cashier should not be able to edit purchase prices or delete past bills. A practical approach: 1. Keep a tenant isolation policy on every table. 2. Add separate policies per operation (`for select`, `for insert`, `for update`, `for delete`). 3. Check the user's role in policies for sensitive operations, such as allowing deletes only for admins. 4. Push multi-step operations into functions so the rules live in one place. ## RPCs and computed values Some operations should not be raw table writes at all. Closing a gaming session, billing snacks and taking payment across cash, card and UPI involves several tables that must stay consistent. HNEFA uses Supabase RPCs for this kind of work. A notable design choice: prepaid customer wallet balances are computed by database functions from the underlying transactions rather than stored as a column. There is no balance field for someone to update incorrectly, and the number always matches the history. When writing such functions, be deliberate about `security invoker` versus `security definer`. Invoker functions run with the caller's RLS. Definer functions bypass it, so they must check tenant and role explicitly inside. ## Testing and migrations RLS policies are code, and they need tests. My checklist: 1. Every tenant-owned table has RLS enabled. A CI query against `pg_tables` can flag any table where `rowsecurity` is false. 2. Seed two tenants and assert that a user from tenant A gets zero rows from tenant B on every table. 3. Assert that inserts with a foreign `tenant_id` fail. 4. Run end-to-end flows as each role. 5. Version every policy change as a migration, never edit policies by hand in a dashboard. ## How I built this in practice On [the HNEFA case study](/work/hnefa) you can see the full product: a live machine floor of PCs and consoles with realtime timed sessions, bookings, touch POS billing, a cash drawer with denomination counting, FIFO inventory batches, purchases and returns, around 15 reports including P&L and GST/HSN tax, and thermal receipt printing. All of it is multi-tenant on Supabase Postgres with row-level security per tenant. The schema evolves through 47 versioned SQL migrations validated in CI, and Playwright end-to-end tests exercise the real flows. The stack is Next.js, TypeScript and TanStack Query, deployed with Coolify and Nixpacks. Realtime updates for the machine floor use Supabase realtime, which also respects RLS, so one cafe never sees another's live sessions. ## Common mistakes - Enabling RLS on most tables and forgetting the one added last week. - Writing `using` without `with check`, allowing cross-tenant inserts. - Reading the tenant ID from a request parameter instead of a signed claim. - Shipping a service-role key to the browser, which bypasses every policy. - Creating `security definer` functions without explicit tenant checks inside. - Editing policies in a dashboard instead of through versioned migrations. ## Internal links - [Custom CRM and SaaS development services](/services/custom-crm-development) - [HNEFA gaming cafe POS case study](/work/hnefa) - [Software for gaming cafes](/industries/gaming-cafes) - [How to build a lead management system that scales](/blog/lead-management-system-development) - [A realistic 12-week SaaS MVP timeline](/blog/saas-mvp-development-timeline) - [Role-based access control for SaaS teams](/blog/role-based-access-control-saas) - [GST invoice software development](/blog/gst-invoice-software-development) ## FAQ ### What is row-level security in Postgres? Row-level security is a Postgres feature that attaches policies to a table, so every query only sees or changes rows that satisfy the policy. For multi-tenant apps, the policy typically checks that a row's tenant ID matches the current user's tenant. ### Does row-level security slow down queries? There is a small overhead because the policy condition is added to each query. With an index on the tenant column and simple policy expressions, it is rarely noticeable in typical SaaS workloads. ### Do I still need tenant checks in my API if I use RLS? RLS should be the guarantee, but validating inputs and permissions in the API still gives better error messages and defense in depth. Never rely only on the frontend. ### Can Supabase handle multi-tenant apps with RLS? Yes. Supabase exposes Postgres RLS directly, and policies can read claims from the user's JWT. HNEFA, a multi-tenant gaming cafe POS, uses exactly this approach. ### How do service roles and admin tools work with RLS? Service roles bypass RLS, so they must only run on trusted servers and never ship to the browser. Admin features are safer as security-definer functions with explicit checks inside. ## Next step If you are building a multi-tenant product on Postgres and want isolation you can trust, [get in touch](/#contact). My [custom CRM development](/services/custom-crm-development) page covers how I design tenancy, roles and data models. --- # How to Build a Lead Management System That Scales URL: https://webdevang.com/blog/lead-management-system-development · Category: CRM & SaaS development · Updated: 2026-11-03 Lead management system development looks easy on a whiteboard: leads come in, get assigned, someone follows up. The difficulty shows up in production, when the same buyer enquires on three channels in ten minutes, a webhook fires twice, and a sales manager runs a bulk update on the wrong filter. I work on Antoc, a real-estate CRM that manages around 300K leads for 100+ firms. This post is the architecture behind the lead engine, written for the people who will have to build or buy one. ## TL;DR Treat lead sources as unreliable event streams: acknowledge fast, store raw payloads, process idempotently. Normalize phones and emails, then dedupe per tenant. Run assignment from editable rules. Record every touch in an activity timeline. Scale with tenant-first indexes, validated bulk operations and locked-down database access. ## Key takeaways - Treat every lead source as an untrusted, at-least-once event stream and make ingestion idempotent. - Normalize before you dedupe; phone formatting alone breaks most naive duplicate checks. - An assignment engine should be data-driven rules that managers edit, not hard-coded if-statements. - Scaling past a few hundred thousand leads is mostly about indexes, safe bulk operations and access hardening. ## The pipeline, stage by stage | Stage | Job | Failure it prevents | |---|---|---| | Receive | Verify signature, return 200 fast | Provider retries and timeouts | | Store raw | Persist the original payload with source and external ID | Lost leads when parsing fails | | Normalize | Map fields, format phone and email | Duplicates from formatting differences | | Dedupe | Match within tenant on normalized keys | Two agents calling the same buyer | | Assign | Apply rules, notify the agent | Leads sitting unowned | | Automate | Trigger flows like WhatsApp drips | Slow first response | | Record | Write timeline events | No audit trail of what happened | ## Ingestion that survives the real world ### Make it idempotent Most providers deliver webhooks at least once. Meta's leadgen webhooks, for example, give you a lead ID you then fetch through the Graph API; the [Meta Marketing API lead ads docs](https://developers.facebook.com/docs/marketing-api/guides/lead-ads/) describe the flow. Store `source` plus `externalId` with a unique index, so a retried webhook is a no-op instead of a second lead. ### Store before you parse Save the raw payload first, then parse. When a portal changes its format or a field mapping breaks, you can fix the mapper and replay the stored payloads instead of losing a day of leads. ### Keep connectors thin Each source (Meta lead ads, Google Ads, property portals, Google Sheets, generic webhooks, public forms) gets a small adapter that outputs one internal lead shape. Everything downstream, from dedupe onward, only knows that shape. ## Normalization and dedupe Dedupe fails silently, which is why it deserves care. 1. Strip spaces, dashes and leading zeros from phones, apply the default country code for the tenant, and store in E.164 format. 2. Lowercase and trim emails. 3. Match within the same tenant only. A buyer can legitimately be a lead at two different firms. 4. On a match, attach the new enquiry to the existing lead with its source and campaign, bump its activity and optionally re-notify the owner. 5. On no match, create the lead and move to assignment. Keep a compound index on `tenantId + normalizedPhone` so the match is a fast index lookup, not a collection scan. If you also match on email, give it its own tenant-first index rather than relying on an `$or` across unindexed fields. ## Assignment as data Managers change assignment rules constantly: a new agent joins, a project launches, someone goes on leave. If rules are code, every change needs a deploy. Store rules as records instead: conditions (source, project, campaign, time of day) and an action (round robin among a group, a specific agent, the least-loaded agent). Evaluate them in priority order. Log which rule assigned each lead so managers can debug "why did this lead go to the resale team instead of the new-launch team?" without asking a developer. ## Activity timeline and realtime Every meaningful event (created, assigned, called, messaged, stage changed, site visit logged) becomes a timeline entry with actor, type and payload. This powers the lead detail screen, call and visit reports, and automation triggers. Antoc pushes changes to the browser over Socket.IO, so a newly assigned lead appears on an agent's screen immediately. Automation hooks off the same events: a new lead or a stage change can start a WhatsApp flow, and the AI voice agent writes its call outcome back as a timeline event through tool calls. ## How I built this in practice On [the Antoc case study](/work/antoc), the lead engine runs on Node and Express with MongoDB and Mongoose, Socket.IO for realtime and Sentry for error tracking, on GCP VMs in asia-south1 behind Nginx with PM2. The most important lessons came from growth. As the database passed 300K leads we added targeted compound indexes for the hottest queries. Bulk operations, such as reassigning or deleting leads by filter, now validate their filters before execution, so an empty or malformed filter cannot accidentally hit every lead in the tenant. Database access got tighter too, with stronger auth and network restrictions. Antoc also exposes leads through a remote MCP server with OAuth, so Claude can query and update a business's CRM data on the user's behalf. That only works safely because tenant scoping and permissions are enforced in the backend, not in the UI. ## Common mistakes - Creating a lead directly inside the webhook handler and timing out under load. - Deduping on raw phone strings with inconsistent formatting. - Deduping across tenants and merging two businesses' leads. - Hard-coding assignment logic so every rule change needs a release. - Allowing bulk updates without validating the filter first. - Not storing raw payloads, so a mapping bug means permanently lost leads. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Antoc lead management case study](/work/antoc) - [Lead management for real estate firms](/industries/real-estate) - [A realistic 12-week SaaS MVP timeline](/blog/saas-mvp-development-timeline) - [Role-based access control for SaaS teams](/blog/role-based-access-control-saas) - [GST invoice software development](/blog/gst-invoice-software-development) - [POS software development guide](/blog/pos-software-development) ## FAQ ### What are the core components of a lead management system? Source connectors, an ingestion layer that validates and stores raw payloads, normalization and deduplication, an assignment engine, a pipeline with follow-ups, an activity timeline and reporting. Automation and messaging sit on top of these. ### How do you prevent duplicate leads? Normalize phone numbers and emails first, then match on those keys within the same tenant. Decide upfront whether a repeat enquiry updates the existing lead or is logged as a new enquiry on it, and record the source of each touch. ### How many leads can a custom system handle? With proper indexing, a single well-tuned MongoDB or Postgres database comfortably handles hundreds of thousands to millions of leads for typical SMB workloads. Antoc manages around 300K leads across 100+ businesses. ### Should lead ingestion be synchronous or queued? Acknowledge the webhook quickly, store the raw payload, then process it. That keeps you within provider timeouts and lets you replay failed leads without asking the source to resend. ## Next step If leads are slipping through the cracks between your ad accounts, portals and sales team, [get in touch](/#contact). My [custom CRM development](/services/custom-crm-development) page explains how I design lead engines that hold up at scale. --- # SaaS MVP Development: A Realistic 12-Week Timeline URL: https://webdevang.com/blog/saas-mvp-development-timeline · Category: CRM & SaaS development · Updated: 2026-11-03 Most saas mvp development estimates are either wildly optimistic ("four weeks!") or so padded they kill the idea. Twelve weeks is a realistic target for a focused product, but only if you are strict about what "minimum" means and you plan for the boring parts that always take longer than expected. This is the plan I use, shaped by building Client Mitra solo (web app, backend, admin panel and native mobile apps) and by shipping other products for clients. It assumes one experienced full stack developer and a founder who can make decisions quickly. ## TL;DR Spend week 1 on scope, weeks 2–3 on auth, tenancy and roles, weeks 4–7 on the core workflow, weeks 8–9 on billing and notifications, week 10 on mobile or polish, and weeks 11–12 on hardening, onboarding and real users. Start external approvals (payment gateway, app stores, WhatsApp) in week 1. Anything not tied to the core workflow waits until after launch. ## Key takeaways - Twelve weeks is realistic for a SaaS MVP only if the scope is one core workflow done end to end. - Auth, tenancy and roles belong in the first weeks because retrofitting them later touches every feature. - Billing and app store requirements take longer than founders expect, so they need their own dedicated time. - Reserve the last two weeks for hardening, onboarding and real users, not new features. ## The 12-week plan | Week | Focus | Output | |---|---|---| | 1 | Scope and design | One-page scope, data model, clickable flows | | 2–3 | Foundation | Auth, tenants, roles, deploy pipeline, monitoring | | 4–7 | Core workflow | The one job your product does, end to end | | 8 | Billing | Plans, checkout, webhooks, feature gating | | 9 | Notifications and reports | Email or WhatsApp, reminders, a basic dashboard | | 10 | Mobile or polish | Flutter wrapper or responsive refinements | | 11 | Hardening | Permission tests, backups, performance pass | | 12 | Launch | Onboarding, first real users, fix list | ### Week 1: scope like you mean it Write the core workflow as a sentence: "A studio turns an enquiry into a booking, assigns crew and gets paid." Every feature either serves that sentence or goes on the later list. Sketch the data model and the main screens. This is also the week to start external processes: payment gateway KYC, Apple and Google developer accounts, WhatsApp Business verification. They run in parallel and often take weeks. ### Weeks 2–3: foundation Sign-up, login, tenants, memberships and roles. Set up a deploy pipeline and error monitoring before any feature work. It feels slow, but every later feature depends on knowing who the user is, which tenant they belong to and what they are allowed to do. ### Weeks 4–7: the core workflow Four weeks for one workflow sounds generous until you account for edge cases, empty states, validation and the inevitable "actually, it works like this" conversation with real users in week 6. Show working software weekly. ### Week 8: billing Billing is never just a checkout button. You need plans, a checkout flow, webhook handling for renewals and failures, and server-side feature gating. If you sell through iOS, Apple requires in-app purchase for digital subscriptions; the [App Store Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) spell out the rules, and server-side receipt verification adds work. ### Week 9: notifications and reports Reminders and a simple dashboard turn a tool people try into a tool people return to. Keep reports to the three numbers users ask about most. ### Week 10: mobile or polish If your users live on phones, wrap the web app in Flutter for Android and iOS. If they work at desks, spend this week on speed and UX polish instead. ### Weeks 11–12: harden and launch Test permissions by trying to break them. Confirm backups restore. Fix the slowest pages. Then put real users on it, watch them, and keep a ruthless fix list. ## What does not belong in a 12-week MVP 1. A second user type with its own portal, unless the product cannot work without it. 2. AI features that are not the core value of the product. 3. Native apps written separately for iOS and Android. 4. Custom report builders. Ship fixed reports first. 5. More than one or two integrations. 6. A marketing site redesign running in parallel with the product. ## How I built this in practice [Client Mitra](/work/clientmitra) shows what a disciplined solo build looks like once it grows past MVP. The core workflow, enquiry to booking to payment, came first. Then came crew calendars for multi-day weddings, GST invoices and quotations with logo and UPI QR, expenses and a profit view. Today it spans about 30 app pages, an admin panel and 15 data models. Several choices kept the timeline realistic. Next.js App Router with Tailwind and TanStack Query on the frontend, Node, Express and MongoDB on the backend, a stack I can move fast in. Tenant isolation in middleware from the start. Login via WhatsApp OTP or Google, which matched how the audience behaves. One Flutter wrapper with flutter_inappwebview for both mobile platforms instead of two native codebases. The parts that took longer than expected were exactly the ones in this plan's dedicated weeks: App Store review required native Sign in with Apple, an IAP paywall and server-side receipt verification, alongside Razorpay subscriptions on the web. ## Common mistakes - Starting with features before auth, tenancy and roles are settled. - Leaving payment gateway and app store setup until the week of launch. - Treating feedback in week 6 as a failure instead of the point of the exercise. - Adding "just one more" feature in week 11 instead of hardening. - Measuring progress by screens built rather than workflows completed end to end. ## Internal links - [Custom CRM and SaaS development services](/services/custom-crm-development) - [Client Mitra SaaS case study](/work/clientmitra) - [Hire a full stack developer for US startups](/hire/full-stack-developer-usa) - [Role-based access control for SaaS teams](/blog/role-based-access-control-saas) - [GST invoice software development](/blog/gst-invoice-software-development) - [POS software development guide](/blog/pos-software-development) - [Audit and compliance software development](/blog/audit-compliance-software-development) ## FAQ ### How long does SaaS MVP development take? For a focused product with one core workflow, roughly 10 to 14 weeks with an experienced developer. Adding native mobile apps, complex integrations or AI features usually pushes it beyond that. ### What should be included in a SaaS MVP? Sign-up and login, tenant and role setup, the one workflow that delivers your core value, basic reporting, billing if you charge from day one, and error monitoring. Everything else can wait for real user feedback. ### Should an MVP include a mobile app? Only if your users work primarily on phones. A responsive web app or a thin Flutter wrapper around it is usually the fastest path; separate native apps rarely belong in an MVP. ### What usually delays a SaaS MVP? Scope creep, late decisions on pricing and billing, app store review cycles, and third-party approvals like WhatsApp templates or payment gateway onboarding. Start those external processes early. ### Can one developer build a SaaS MVP? Yes, if they are genuinely full stack and the scope is disciplined. I built Client Mitra solo, including the web app, backend, admin panel and Flutter mobile apps. ## Next step If you have a SaaS idea and want a week-by-week plan for it, [get in touch](/#contact) with a short description of the core workflow. My [custom CRM development](/services/custom-crm-development) page explains how I scope and ship MVPs. --- # Role-Based Access Control for SaaS Teams URL: https://webdevang.com/blog/role-based-access-control-saas · Category: CRM & SaaS development · Updated: 2026-11-03 Customers rarely ask for "role based access control." They ask for things like "my assistant should not see what I charge clients" or "the cashier should not be able to delete yesterday's bills." Good role based access control saas design is how you turn those sentences into rules your product enforces every time. I have implemented permission systems in several products: owner, manager and staff roles in Client Mitra, super admin, admin and cashier roles in the HNEFA gaming cafe POS, separate agent and admin portals in an audit platform for an Australian accounting firm, and plan-based feature locks in the Antoc real-estate CRM. Here is the approach that has held up. ## TL;DR Start with three or four named roles that match how your customers talk about their team. Behind them, check granular permission keys in code. Handle field-level visibility (like money) explicitly. Enforce everything on the server, mirror it in the UI, and keep role checks, plan checks and tenant checks as three separate layers. ## Key takeaways - Start with a few named roles, but check fine-grained permission keys in code so roles can change without rewriting features. - Field-level visibility, such as hiding prices and profit from staff, is often what customers care about most. - Every permission must be enforced on the server; hiding a button in the UI is a convenience, not security. - Roles, plan-based feature locks and tenant isolation are three separate checks and should stay separate in code. ## Roles for people, permissions for code The mistake I see most often is code full of `if (user.role === 'manager')`. It works until a customer wants "a manager who can't issue refunds," and suddenly you are editing fifty files. Instead, define permission keys such as `bookings.create`, `invoices.view`, `payments.record`, `reports.profit.view`, `team.manage`. Roles are simply named bundles of those keys. Code only ever asks "does this user have `invoices.view`?" Changing what a manager can do becomes a data change, not a code change. ## A starting permission matrix Here is a simplified matrix in the style I used for a studio CRM. The exact keys will differ for your product, but the shape transfers well. | Permission | Owner | Manager | Staff | |---|---|---|---| | View assigned events and tasks | Yes | Yes | Yes | | Create and edit bookings | Yes | Yes | No | | View package prices and invoices | Yes | Yes | No | | Record payments and expenses | Yes | Yes | No | | View profit and financial reports | Yes | No | No | | Manage team members and roles | Yes | No | No | | Change subscription and billing | Yes | No | No | Write a matrix like this with your customers before writing any code. It forces decisions that otherwise surface as support tickets. ## Field-level visibility Route-level checks are the easy part. The harder and more valuable part is fields. A staff member in a photography studio needs the event date, venue and client phone number, but not the package amount. Practical rules: 1. Shape responses on the server per role. Do not send the price to the client and hide it with CSS. 2. Use a serializer or projection per permission set, so new endpoints do not leak sensitive fields by default. 3. Check exports and PDFs too. A CSV export or invoice download is the most common place a hidden field leaks. 4. Apply the same rules to push notifications and emails, which often include amounts. ## Enforce on the server, mirror in the UI The server is the only place a permission means anything. The [OWASP Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html) puts it well: deny by default and validate permissions on every request. My request pipeline is consistent across projects: 1. Authenticate the user from a verified token. 2. Resolve the active tenant and the user's membership in it. 3. Load the membership's permissions. 4. Check the plan allows the feature. 5. Check the permission for the specific action. 6. Run the query scoped to the tenant. The frontend receives the same permission list and uses it to hide buttons and menu items. That keeps the interface clean, but it is never the line of defense. ## Roles, plans and tenants are different questions These three checks get tangled constantly: - **Tenant isolation** answers "which organization's data?" - **Plan gating** answers "has this organization paid for this feature?" Antoc uses plan-based feature locking for this. - **Roles and permissions** answer "is this person allowed to do this here?" A feature should work only when all three pass, and each check should live in its own layer so you can change pricing without touching permissions, and vice versa. In Postgres products like HNEFA, tenant isolation is pushed further down into row-level security, with role checks layered on top. ## Stronger auth for sensitive roles Higher-privilege roles deserve stronger sign-in. On the audit portal, sign-in goes password, then email OTP, then an optional TOTP authenticator, with short-lived access tokens held in memory and httpOnly refresh cookies. Agents and auditors also use separate portals, which keeps admin-only actions like releasing a final report physically out of the agent interface. ## How I built this in practice In [Client Mitra](/work/clientmitra), memberships connect users to studios with a role of owner, manager or staff. Express middleware verifies the JWT, resolves the tenant and attaches permissions before any route runs. Financial fields are stripped from responses for staff, which is how a second shooter can see their call time and venue but never the package price. The same rules apply to the Flutter mobile apps, because they wrap the same web app and hit the same API. The owner role also controls subscriptions, whether bought through Razorpay on the web or Apple in-app purchase on iOS, so only the person paying can change the plan. ## Common mistakes - Checking role names directly in code instead of permission keys. - Hiding sensitive fields in the UI while still returning them from the API. - Forgetting exports, PDFs and notifications when restricting fields. - Mixing plan checks and role checks in the same condition. - Building a custom role editor before any customer has asked for one. ## Internal links - [Custom CRM and SaaS development services](/services/custom-crm-development) - [Client Mitra roles and permissions case study](/work/clientmitra) - [Software for photography studios](/industries/photography-studios) - [GST invoice software development](/blog/gst-invoice-software-development) - [POS software development guide](/blog/pos-software-development) - [Audit and compliance software development](/blog/audit-compliance-software-development) - [Bank reconciliation automation](/blog/bank-reconciliation-automation) ## FAQ ### What is role-based access control in a SaaS app? It is a way of deciding what each user can see and do based on the role they hold within their organization, such as owner, manager or staff. Roles map to a set of permissions that the server checks on every request. ### How many roles should a SaaS product start with? Usually three or four. Owner, admin or manager, and a standard staff role cover most SMB products. Add custom roles only when several customers ask for the same variation. ### Should permissions be checked on the frontend or backend? Both, for different reasons. The backend check is the real security; the frontend check just hides actions the user cannot take so the interface stays clean. ### What is the difference between RBAC and plan-based feature locking? RBAC decides what a person can do inside their organization. Plan-based locking decides what the organization has paid for. A feature should be available only when both checks pass. ## Next step If your customers are asking for finer control over who sees what, [get in touch](/#contact) and I can help design a permission model that fits. My [custom CRM development](/services/custom-crm-development) page covers how I build roles, tenancy and billing into SaaS products. --- # Building GST Invoices and UPI QR Into SaaS URL: https://webdevang.com/blog/gst-invoice-software-development · Category: CRM & SaaS development · Updated: 2026-11-03 Most Indian SaaS products eventually hit the same request: "Can we send a proper GST invoice from here?" GST invoice software development sounds like a small feature, but it touches your data model, tax math, document rendering, numbering rules and payments all at once. Get the foundations wrong and you end up patching rounding errors and edited invoices for years. I built the invoicing and quotation module for Client Mitra, a multi-tenant CRM for photography studios and creative service businesses. This post walks through what that build taught me: how to model invoices, compute tax, render branded PDFs and add a UPI QR code that gets studios paid faster. ## TL;DR Model invoices as frozen snapshots, not live joins. Keep amounts in paise, compute CGST/SGST or IGST per line with one shared function, and generate PDFs on the server. Add a UPI QR built from a `upi://pay` link with the amount and invoice number pre-filled. Make quotations and invoices share one line-item structure so conversion is a single click. ## Key takeaways - Treat invoices as immutable snapshots of customer, business and tax data at the moment of issue, not live views of other records. - Store money in the smallest unit and compute CGST, SGST or IGST per line from a single tax function used everywhere. - A UPI QR code is just a upi://pay deep link encoded as an image, so it costs almost nothing to add and shortens time to payment. - Quotations, invoices and payments should share one line-item model so converting a quote to an invoice is a copy, not a re-entry. ## The data model behind a GST invoice The most common mistake I see is an invoice table that stores a `customerId` and looks up the customer's name and GSTIN at render time. Six months later the customer changes their address, and every old invoice silently changes too. That is a compliance problem. Instead, an invoice should copy everything it prints at the moment it is issued. In practice that means three groups of fields. | Group | Fields to snapshot | Why | |---|---|---| | Seller | business name, GSTIN, address, state code, logo URL, UPI VPA | Your own details change too (new logo, new office) | | Buyer | name, GSTIN (optional for B2C), billing address, place of supply | Place of supply decides intra- vs inter-state tax | | Lines | description, HSN/SAC, qty, rate, discount, tax rate, computed tax | Rates and catalogs change after issue | Alongside those, keep `invoiceNumber`, `issueDate`, `dueDate`, `status` (draft, issued, partially paid, paid, cancelled) and a `tenantId`. In Client Mitra every query runs through tenant isolation middleware, so one studio can never fetch another's invoices even with a guessed ID. ### Numbering that never collides Invoice numbers must be unique and sequential per business per financial year. Do not generate them with `count() + 1`, because two staff members issuing at the same second will collide. Use an atomic counter document per tenant and financial year, incremented with a single `findOneAndUpdate` and `$inc`, and assign the number only when the draft becomes issued. Drafts do not consume numbers. ## Getting the tax math right GST math is simple until it isn't. The rules that matter for most service businesses: 1. Compare the seller's state code with the place of supply. 2. Same state: split the rate into CGST and SGST (for example 18% becomes 9% + 9%). 3. Different state: apply the full rate as IGST. 4. Compute tax per line on the taxable value after discount, then sum. 5. Round each tax component to the paisa, then round the grand total as your business rules require, showing any round-off as its own line. Write this once as a pure function, something like `computeInvoiceTotals(lines, sellerState, placeOfSupply)`, and call it from the API, the PDF renderer and the UI preview. When the browser computes one total and the server computes another, customers notice before you do. Store all money as integers in paise. JavaScript floating point turns `0.1 + 0.2` into `0.30000000000000004`, and across hundreds of line items that becomes a visible one-rupee mismatch between the PDF and your reports. ### Quotations use the same engine Studios send quotations first, then convert the accepted quote to an invoice. If quotations have their own schema, conversion becomes a manual re-entry and the numbers drift. In Client Mitra quotations and invoices share the line-item shape and the totals function. Converting is a copy into a new invoice draft with a reference back to the quote. ## Branded PDFs and the UPI QR code Customers judge a business by its invoice. Small businesses want their logo, their colors and a clean layout, not a generic template with your SaaS branding on top. I render invoices server-side with PDFKit in Node. Server rendering means the same PDF whether it is downloaded on a phone, emailed, or shared through a link on WhatsApp. Business logos are stored on Cloudinary, so the renderer fetches a resized version instead of embedding a 4 MB phone photo into every PDF. ### Adding a UPI QR A UPI QR is the highest-value, lowest-effort addition to any Indian invoice. The QR simply encodes a deep link: ``` upi://pay?pa=studio@okbank&pn=Studio%20Name&am=25000.00&cu=INR&tn=INV-2026-0142 ``` Here `pa` is the payee VPA, `pn` the payee name, `am` the amount, `cu` the currency and `tn` a note that should contain the invoice number. Generate the QR as a PNG on the server and place it near the total with a "Scan to pay" label. When the customer scans, their UPI app opens with the amount and reference already filled in, which removes the most common reason for payment delays: typing the wrong amount or forgetting the reference. Two cautions. First, use the balance due, not the invoice total, once partial payments exist. Second, a static UPI QR does not notify your system of payment. Staff still mark payments received, or you add a payment gateway for automatic confirmation. If you want gateway-based collection, [Razorpay's payment links documentation](https://razorpay.com/docs/payments/payment-links/) covers the hosted flow. ## Payments, expenses and the profit view An invoice module is only half useful if payments live somewhere else. Each invoice should have a payments array or collection with amount, mode (UPI, cash, bank transfer, card), date and who recorded it. Status is derived: if payments sum to the total, it is paid. Once payments and expenses sit in the same database, a basic profit view per booking or per month becomes a query instead of a spreadsheet exercise. ## How I built this in practice In [the Client Mitra case study](/work/clientmitra) I built the whole product solo: a Next.js App Router front end with Tailwind and TanStack Query, and a Node/Express API on MongoDB with Mongoose. The invoicing piece covers GST invoices and quotations carrying the studio's own logo and a UPI QR, recorded payments, expenses and a profit view, plus reports. PDFs are generated with PDFKit on the server and logos come from Cloudinary. Owners, managers and staff have different permissions, so staff can run the crew calendar for multi-day weddings without seeing any money. Tenant isolation is enforced in middleware, and node-cron sends payment reminders for overdue invoices. The same web app ships as native Android and iOS apps through a Flutter wrapper, so studios can share an invoice straight from their phone. ## Common mistakes - Rendering invoices from live customer and product records instead of a frozen snapshot at issue time. - Using floating point rupees, which creates one-rupee mismatches between PDFs, dashboards and reports. - Generating invoice numbers with a count query, which collides under concurrent issuing. - Building quotations with a separate schema, forcing manual re-entry when a quote is accepted. - Encoding the invoice total in the UPI QR after a partial payment has already been received. - Allowing edits to issued invoices instead of using cancellation and credit notes. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Client Mitra case study: CRM with GST invoices for studios](/work/clientmitra) - [Hire a full stack developer in India](/hire/full-stack-developer-india) - [POS software development for gaming cafes](/blog/pos-software-development) - [Audit and compliance software development](/blog/audit-compliance-software-development) - [Bank reconciliation automation](/blog/bank-reconciliation-automation) - [Next.js SaaS development architecture](/blog/nextjs-saas-development) ## FAQ ### How long does GST invoice software development take inside an existing SaaS? For a focused module with quotations, invoices, PDF output and a UPI QR, plan on roughly three to six weeks of development. The range depends on how many tax edge cases you support and whether payments must reconcile automatically. ### Do I need a GST API or e-invoicing integration? Not always. Small businesses below the e-invoicing threshold only need a correctly formatted tax invoice. If your customers cross the threshold, plan a separate integration with the government invoice registration portal through an approved provider. ### Can a UPI QR code on an invoice include the exact amount? Yes. The upi://pay link supports payee VPA, payee name, amount, currency and a transaction note, so the customer's app opens with the amount and invoice number already filled in. ### Should invoices be generated on the server or in the browser? Generate them on the server. Server-side PDFs look identical on every device, can be emailed or shared by link, and keep your numbering and tax logic in one trusted place. ## Next step If you want GST invoicing, quotations and UPI collection inside your product, I can scope it with you in one call. Read more about my [custom CRM development](/services/custom-crm-development) work or [get in touch](/#contact) with what you are building. --- # POS Software Development for Gaming Cafes URL: https://webdevang.com/blog/pos-software-development · Category: CRM & SaaS development · Updated: 2026-11-03 Gaming cafes are a tough fit for off-the-shelf billing tools. They sell time on PCs and consoles, snacks and drinks, prepaid recharges and bookings, often all on one bill. That is why POS software development for this niche is less about a pretty till and more about a reliable engine for sessions, money and stock. I contributed to HNEFA, a gaming cafe POS and ERP built with the Exlaso team. This post breaks down the pieces a real gaming cafe POS needs, the architecture decisions that kept it accurate, and the mistakes worth avoiding if you are planning your own build. ## TL;DR A gaming cafe POS combines a realtime machine floor with timed sessions and a retail till. The hard parts are accurate session billing, wallet balances that never drift, FIFO stock costing, cash drawer reconciliation and tax reports. HNEFA solved these with Next.js, TypeScript and Supabase Postgres using RPCs, row-level security and realtime updates. ## Key takeaways - A gaming cafe POS is really two systems: a realtime session engine for machines and a retail till for snacks and recharges. - Wallet balances should be computed from transactions by the database, never stored as a column that can drift. - FIFO inventory batches give accurate cost of goods, which is what makes the P&L report trustworthy. - Row-level security in Postgres keeps multi-tenant data isolated even if an API bug slips through. ## What a gaming cafe POS actually has to do Before writing code, list the jobs the counter staff do in a shift. For a gaming cafe, it looks like this: | Job | What the software must handle | |---|---| | Start a session | Pick a machine, pick a rate (hourly, package, member), start a timer visible to everyone | | Extend or end | Add time, switch machines, stop and price the session correctly | | Sell snacks | Touch grid of products, quantity, add to the same bill as the session | | Take payment | Cash, card, UPI, split payments, prepaid wallet | | Bookings | Reserve machines for a time slot without double booking | | Shift close | Count cash by denomination, compare against expected, record variance | | Stock | Purchases, returns, current stock, reorder visibility | | Reports | Day summary, P&L, GST/HSN tax, cash, stock | Every row in that table is a place where money can quietly leak. A session that keeps running after the customer leaves, a snack that never hits the bill, a cash count nobody checks. Good POS software makes the leak visible. ## The realtime machine floor The machine floor is the screen staff stare at all day. Each PC or console shows its state: free, in session, booked, or offline, with time remaining. When one cashier starts a session, every other terminal and the owner's dashboard must update instantly. HNEFA uses Supabase realtime for this. Session rows change in Postgres, and subscribed clients receive the change and refresh their view through TanStack Query. That avoids polling and keeps two cashiers from starting sessions on the same machine. ### Price at the end, store the facts A key design choice is to store session facts (machine, rate plan, start time, pauses, end time) and compute the price when the session closes. Do not keep incrementing a "current amount" field every minute. Computing from facts means you can always explain a bill, and rate rules like "first hour full price, then per 15 minutes" live in one place. ## Money that adds up: wallets, cash drawers and payments ### Prepaid wallets computed by the database Regulars top up wallets and play against the balance. The tempting design is a `balance` column you increment and decrement. It works until a network retry double-applies a top-up or a failed transaction leaves a partial update. Then the balance is wrong and nobody can say why. In HNEFA, wallet balances are computed by database functions from the underlying transactions rather than stored as columns. The ledger is the truth, and the balance is always derivable. Postgres functions (exposed as Supabase RPCs) do the work close to the data, so the calculation is fast and the same for every client. The [Supabase database functions docs](https://supabase.com/docs/guides/database/functions) are a good primer on the pattern. ### Cash drawer with denomination counting At shift close, staff count notes and coins by denomination. The POS multiplies, totals and compares against expected cash from the shift's cash payments. The variance gets recorded against the shift. This one feature changes behavior at the counter more than any report, because everyone knows the count is checked. ### Thermal receipts Customers expect a printed receipt. A browser-based POS can print to standard thermal printers with a receipt-width print stylesheet, keeping the layout tight: business details, items, session duration, taxes, payment mode. ## Inventory and reports owners trust Snacks and drinks look trivial, but they decide whether the P&L is real. HNEFA tracks inventory in FIFO batches: each purchase creates a batch with quantity and unit cost, and sales consume the oldest batch first. That gives true cost of goods sold even when supplier prices change month to month. Purchases and returns adjust batches rather than overwriting a single stock number. With sessions, sales, wallets, purchases and cash all in one Postgres database, reports become queries. HNEFA ships around 15, including: 1. Day summary for the shift and the day 2. Profit and loss using FIFO cost 3. GST and HSN tax summary for filing 4. Cash report reconciling drawer counts 5. Stock report with current batches Because these run as SQL close to the data, numbers match across reports. If the day summary and the tax report disagree, owners stop trusting both. ## Multi-tenancy, roles and safe change HNEFA is multi-tenant: many cafes run on one deployment. Isolation is enforced with Postgres row-level security per tenant, so a query can only ever see rows for the user's tenant. RLS is a second wall behind your API checks; even a buggy endpoint cannot leak another cafe's sales. See the [PostgreSQL row security docs](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) for how policies work. Roles are super admin, admin and cashier. Cashiers can run sessions and bills but cannot edit prices or see the P&L. Schema changes are frequent in a POS as owners ask for new reports. HNEFA has 47 versioned SQL migrations, validated in CI, so every change is reviewed and replayable. Playwright end-to-end tests cover critical flows like starting a session and closing a bill. ## How I built this in practice HNEFA was built with the Exlaso team, and I contributed to it as a developer. You can see the scope in [the HNEFA case study](/work/hnefa). The stack is Next.js with TypeScript on the front end and Supabase for Postgres, RPCs, row-level security and realtime, with TanStack Query managing client state. The product covers the live machine floor with realtime timed sessions, bookings, touch POS billing for sessions and snacks, cash, card and UPI payments, a cash drawer with denomination counting, prepaid wallets computed by database functions, FIFO inventory batches, purchases and returns, around 15 reports and thermal receipt printing. Deployment runs on Coolify with Nixpacks, and the 47 migrations plus Playwright e2e tests run in CI before anything reaches a cafe. ## Common mistakes - Storing a running wallet balance as a column instead of deriving it from a transaction ledger. - Updating a session amount every minute instead of pricing from start, pause and end facts. - Tracking stock as a single number, which makes cost of goods and P&L guesswork. - Relying only on API checks for tenant isolation with no row-level security behind them. - Skipping the denomination-based cash count at shift close. - Changing the production schema by hand instead of through versioned migrations. ## Internal links - [Custom CRM and business software development](/services/custom-crm-development) - [HNEFA gaming cafe POS case study](/work/hnefa) - [Software for gaming cafes](/industries/gaming-cafes) - [Audit and compliance software development](/blog/audit-compliance-software-development) - [Bank reconciliation automation](/blog/bank-reconciliation-automation) - [Next.js SaaS development architecture](/blog/nextjs-saas-development) - [CRM data migration from spreadsheets](/blog/crm-data-migration) ## FAQ ### How much does custom POS software development cost? A focused POS for one business type typically runs from a few weeks for a billing-only MVP to several months for sessions, inventory, wallets and full reporting. The biggest cost drivers are hardware integration, offline needs and the number of reports. ### Can a web-based POS print thermal receipts? Yes. A browser POS can print to 80 mm or 58 mm thermal printers using a receipt-sized print layout, and it can open a cash drawer that is connected through the printer. ### Why not just use an off-the-shelf POS for a gaming cafe? Generic retail POS systems do not understand timed machine sessions, per-machine pricing, bookings or prepaid playtime. Cafes end up running a separate timer app and reconciling by hand, which is where revenue leaks. ### Should a multi-location POS be multi-tenant? If you plan to sell it to more than one business, yes. Build tenant isolation into the database from day one, because retrofitting it after launch means touching every query and report. ## Next step If you run gaming cafes or want to build a POS product for a niche that generic tools ignore, I would like to hear about it. See my [gaming cafe software](/industries/gaming-cafes) work and [get in touch](/#contact) to scope your build. --- # Building Audit and Compliance Software for Accountants URL: https://webdevang.com/blog/audit-compliance-software-development · Category: CRM & SaaS development · Updated: 2026-11-03 Many accounting firms still run specialist audits on spreadsheets, shared drives and long email threads. It works until volume grows, a reviewer leaves, or a regulator asks how a sample was chosen. Audit compliance software development replaces that patchwork with a system where every document, query, test and sign-off has a home. I built an audit portal solo for an Australian accounting firm that audits estate agents' trust accounts. This post shares the blueprint: which modules matter, how to model an audit programme as data, and what security looks like when your users are accountants. ## TL;DR Good audit software has a client upload portal, an auditor review workflow (verify, reject, raise query), reproducible sampling, a data-driven audit programme with evidence, reconciliation tools and one-click reporting. Wrap it in strong sign-in and regional data hosting. The highest-value step is converting the firm's spreadsheet methodology into structured data. ## Key takeaways - The fastest win in audit software is replacing email attachments with a structured client upload portal tied to each engagement. - Turning spreadsheet audit programmes into data (sections, requirements, tests) lets firms reuse, version and report on their methodology. - Random sampling must be reproducible and saved, so a reviewer can see exactly which items were selected and why. - Security and data residency are product features for accountants, not infrastructure afterthoughts. ## The modules an audit portal needs Start by mapping the life of one engagement, from "client invited" to "final report released". For a trust-account audit, the modules fall out naturally. | Module | Who uses it | Core actions | |---|---|---| | Client portal | Agents (the audited business) | Upload preliminary documents and per-property documents, answer queries | | Document review | Auditors | Verify, reject with reason, raise a query on any document | | Sampling | Auditors | Select a random subset of properties for detailed testing | | Audit programme | Auditors | Work through sections, requirements and tests, attach evidence | | Reconciliation | Auditors | Import bank and ledger lines, match, track variances, lock | | Billing | Admin | Upload invoices for the engagement | | Reporting | Admin | Release final report and audit pack as PDF or Excel | Two separate portals keep this clean: an agent portal with a narrow, guided experience, and an admin portal for the firm. They share a backend but never share screens. ### Review states that leave a trail Each uploaded document carries a status: pending, verified, rejected, or queried. Rejections need a reason. Queries open a thread. Every transition records who did it and when. That history is what lets a manager review an engagement without asking the junior auditor what happened. ## Turning a spreadsheet programme into a data-driven engine Most firms already have a methodology. It just lives in a workbook with tabs per section and rows per test. The temptation is to hard-code those screens. Do not. The methodology will change next year, and you will be redeploying for wording edits. Instead, model the programme as data: 1. **Programme template**: a versioned set of sections for a given audit type. 2. **Section**: an ordered group such as "Trust account receipts". 3. **Requirement**: what must be true, often citing a regulation. 4. **Test**: a concrete procedure with a result (pass, fail, not applicable) and a notes field. 5. **Evidence**: files or references linked to a test. When an engagement starts, it instantiates a copy of the current template. Edits to the template affect future engagements, not ones in progress. Reporting then becomes straightforward: count failed tests by section, list exceptions, and include them in the audit pack. In my experience this is the change that matters most: the methodology becomes queryable and consistent across auditors. ## Sampling you can defend Auditors rarely test every property. They sample, typically a small percentage, with a floor so tiny portfolios still get meaningful coverage. Software makes this both easier and more rigorous, if you do it right. Use a Fisher–Yates shuffle for an unbiased random order, then take the first N items where N is the larger of the percentage and the minimum count. Save the selection run: date, who ran it, the population size, the parameters and the chosen items. If an auditor reruns sampling, it creates a new run instead of overwriting the old one. Nobody can quietly regenerate a sample until it looks convenient. ## Security and data residency for accountants Accounting firms hold sensitive financial records, and their clients ask where data lives. Build for that from the first sprint. **Sign-in.** A layered flow works well: password, then a one-time code by email, then an optional TOTP authenticator for users who want it. Keep short-lived access tokens in memory on the client and put refresh tokens in httpOnly cookies, so a script injected into the page cannot read a long-lived credential. **Files.** Store documents in private object storage and hand out time-limited signed URLs when someone opens a file. Links expire, so a forwarded URL stops working. **Region.** Host the app, database and storage in the client's country. The [Azure Blob Storage SAS documentation](https://learn.microsoft.com/azure/storage/common/storage-sas-overview) explains the signed-URL approach on Azure. ## How I built this in practice In [the audit portal case study](/work/audit) I describe the system I built solo for an Australian accounting firm. Estate agents upload preliminary and per-property documents. Auditors verify, reject or raise queries, randomly sample around 5% of properties using Fisher–Yates with a minimum count and saved selection runs, and work through an audit programme of sections, requirements and tests with evidence. Trust-account reconciliation imports bank and ledger lines from CSV or XLSX, auto-matches them at exact, strong and fuzzy levels, tracks variances, then moves through verify and lock. Admins upload invoices and release the final report and audit pack as PDF or Excel. Query threads update in real time over Socket.IO. The stack is Prisma with around 31 models on Azure PostgreSQL, Azure App Service, Azure Blob Storage with time-limited signed URLs, and Azure Communication Email, all in Azure Australia East. GitHub Actions handles CI/CD. Sign-in is password, then email OTP, then optional TOTP, and both portals support light and dark themes. ## Common mistakes - Hard-coding the audit programme into screens, so every methodology update becomes a code release. - Letting engagements reference a live template, so editing the template rewrites past audits. - Regenerating samples in place rather than saving each selection run with its parameters. - Serving documents from public URLs or long-lived links instead of short-lived signed URLs. - Mixing client and auditor experiences in one portal, which confuses clients and risks exposing internal notes. - Treating data residency as a later migration rather than a first-week hosting decision. ## Internal links - [Custom CRM and workflow software development](/services/custom-crm-development) - [Audit portal case study for an Australian accounting firm](/work/audit) - [Software for accounting and compliance firms](/industries/accounting-compliance) - [Bank reconciliation automation: bank vs ledger matching](/blog/bank-reconciliation-automation) - [Next.js SaaS development architecture](/blog/nextjs-saas-development) - [CRM data migration without losing records](/blog/crm-data-migration) - [Razorpay subscription integration for SaaS](/blog/razorpay-subscription-integration) ## FAQ ### How long does audit compliance software development take? A focused portal for one audit type, with uploads, review, sampling, a programme engine and reports, typically takes three to five months for one experienced developer. Adding more audit types later is faster once the programme engine is data-driven. ### Can audit software keep client data in a specific country? Yes. Choose a cloud region in that country for the app server, database and file storage, and use services that do not replicate data elsewhere by default. For Australian clients, Azure Australia East is one option I have used. ### How should audit sampling work in software? Use a proper random algorithm such as Fisher–Yates shuffle, enforce a minimum sample count, and save each selection run with its parameters. That way the sample is defensible and cannot be quietly regenerated. ### Do accountants need two-factor authentication on an audit portal? They should have it. Audit portals hold financial records, so password plus email OTP with an optional authenticator app is a sensible baseline for both staff and clients. ### Is off-the-shelf audit software a better choice? For standard financial statement audits, often yes. Custom software pays off when a firm runs a specialized audit type that generic tools handle through spreadsheets and email. ## Next step If your firm runs a specialist audit on spreadsheets and email, I can help turn it into a secure portal. See my [accounting and compliance](/industries/accounting-compliance) work and [get in touch](/#contact) to talk through your methodology. --- # Bank Reconciliation Automation: Bank vs Ledger Matching URL: https://webdevang.com/blog/bank-reconciliation-automation · Category: CRM & SaaS development · Updated: 2026-11-03 Reconciling a bank statement against a ledger is one of those jobs that looks mechanical but eats hours. Someone exports two spreadsheets, sorts both by amount, and ticks lines off one by one. Bank reconciliation automation takes that routine matching off people's plates so they can focus on the lines that genuinely do not agree. I built a reconciliation module as part of an audit portal for an Australian accounting firm, used to reconcile estate agents' trust accounts. This post covers the parts that make automated matching accurate: clean imports, tiered matching rules, variance tracking and a lock step that makes the result auditable. ## TL;DR Import bank and ledger lines from CSV or XLSX through a column mapper, normalize everything, then match in tiers: exact first, strong next, fuzzy last as suggestions only. Track what remains unmatched as variances with explanations. When the numbers agree, a reviewer verifies and locks the reconciliation so it cannot change. ## Key takeaways - Most reconciliation pain comes from messy imports, so normalize dates, amounts and references before attempting any match. - Tiered matching (exact, strong, fuzzy) lets software clear the obvious pairs while humans review only the uncertain ones. - Fuzzy matches should be suggestions that a person confirms, never automatic final matches. - A verify-then-lock step turns a reconciliation into an auditable record that cannot drift after sign-off. ## Step one: imports that do not lie Every bank exports statements differently. One puts debits and credits in separate columns, another uses a single signed amount, a third adds a running balance and a header block. Ledgers from accounting software have their own quirks. If you match on raw imported data, you will get false mismatches all day. A practical import pipeline looks like this: 1. **Upload** a CSV or XLSX file per side (bank, ledger) for the period. 2. **Map columns**: the user picks which column is date, description, reference, debit, credit or signed amount. Save the mapping per source so next month is one click. 3. **Normalize**: parse dates into one format, convert amounts to integer cents with consistent signs, trim and uppercase references, collapse whitespace in descriptions. 4. **Validate**: reject rows with unparseable dates or amounts and show them, rather than silently dropping them. 5. **Check totals**: compare the sum of imported lines with the statement's opening and closing balances when available. Step five catches more problems than any matching algorithm. If imported totals do not equal the statement movement, the file is incomplete, and matching it is pointless. For XLSX parsing in Node, libraries such as SheetJS handle most real-world workbooks; see the [SheetJS documentation](https://docs.sheetjs.com/) for parsing options like date handling. ## Step two: tiered matching rules The core idea is to clear high-confidence matches automatically and push everything else to a review queue, sorted by how likely it is to be a match. | Tier | Rule | What happens | |---|---|---| | Exact | Same amount, same date, same normalized reference | Matched automatically | | Strong | Same amount, date within a small window (for example 1 to 3 days), reference or description overlap | Matched automatically or with one-click confirm, depending on firm policy | | Fuzzy | Same amount, wider date window, partial text similarity | Suggested only, reviewer accepts or rejects | | Unmatched | No candidate above threshold | Goes to variance list | ### Why order matters Run tiers in order and remove matched lines from the pool after each tier. If you run fuzzy matching first, a loose rule might grab a line that had a perfect exact partner elsewhere. Exact first means the safest pairs lock in before any guessing starts. ### One-to-one, then one-to-many Start with one-to-one matches. Then handle the common many-to-one case: several receipts in the ledger deposited as one bank credit. A simple approach looks for small groups of ledger lines on the same day whose sum equals a single bank line. Cap the group size, because subset-sum search explodes quickly, and always present these as suggestions. ### Scoring fuzzy candidates For fuzzy candidates, compute a score from a few signals: amount equal (required), days apart (penalty per day), and text similarity between references and descriptions, for example token overlap after removing common words like "TRANSFER" or "DEPOSIT". Show the score and the reasons in the UI. Reviewers trust suggestions they can understand. ## Step three: variances, verification and lock Whatever remains unmatched is a variance. Variances are not failures. They are often timing differences: a deposit recorded in the ledger on the 30th that clears the bank on the 2nd, or unpresented payments. Track each variance with a type (timing, error, unexplained), a note and who classified it. The reconciliation screen should always show: - Bank closing balance - Ledger closing balance - Total of explained variances - Remaining unexplained difference When the unexplained difference is zero, or within the firm's tolerance, a reviewer verifies the reconciliation. Then it is locked: no more imports, no re-matching, no edits. If something must change later, an authorized user reopens it and the reopening is recorded. This verify-then-lock workflow is what turns a working spreadsheet into evidence. ## Storage and data model The data model is small but deliberate. A `Reconciliation` belongs to an engagement and a period and has a status (draft, in review, verified, locked). `BankLine` and `LedgerLine` rows belong to it with normalized fields plus the raw imported row for traceability. A `Match` links one or more bank lines to one or more ledger lines, with a tier, a score and who confirmed it. A relational database fits this well, since matches are many-to-many and totals need consistent aggregation; see the [PostgreSQL aggregate functions docs](https://www.postgresql.org/docs/current/functions-aggregate.html) for the summing patterns involved. ## How I built this in practice The reconciliation module lives inside the audit portal described in [the audit portal case study](/work/audit), which I built solo for an Australian accounting firm. Auditors import bank and ledger lines from CSV or XLSX, the system auto-matches them at exact, strong and fuzzy levels, tracks variances, and moves each reconciliation through verify and then lock. It runs on Azure PostgreSQL with Prisma as the ORM, on Azure App Service in Australia East, with GitHub Actions for CI/CD. Reconciliation sits alongside the rest of the audit workflow: document review, sampling of around 5% of properties, an audit programme of tests with evidence, and the final report and audit pack in PDF or Excel. Because reconciliation results live in the same database, they feed straight into that final audit pack instead of being pasted in from a separate workbook. ## Common mistakes - Matching on raw imported data before normalizing dates, signs, amounts and references. - Skipping the import totals check against the statement's opening and closing balances. - Running fuzzy rules before exact ones, so loose matches steal lines from perfect pairs. - Auto-accepting fuzzy matches instead of keeping them as reviewer suggestions. - Discarding the raw imported row, which makes it impossible to trace a line back to the source file. - Leaving reconciliations editable after sign-off instead of locking them. ## Internal links - [Custom CRM and finance workflow development](/services/custom-crm-development) - [Audit portal case study with trust account reconciliation](/work/audit) - [Software for accounting and compliance firms](/industries/accounting-compliance) - [Next.js SaaS development architecture](/blog/nextjs-saas-development) - [CRM data migration from spreadsheets](/blog/crm-data-migration) - [Razorpay subscription integration for SaaS](/blog/razorpay-subscription-integration) - [Scaling a CRM database to 300K leads](/blog/scaling-crm-database) ## FAQ ### Can bank reconciliation be fully automated? Not completely. Software can clear most exact and near-exact pairs, but timing differences, split payments and unclear references still need a person. The goal is to shrink manual review to the exceptions. ### What file formats should a reconciliation tool accept? CSV and XLSX cover nearly every bank export and accounting ledger. Build a column-mapping step so users can tell the importer which column holds the date, amount, description and reference. ### How does fuzzy matching work for bank transactions? It scores candidate pairs on amount equality, date proximity and text similarity between descriptions or references. Pairs above a threshold are suggested, and a reviewer accepts or rejects each one. ### Is it better to connect bank APIs than to import statements? Bank feeds are convenient where available, but many firms and auditors work from exported statements for a fixed period. A file import path is usually needed either way, so build it first. ## Next step If your team still reconciles by sorting two spreadsheets side by side, I can help you automate the routine part. See my [accounting and compliance](/industries/accounting-compliance) work and [get in touch](/#contact) with a sample of your files. --- # Next.js SaaS Development: Architecture That Holds Up URL: https://webdevang.com/blog/nextjs-saas-development · Category: CRM & SaaS development · Updated: 2026-11-03 Starting a SaaS on Next.js is easy. Keeping it pleasant to work on after two years, a few hundred customers and a dozen integrations is the real test. Most nextjs saas development guides stop at authentication and a pricing page. The decisions that actually hurt later are about tenancy, entitlements, background work and where long-running code lives. I am a core engineer on Antoc AI, a real-estate CRM used by 100+ firms in India, and I have built several other SaaS products solo. This post lays out the architecture choices I now make by default, and why. ## TL;DR Use Next.js for the product UI and public pages. Put websockets, webhooks, cron and heavy jobs in a separate Node/Express service once the product needs them. Model organizations and memberships first, scope every query on the server, and centralize plan-based feature checks. Treat realtime, scheduled jobs and Sentry-style monitoring as day-one infrastructure. ## Key takeaways - Use Next.js for what it is great at, the product UI and marketing pages, and keep long-running work in a separate Node service when the product needs it. - Design the organization and membership model before the first feature, because every query will depend on it. - Plan-based feature locking belongs in one shared entitlement check used by both the API and the UI. - Realtime, scheduled jobs and error monitoring are core SaaS infrastructure, not extras to add after launch. ## Where Next.js ends and the backend begins Next.js can do a lot on its own: route handlers, server actions and server components that read data directly. For a small product, keeping everything in one app is a perfectly good choice. The [Next.js App Router docs](https://nextjs.org/docs/app) cover these primitives well. The trouble starts when the product grows workloads that do not fit request-response: | Workload | Fits inside Next.js? | Why | |---|---|---| | Product UI, dashboards, settings | Yes | This is what it is built for | | Public marketing and SEO pages | Yes | Server rendering and metadata | | Simple CRUD for one client | Yes | Route handlers or server actions | | Websocket connections | Usually no | Needs long-lived processes | | Inbound webhooks at volume (ads, WhatsApp, payments) | Often no | Retries, queues and idempotency are easier in a service | | Cron and drip campaigns | No | Needs a scheduler that is always running | | Mobile apps sharing the same API | Better separate | One versioned API for all clients | A CRM hits every row of that table. So for products like Antoc, the Next.js app is the web client and a Node/Express service owns the API, Socket.IO and background jobs. For Client Mitra, a smaller product, I used the same split because the mobile apps needed the same API. ## Organizations, memberships and switching The single most important schema decision in B2B SaaS is how users relate to organizations. Get it wrong, and adding "invite a teammate" or "manage two businesses" later becomes a migration. The model I use: 1. **User**: identity only (name, email, phone, auth methods). 2. **Organization**: the tenant, with plan, settings and billing. 3. **Membership**: user plus organization plus role, with permissions. 4. **Session**: carries the active organization ID. Every API handler resolves the active membership first, then scopes queries by `organizationId`. No handler trusts an organization ID sent in the request body. Switching organizations just changes the active membership in the session and refetches data on the client. Antoc supports multi-business organization switching this way: an owner running two agencies flips between them without logging out, and each business sees only its own leads, inventory and team. ## Plan-based feature locking Pricing tiers mean some features exist only on some plans. The naive approach scatters `if (plan === "pro")` checks through components. Within months, the UI hides a feature that the API still serves, or worse, the reverse. Instead, define entitlements once: ```js const PLAN_FEATURES = { starter: ["leads", "pipeline"], growth: ["leads", "pipeline", "whatsapp", "reports"], scale: ["leads", "pipeline", "whatsapp", "reports", "voiceAgent", "mcp"], }; ``` The API exposes a `can(org, feature)` check used by middleware on protected routes, and the client receives the same entitlement list to render lock states and upgrade prompts. Limits like seats or monthly messages live in the same place. When sales invents a new plan, you edit one object. ## Realtime, jobs and observability **Realtime.** CRM users expect a new lead or WhatsApp reply to appear without refreshing. Socket.IO on the Node service, with rooms per organization, handles this. Emit events after the database write succeeds, and let clients refetch through their query cache rather than trusting payloads blindly. **Scheduled work.** Reminders, nurture drips, report emails and sync jobs need a scheduler that is always running. On a VM, a PM2-managed worker process with cron-style schedules is simple and reliable. Make every job idempotent so a restart mid-run does not double-send. **Observability.** Install error monitoring before launch. Sentry on both the Next.js client and the Node API shows you which customer hit which error, with the release that introduced it. Without it, you learn about bugs from angry WhatsApp messages. ### Deployment that you understand For Antoc, the services run on GCP VMs in asia-south1, close to Indian users, managed by PM2 behind Nginx. That setup is boring, cheap and easy to debug at 2 a.m. Managed platforms are great for a first version, but once you have websockets and workers, a VM or container host is often the more honest fit. ## How I built this in practice On [the Antoc case study](/work/antoc) I describe the product I work on as a core engineer and top committer on the web client. The stack is Next.js and React on the front end, Node/Express with MongoDB and Mongoose behind it, Socket.IO for realtime, Sentry for errors, and GCP VMs with PM2 and Nginx. The architecture above is what lets one codebase carry lead capture from Meta lead ads, Google Ads, portals, Sheets and webhooks, a WhatsApp flow builder with drips, an AI voice calling agent, a remote MCP server with OAuth, inventory with public share links, attendance and field team tools. Plan-based feature locking and multi-business organization switching sit in shared layers, so new modules inherit them instead of reimplementing them. Several of these, like webhooks and drips, would have been painful inside a request-response-only app. ## Common mistakes - Putting websockets, cron and webhook processing inside serverless request handlers that time out or scale to zero. - Accepting an organization ID from the client instead of resolving it from the session on the server. - Scattering plan checks through components instead of one entitlement map shared by API and UI. - Emitting realtime events before the database write has committed. - Writing background jobs that are not idempotent, so a restart double-sends messages. - Launching without error monitoring and release tracking. ## Internal links - [Custom CRM and SaaS development services](/services/custom-crm-development) - [Antoc AI case study: Next.js real-estate CRM](/work/antoc) - [Hire a full stack developer for UK teams](/hire/full-stack-developer-uk) - [CRM data migration from spreadsheets](/blog/crm-data-migration) - [Razorpay subscription integration for SaaS billing](/blog/razorpay-subscription-integration) - [Scaling a CRM database to 300K leads](/blog/scaling-crm-database) - [Custom CRM development cost](/blog/custom-crm-development-cost) ## FAQ ### Is Next.js a good choice for SaaS development? Yes, for most B2B SaaS products. It gives you a fast React UI, routing, server rendering for public pages and a large hiring pool. Pair it with a dedicated backend when you need websockets, queues or heavy background work. ### Should I use Next.js API routes or a separate backend? API routes and server actions are fine for simple CRUD and small products. Once you have websockets, long-running jobs, webhooks from many providers or multiple clients like mobile apps, a separate Node service is easier to scale and reason about. ### How do you handle multiple organizations per user in a SaaS? Model users, organizations and memberships separately, store the active organization in the session, and scope every query by it on the server. An organization switcher then only changes the active membership. ### Where should a Next.js SaaS be hosted? Managed platforms are quickest to start. For products with websockets, workers and predictable traffic, a VM with PM2 and Nginx or a container platform often costs less and gives more control. ## Next step If you are planning a SaaS on Next.js or untangling one that has outgrown its first architecture, I can help. Read about my [custom CRM and SaaS development](/services/custom-crm-development) work and [get in touch](/#contact) with where you are today. --- # CRM Data Migration: Leaving Spreadsheets Without Losing Leads URL: https://webdevang.com/blog/crm-data-migration · Category: CRM & SaaS development · Updated: 2026-11-03 Most sales teams do not start with a CRM. They start with a Google Sheet, then five sheets, then a sheet per salesperson and a WhatsApp group where leads get forwarded. When they finally switch, the biggest fear is simple: what if we lose leads in the move? A careful CRM data migration makes sure that does not happen. As a core engineer on Antoc AI, a real-estate CRM used by 100+ firms in India with around 300K leads managed, I have seen a lot of teams make this switch. This post is the plan I recommend, with the specific checks that prevent lost and duplicated leads. ## TL;DR Inventory every lead source, agree on a field map, and normalize phone numbers before importing. Run each import as a dry run that reports new, duplicate and rejected rows. Tag every record with an import batch ID and the original row. Plan the cutover so new leads from ads and portals start flowing into the CRM the same day the spreadsheets freeze. ## Key takeaways - Phone numbers are the real identity key for most Indian sales teams, so normalize them before anything else. - Run every import as a dry run first and review the report of new, duplicate and rejected rows before writing data. - Keep the original source row and an import batch ID on every record so any import can be traced or rolled back. - The cutover moment matters as much as the data, because leads that arrive during the switch are the ones most often lost. ## Step 1: Audit where leads actually live Teams almost always underestimate how many places leads live. Before touching any data, list every source and who owns it. | Source | Typical shape | Common problems | |---|---|---| | Master Google Sheet | One row per lead, many columns | Columns added ad hoc, merged cells, colors meaning status | | Per-salesperson sheets | Copies of master with notes | Same lead in several sheets with different statuses | | Meta lead ads exports | CSV per form | Different question columns per form | | Property portal leads | Emails or portal dashboards | Not exported anywhere | | Old CRM or software | CSV export | Custom fields, IDs that mean nothing outside | | WhatsApp and call logs | Unstructured | Usually only partially recoverable | Agree on which sources get migrated, which get archived as files, and which you will simply stop using. Not every historical scrap is worth importing. ## Step 2: Map fields and normalize values Next, build a field map from each source column to a CRM field. Keep it in a shared sheet so the sales head can sign off. The fields that need the most care: - **Phone**: strip spaces, dashes and brackets, remove leading zeros, add the country code (`+91` for India), and validate length. "98250 12345", "+91-9825012345" and "09825012345" must all become the same value. - **Name**: trim, fix casing, split into first and last only if the CRM requires it. - **Source**: map free text like "FB", "facebook", "Meta ad" to one controlled value. - **Status and stage**: map each team's informal labels ("hot", "callback", "visit done") onto your pipeline stages. This is the most debated step, and it should be. - **Owner**: map salesperson names to CRM user accounts. Unmapped owners go to a default queue, not to nobody. - **Dates**: parse created and last-contacted dates into one format, and keep them. Lead age matters for prioritization. Anything that does not map goes into a custom field or a note. Do not drop columns silently. ## Step 3: Deduplicate before you write Duplicate leads are worse than missing ones in the short term, because two salespeople end up calling the same buyer. Run deduplication in two passes. 1. **Within the import**: collapse rows with the same normalized phone or email. Keep the most recent status and merge notes. 2. **Against the CRM**: check each incoming lead against existing records. Choose a rule per migration: skip, merge (update empty fields only), or flag for review. This is the same logic a good CRM applies to live lead capture. In Antoc, duplicate detection runs on every incoming lead from ads, portals and forms, so the migration and the daily intake follow one set of rules. ## Step 4: Dry run, import, verify Never import straight into production on the first attempt. A dry run processes the file end to end without writing and produces a report: 1. Rows read 2. New leads that would be created 3. Duplicates found, and what would happen to each 4. Rejected rows with reasons (invalid phone, missing required field) 5. Leads per owner after assignment Review it with the sales head. Fix the source or the mapping, and run again until the report looks right. Then import for real, tagging every record with an `importBatchId` and storing the original row as JSON. If something goes wrong, you can find and delete exactly that batch. For large imports into MongoDB, batch writes with `bulkWrite` rather than inserting one document per request, and validate filters carefully on any bulk update. The [MongoDB bulkWrite documentation](https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/) explains ordered versus unordered behavior, which matters when some rows fail. After the import, spot-check: pick twenty random leads from the original sheets and find each one in the CRM with the right owner, stage and notes. ## Step 5: Plan the cutover The riskiest window is not the import. It is the day or two when leads keep arriving while the team is switching. To close that gap: - Connect live sources (Meta lead ads, Google Ads forms, portals, website forms, webhooks) to the CRM before the import, so new leads land there. - Freeze the old sheets on a fixed date and time, and make them read-only. - Run a final delta import of anything added to the sheets since the main import. - Keep a Google Sheets sync for vendors who insist on sending leads by sheet. The [Google Sheets API docs](https://developers.google.com/sheets/api/guides/concepts) cover reading new rows reliably. ## How I built this in practice In [the Antoc case study](/work/antoc) you can see the lead capture system this process plugs into. Antoc captures leads from Meta lead ads, Google Ads, property portals, Google Sheets, webhooks and public forms, with duplicate detection and auto-assignment rules, which means migrated leads and new leads go through the same pipeline. Behind it is MongoDB with Mongoose. As the platform grew past 300K leads, we hardened the database with proper indexes and safe bulk operations that validate filters before running, so a malformed bulk update cannot touch more records than intended. Auto-assignment rules mean that once migration is done, new leads route to the right salesperson without anyone forwarding them on WhatsApp. ## Common mistakes - Importing phone numbers as-is, so the same buyer appears three times in different formats. - Dropping columns that do not map neatly instead of preserving them as custom fields or notes. - Skipping the dry run and discovering mapping errors after thousands of records are written. - Importing without a batch ID, which makes a bad import nearly impossible to undo cleanly. - Leaving lead sources pointed at old sheets during the switch, so new leads fall through the gap. - Letting each salesperson keep a private sheet after go-live. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Antoc AI case study: real-estate CRM with lead capture](/work/antoc) - [CRM software for real estate teams](/industries/real-estate) - [Razorpay subscription integration for SaaS](/blog/razorpay-subscription-integration) - [Scaling a CRM database to 300K leads](/blog/scaling-crm-database) - [What custom CRM development costs](/blog/custom-crm-development-cost) - [Build vs buy a CRM](/blog/build-vs-buy-crm) ## FAQ ### How long does CRM data migration take? For a team with a few spreadsheets and tens of thousands of leads, the technical import usually takes days, not weeks. Most of the calendar time goes into agreeing on field mapping, cleaning rules and the cutover date. ### How do you avoid duplicate leads when migrating to a CRM? Normalize phone numbers and emails into a canonical format, then check each incoming row against existing records on those keys. Decide in advance whether duplicates are skipped, merged or flagged for review. ### Can I keep using Google Sheets after moving to a CRM? Yes, as a source. Many teams still collect leads into a sheet from forms or vendors. A sync that pulls new rows into the CRM keeps the sheet useful without making it the system of record. ### What should happen to old lead history and notes? Import the history as timeline notes or activities linked to each lead, with the original date preserved. Do not cram it into one long text field, because nobody can search or report on it later. ## Next step If your leads are spread across sheets and you want to move without losing any, I can plan and run the migration with you. See my [real estate CRM](/industries/real-estate) work and [get in touch](/#contact) to start. --- # Razorpay Subscription Integration for SaaS Billing URL: https://webdevang.com/blog/razorpay-subscription-integration · Category: CRM & SaaS development · Updated: 2026-11-03 Billing is the part of a SaaS that nobody wants to rebuild twice. If a customer pays and the app still shows them locked out, you get a support ticket at best and a lost customer at worst. A careful Razorpay subscription integration avoids that by treating payments as events, verifying everything and keeping one source of truth for what each customer has paid for. I integrated Razorpay subscriptions on the web for Client Mitra, a multi-tenant CRM for photography studios, alongside Apple in-app purchase on iOS. This post covers the architecture, the webhook handling and the iOS wrinkle most Indian SaaS founders hit late. ## TL;DR Create plans in Razorpay, start subscriptions from your server, and open checkout on the client. Verify the checkout signature, but treat webhooks as the source of truth. Store one internal subscription record per organization with a status, plan and period end, updated idempotently by every provider. If you ship on iOS, add Apple in-app purchase with server-side receipt verification. ## Key takeaways - Webhooks, not the checkout success callback, should be the source of truth for whether a subscription is active. - Keep one internal subscription record per organization that every payment provider updates, so the rest of the app never asks which provider was used. - Verify every signature and make webhook handlers idempotent, because Razorpay retries and events can arrive out of order. - If you ship an iOS app, plan Apple in-app purchase from the start, since App Store review will require it for digital subscriptions. ## How Razorpay subscriptions fit together Razorpay's subscription model has three objects worth understanding before you write code. The [Razorpay Subscriptions documentation](https://razorpay.com/docs/payments/subscriptions/) has the full reference. | Object | What it is | Where you create it | |---|---|---| | Plan | Price, currency, billing interval (monthly, yearly) | Once, in the dashboard or via API | | Subscription | A customer's instance of a plan with total cycles and start date | Your server, when the user clicks subscribe | | Payment | Each charge against the subscription | Razorpay, on each billing cycle | The flow in a typical SaaS looks like this: 1. User picks a plan on your pricing page. 2. Your server creates a Razorpay subscription for that plan and returns its ID. 3. The client opens Razorpay Checkout with the subscription ID. 4. The user authorizes the mandate or card payment. 5. Checkout returns `razorpay_payment_id`, `razorpay_subscription_id` and `razorpay_signature`. 6. Your server verifies the signature and marks the subscription as pending activation. 7. Razorpay sends webhooks as the subscription activates and renews, and your server updates status. Store the Razorpay subscription ID against the organization the moment you create it, before checkout opens. If the user closes the tab mid-payment, you still know which organization the later webhook belongs to. ## Webhooks are the source of truth The checkout success handler runs in the user's browser. Browsers close, networks drop, and users hit back. If your app only activates plans on that callback, some paying customers will stay locked out. Treat the callback as a fast path for good UX ("Payment received, activating...") and let webhooks make the real decision. ### Verify the signature on the raw body Razorpay signs webhook payloads with your webhook secret in the `X-Razorpay-Signature` header. Compute an HMAC SHA256 of the raw request body and compare. The key detail: use the raw body, not a re-serialized JSON object. In Express, that means capturing the raw buffer for the webhook route before the JSON parser touches it. ### Make handlers idempotent Razorpay retries webhooks that do not get a 2xx response, and events can arrive out of order. Store each processed event ID, and skip duplicates. When applying a status change, compare the event's timestamp or the subscription's current period against what you already have, so a late "charged" event never overrides a newer "cancelled". ### Events to handle Map provider events to your own statuses: - `subscription.activated` and `subscription.charged`: set status active, update `currentPeriodEnd`. - `subscription.pending`: payment retry in progress; keep access but show a banner. - `subscription.halted`: retries exhausted; restrict paid features. - `subscription.cancelled` and `subscription.completed`: set the end date and downgrade at period end. ## One internal subscription record The rest of your app should never call Razorpay to ask "is this customer paid?" It should read your own record: ```js { organizationId, plan: "pro", status: "active", // trialing | active | past_due | cancelled | expired provider: "razorpay", // or "apple" providerSubscriptionId, currentPeriodEnd, cancelAtPeriodEnd: false } ``` Feature checks, seat limits and the billing page all read this. When you add a second provider, only the code that writes this record changes. A nightly job that compares records against the provider is a cheap safety net for missed webhooks. ## The iOS problem: Apple in-app purchase Here is the part many teams discover at App Store review. If your iOS app sells digital subscriptions, Apple generally requires in-app purchase for that purchase inside the app. You cannot simply open Razorpay checkout in the iOS build. The practical setup is Razorpay on web and Android, Apple IAP on iOS, both writing the same internal subscription record. On the server, verify Apple transactions and process App Store Server Notifications rather than trusting the device. The [App Store Server API documentation](https://developer.apple.com/documentation/appstoreserverapi) covers transaction verification. ## How I built this in practice In [the Client Mitra case study](/work/clientmitra) I describe the full product I built solo. Subscriptions run through Razorpay on the web and Apple in-app purchase on iOS, with server-side receipt verification using `@apple/app-store-server-library`. App Store review required native Sign in with Apple, an IAP paywall and server verification before the iOS app was approved. The native Android and iOS apps are a single Flutter wrapper around the web app using flutter_inappwebview, which adds native sign-in, IAP, FCM push, local notifications and Crashlytics. The backend is Node/Express with MongoDB and Mongoose, JWT auth and tenant isolation in middleware, so subscription state is scoped per studio and roles control who can see billing. Earlier, on the X4ET B2B marketplace I built solo, Razorpay handled payments too, so the webhook and signature patterns here come from more than one production system. ## Common mistakes - Activating plans only in the browser success callback instead of on verified webhooks. - Verifying webhook signatures against parsed and re-serialized JSON rather than the raw body. - Processing the same webhook twice because event IDs are not stored. - Letting out-of-order events downgrade a customer who has already renewed. - Scattering provider-specific checks through the app instead of one internal subscription record. - Planning iOS billing after the app is built, then failing App Store review. ## Internal links - [Custom CRM and SaaS development services](/services/custom-crm-development) - [Client Mitra case study with Razorpay and Apple IAP](/work/clientmitra) - [Hire a full stack developer in India](/hire/full-stack-developer-india) - [Scaling a CRM database to 300K leads](/blog/scaling-crm-database) - [What custom CRM development costs](/blog/custom-crm-development-cost) - [Build vs buy a CRM](/blog/build-vs-buy-crm) - [Multi-tenant SaaS architecture](/blog/multi-tenant-saas-architecture) ## FAQ ### How long does a Razorpay subscription integration take? A clean integration with plans, checkout, webhooks, upgrade and cancel flows typically takes one to two weeks of development. Adding a second provider like Apple in-app purchase adds roughly another one to two weeks. ### Which Razorpay webhook events should a SaaS handle? At minimum handle subscription activated, charged, pending, halted, cancelled and completed. Map each event to a status change on your internal subscription record and ignore events you have already processed. ### Can I use Razorpay for subscriptions inside an iOS app? For digital subscriptions bought inside an iOS app, Apple generally requires in-app purchase. A common setup is Razorpay on the web and Android, Apple IAP on iOS, both updating one internal subscription record. ### How do I verify a Razorpay payment on the server? Compute an HMAC SHA256 of the payment and subscription IDs using your key secret and compare it with the signature returned by checkout. For webhooks, verify the X-Razorpay-Signature header against the raw request body using your webhook secret. ## Next step If you are adding subscriptions to a SaaS or preparing an app for App Store review, I can help you get billing right the first time. See my [custom CRM and SaaS development](/services/custom-crm-development) work and [get in touch](/#contact). --- # Scaling a CRM Database to 300K Leads URL: https://webdevang.com/blog/scaling-crm-database · Category: CRM & SaaS development · Updated: 2026-11-03 A CRM that feels instant at 5,000 leads can feel sluggish at 300,000. Lists take seconds to load, filters time out, and the team starts blaming "the server". Scaling CRM database performance at this size is rarely about bigger machines. It is about indexes that match how people actually query, pagination that does not degrade, and bulk operations that cannot go wrong. I am a core engineer on Antoc AI, a real-estate CRM used by 100+ firms in India, which grew past roughly 300K leads managed. This post shares what we changed in MongoDB as that happened, and the order I would tackle things in again. ## TL;DR Find the real query shapes your screens send, then build compound indexes that start with the tenant key, followed by equality filters and the sort field. Replace deep skip pagination with range-based paging. Wrap bulk updates in code that validates filters and caps counts. Lock down the database with authentication, network restrictions and least-privilege users. ## Key takeaways - At a few hundred thousand records, slowness almost always comes from missing or misordered compound indexes, not from the database being too small. - Every compound index in a multi-tenant CRM should start with the tenant key, followed by equality filters, then the sort field. - Bulk updates and deletes need filter validation in code, because an empty or wrong filter can touch every document. - Authentication, network restrictions and least-privilege database users are part of scaling, since more data means more at stake. ## Start with query shapes, not guesses Before adding any index, collect the queries your app actually sends. In a CRM, a handful of screens generate most of the load: | Screen | Typical filter | Typical sort | |---|---|---| | Lead list | business, stage, assigned user, source, date range | created date, newest first | | My leads (salesperson) | business, assigned user, stage | next follow-up date | | Duplicate check on intake | business, normalized phone | none | | Pipeline board | business, stage | updated date | | Reports | business, date range, grouped by source or user | none | Turn on the MongoDB profiler for slow operations, or check slow query logs, and run `explain("executionStats")` on the worst offenders. Two numbers matter: `totalDocsExamined` versus `nReturned`. If the database examines 200,000 documents to return 25, you need an index. ## Index design for a multi-tenant CRM ### Tenant key first, always In a multi-tenant CRM every query is scoped to a business. So every compound index starts with `businessId`. An index on `{ stage: 1, createdAt: -1 }` without the tenant key forces the database to sift through other businesses' leads. ### Equality, sort, range The ordering rule that fixes most slow lists: equality fields first, then the sort field, then range fields. The [MongoDB ESR guideline](https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-guideline/) explains it in detail. For the "my leads" screen, that gives: ```js leadSchema.index({ businessId: 1, assignedTo: 1, stage: 1, nextFollowUpAt: 1 }); ``` For duplicate checks on intake, a tight index on `{ businessId: 1, phone: 1 }` turns every new lead's lookup into a near-instant probe, which matters when ads and portals push leads in bursts. ### Do not index everything Each index costs write time and memory. A lead collection with twenty single-field indexes is slower to write and still slow to read, because single-field indexes rarely serve multi-filter queries well. Prefer a few compound indexes designed around your top screens, and drop indexes the `$indexStats` output shows are never used. ## Pagination and heavy queries ### Replace deep skip with range paging `skip(50000).limit(25)` makes the database walk 50,000 entries before returning anything. Page 1 is fast, page 2,000 is not. For infinite scroll and "next page" lists, use range-based pagination: remember the last item's sort value and `_id`, and query for items after it. Response time stays flat however deep the user scrolls. ### Count less Exact counts across hundreds of thousands of filtered documents are expensive. Show counts where they matter (pipeline totals, report figures) and avoid recomputing them on every list request. Cache or compute them on a schedule if they appear on busy screens. ### Project only what you render Lead documents grow: notes, custom fields, activity references. A list view needs maybe ten fields. Use projections so the database and network do not ship whole documents for a table row. ## Safe bulk operations As the dataset grows, so does the blast radius of a single bad command. Reassigning a salesperson's leads, bulk-changing stages or cleaning imported data all use `updateMany` or `bulkWrite`. A filter that accidentally comes through as `{}` updates every lead in every business. A safety wrapper prevents that: 1. Reject empty filters outright. 2. Require the tenant key (`businessId`) in every filter. 3. Count matching documents first and refuse if the count exceeds an expected cap. 4. Log who ran the operation, the filter and the affected count. 5. For deletes, prefer soft deletes with a timestamp so mistakes are recoverable. This sounds bureaucratic until the day it stops a script from rewriting the wrong data. ## Hardening access as data grows More data means more at stake. Alongside performance work, tighten access: - Require authentication on the database, with separate users for the app, background workers and admin tasks. - Give each user only the roles it needs. The app does not need to drop collections. - Restrict network access so only your application servers can reach the database port. - Keep connection strings in environment configuration, never in the repo. ## How I built this in practice [The Antoc case study](/work/antoc) covers the product: a real-estate CRM with lead capture from Meta lead ads, Google Ads, property portals, Google Sheets, webhooks and public forms, plus WhatsApp automation, an AI voice agent and an MCP server. All of that writes into MongoDB through Mongoose, from Node/Express services on GCP VMs. As leads grew past 300K, we scaled and hardened the database: indexes built around real query shapes, safe bulk operations with filter validation, and authentication plus network restrictions on the database itself. Duplicate detection and auto-assignment on intake depend directly on those indexes, because every incoming lead triggers lookups before it is saved. ## Common mistakes - Adding single-field indexes on every filterable field instead of a few compound indexes for real screens. - Leaving the tenant key out of compound indexes in a multi-tenant collection. - Using deep `skip` pagination on large lists. - Running exact counts on every list request. - Allowing `updateMany` or `deleteMany` with unvalidated filters from admin tools or scripts. - Treating database authentication and network restrictions as optional once traffic grows. ## Internal links - [Custom CRM development services](/services/custom-crm-development) - [Antoc AI case study: 300K leads on MongoDB](/work/antoc) - [Hire a full stack developer for Dubai and UAE teams](/hire/full-stack-developer-dubai) - [What custom CRM development costs](/blog/custom-crm-development-cost) - [Build vs buy a CRM](/blog/build-vs-buy-crm) - [Multi-tenant SaaS architecture](/blog/multi-tenant-saas-architecture) - [Real estate CRM development](/blog/real-estate-crm-development) ## FAQ ### Is 300K leads a lot for MongoDB? No. MongoDB handles collections far larger than that comfortably. At this size, performance problems usually come from query patterns and indexes rather than raw volume. ### How do I find slow queries in a CRM database? Enable the database profiler or slow query log, then run explain on the worst offenders. Look for collection scans and for queries that examine far more documents than they return. ### Should I switch from MongoDB to PostgreSQL as my CRM grows? Usually not for performance alone. Both scale well for CRM workloads. Switch only if your data has become heavily relational or you need features the current database lacks, because migrations are expensive. ### What is the safest way to run bulk updates on production data? Validate that the filter is non-empty and scoped to a tenant, count matching documents first, cap the expected count, and log the operation. Test the exact filter on a staging copy before running it in production. ## Next step If your CRM is slowing down as data grows, I can audit your queries and indexes and fix the worst offenders first. See my [custom CRM development](/services/custom-crm-development) work and [get in touch](/#contact). --- # WhatsApp Automation for Business: A Developer Guide URL: https://webdevang.com/blog/whatsapp-automation-for-business · Category: AI agents & automation · Updated: 2026-11-03 For many businesses in India, the UAE and beyond, WhatsApp is where customers actually reply. Email gets ignored, calls go unanswered, but a WhatsApp message gets read. That makes WhatsApp automation for business one of the highest-return things a sales or service team can build, as long as it is designed around real events and stops when a human should take over. I built WhatsApp automation into Antoc AI, a real-estate CRM used by 100+ firms in India, including a visual flow builder, nurture drips and an AI agent node. This guide covers how to design that kind of system from a developer's point of view. ## TL;DR Trigger automations from business events: incoming messages, new leads, reminders and pipeline stage changes. Store flows as nodes and edges so teams can edit them visually. Build drips (Day 0, 2, 7) that stop the moment someone replies or changes stage. Add an AI agent node for answering and qualifying, with explicit handoff. Keep every message and outcome synced to the CRM. ## Key takeaways - Good WhatsApp automation starts from business events like a new lead or a stage change, not from a list of messages to blast. - A visual flow builder stored as nodes and edges lets non-developers change journeys without a code release. - Drips must stop the moment a person replies or moves stage, or automation starts working against your sales team. - An AI agent node is most useful for answering and qualifying, with clear handoff to a human for anything uncertain. ## Start from triggers, not messages The common mistake is to start with "what messages should we send?" Start instead with "what happens in the business that deserves a response?" In a CRM, four triggers cover most needs: | Trigger | Example | Typical automation | |---|---|---| | Incoming message | Lead replies "price?" | Route to AI agent or assigned salesperson, tag the lead | | New lead | Lead arrives from a Meta ad or property portal | Instant welcome with brochure, start nurture drip | | Reminder | Site visit tomorrow at 11 | Confirmation message with location, then a morning reminder | | Pipeline stage | Lead moved to "visit done" | Feedback request, then next-step offer after two days | Each trigger carries context: the lead, the business, the assigned user, the source. Your flows can then personalize messages and branch on real data, which generic broadcast tools cannot do. ## Designing a visual flow builder Hard-coding journeys means every change goes through a developer. A visual flow builder lets an ops head adjust timing or wording themselves. ### Store flows as a graph Represent a flow as nodes and edges, the same shape libraries like React Flow use on the front end: - **Trigger node**: one per flow, defines the event and filters (for example, new lead where source is Meta ads). - **Message node**: sends a template or session message with variables like `{{lead.name}}` or `{{project.name}}`. - **Wait node**: pauses for a duration or until a time of day. - **Condition node**: branches on lead fields, reply content or stage. - **Action node**: updates the CRM, such as assigning, tagging or changing stage. - **AI agent node**: hands the conversation to an LLM with tools and a goal. Save the graph as JSON with a version number. When a lead enters a flow, store a run record with the flow version and the current node. Editing the flow then affects new runs, not leads halfway through. ### Execute runs reliably A scheduler wakes up due runs (wait nodes that have expired), executes the next node and records the result. Make each step idempotent so a retry after a crash does not send the same message twice. Log every step against the lead's timeline so salespeople can see exactly what the automation said. ## Drips that know when to stop A nurture drip is a timed sequence: Day 0 welcome and brochure, Day 2 a relevant project or offer, Day 7 a check-in asking if they would like a call or visit. Done well, it keeps cold leads warm without effort. Done badly, it keeps messaging someone who already booked a visit. Exit rules are what separate the two: 1. Stop when the lead replies, and route the reply to a human or the AI agent. 2. Stop when the lead changes pipeline stage. 3. Stop when the lead is marked lost or opted out. 4. Respect quiet hours, and never send at 2 a.m. local time. 5. Cap the number of automated messages per lead per week across all flows. Business-initiated messages outside the customer service window need pre-approved templates, so design drip content as templates from the start. Meta's [WhatsApp Business Platform documentation](https://developers.facebook.com/docs/whatsapp) covers templates, opt-in and messaging windows. ## Adding an AI agent node Once the basics work, an AI agent node can handle the first response to inbound questions: price ranges, availability, location, amenities. Give it a narrow job and the right tools: - **Context**: the lead's record, the project or product details, and recent messages. - **Tools**: look up inventory, book a site visit slot, update lead fields, request human handoff. - **Guardrails**: only answer from provided data, never promise discounts, hand off on anything uncertain or sensitive. The AI should write results back to the CRM, for example tagging budget and preferred location, so the salesperson starts the conversation already informed. ## How I built this in practice In [the Antoc case study](/work/antoc) you can see the WhatsApp automation module I worked on. It includes a visual flow builder with triggers for incoming messages, new leads, reminders and pipeline stages, Day 0/2/7 nurture drips, and an AI agent node. Leads arrive from Meta lead ads, Google Ads, property portals, Sheets, webhooks and forms, get deduplicated and auto-assigned, then enter the right flow automatically. The stack is Next.js and React for the builder UI, Node/Express workers for execution, MongoDB with Mongoose for flows, runs and timelines, and Socket.IO so new replies appear instantly for salespeople. I also built an Instagram DM automation tool on the official Instagram API using the same pattern: Next.js, Mongoose, reactflow-based flows, Gemini for AI replies and cron for scheduled steps. ## Common mistakes - Designing automation as broadcasts instead of event-driven flows tied to CRM data. - Hard-coding journeys so every wording or timing change needs a developer. - Editing a live flow in place so leads halfway through jump to the wrong step. - Letting drips continue after a reply or a stage change. - Giving an AI agent open-ended freedom without tools, data limits or a handoff path. - Not logging automated messages on the lead timeline, leaving salespeople blind. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI case study: WhatsApp flow builder and AI agent](/work/antoc) - [Hire a full stack developer for Dubai and UAE businesses](/hire/full-stack-developer-dubai) - [AI voice agent development](/blog/ai-voice-agent-development) - [MCP server development](/blog/mcp-server-development) - [WhatsApp Business API integration](/blog/whatsapp-business-api-integration) - [AI CRM integration](/blog/ai-crm-integration) ## FAQ ### Is WhatsApp automation allowed for businesses? Yes, through the official WhatsApp Business Platform. You need user opt-in, approved message templates for business-initiated messages, and you must follow Meta's commerce and messaging policies. ### What can be automated on WhatsApp for a sales team? Instant replies to new leads, follow-up drips, reminders for site visits or appointments, stage-based messages, document sharing and first-line question answering by an AI agent. Human handoff should stay one tap away. ### How much does custom WhatsApp automation cost to build? A focused set of fixed automations can take a few weeks. A full visual flow builder with multiple triggers, drips, an AI node and CRM sync is a larger project, often a few months, depending on scope. ### Should I build WhatsApp automation or use an off-the-shelf tool? Off-the-shelf tools are fine for simple broadcasts and chatbots. Build custom when automation must react to your own CRM data, like pipeline stages, assignments and inventory, in ways generic tools cannot see. ### Can an AI agent reply on WhatsApp on behalf of a business? Yes. An AI agent can answer questions from your own data and qualify leads within the customer service window. It should be scoped to known topics and hand off to a person when unsure. ## Next step If your customers live on WhatsApp and your follow-ups still depend on someone remembering, I can help you automate them properly. See my [AI agent development](/services/ai-agent-development) work and [get in touch](/#contact). --- # AI Voice Agent Development: What It Really Takes URL: https://webdevang.com/blog/ai-voice-agent-development · Category: AI agents & automation · Updated: 2026-11-03 Voice agent demos look magical. Then you put one on a real phone line with a real lead, and it pauses for three seconds, talks over the caller, or answers a question nobody asked. AI voice agent development is mostly the unglamorous work of closing that gap: latency, turn-taking, language and reliable actions. I built an AI voice calling agent for Antoc AI, a real-estate CRM used by 100+ firms in India. It is a Hinglish sales agent that calls leads, qualifies them and updates the CRM through tool calls. These are the field notes I wish I had at the start. ## TL;DR A voice agent is a pipeline: speech-to-text, an LLM with tools, and text-to-speech, wrapped in telephony and turn-taking. Use a voice platform for the plumbing. Spend your effort on latency (VAD tuning, prompt compression, streaming), natural language for your market, and tool calls that write outcomes to the CRM. Test on real calls, not demos. ## Key takeaways - Latency, not model intelligence, decides whether a voice agent feels human, so every stage of the pipeline needs a time budget. - Voice activity detection settings control interruptions and awkward pauses more than almost any other parameter. - Shorter prompts respond faster, so compress system prompts and pass only the context the current call needs. - A voice agent earns its keep through tool calls that update the CRM, not through the conversation alone. ## The anatomy of a voice agent Every voice agent, whatever the vendor, has the same moving parts: | Stage | Job | What can go wrong | |---|---|---| | Telephony | Place or receive the call, stream audio | Poor audio quality, dropped calls | | Voice activity detection (VAD) | Decide when the caller has finished speaking | Cuts callers off, or waits too long | | Speech-to-text (STT) | Turn audio into text | Mishears names, numbers, mixed languages | | LLM | Decide what to say and which tools to call | Slow first token, rambling, off-script | | Tools | Read and write business data | Wrong arguments, slow APIs | | Text-to-speech (TTS) | Speak the reply | Robotic tone, wrong pronunciation | A voice platform typically handles telephony, audio streaming and orchestration, and lets you plug in STT, LLM and TTS providers. That is the right call for most teams. Building the realtime audio plumbing yourself is months of work that does not differentiate your product. ## Latency is the product On a phone call, silence feels broken. Humans expect a response within about a second. Your pipeline has to fit VAD, STT, LLM thinking, tool calls and TTS into that window, which means every stage needs a budget. ### Tune VAD before anything else VAD decides when the caller is done. Set the silence threshold too short and the agent interrupts people mid-sentence, especially when they pause to think ("Haan, budget toh... around 80 lakh"). Set it too long and every turn starts with dead air. I spent a lot of time adjusting silence duration and sensitivity against real recordings until turn-taking felt natural for how people actually speak on sales calls. ### Compress the prompt The LLM's time to first token grows with prompt length. A long system prompt full of edge cases and examples is slow on every single turn. I rewrote the system prompt into a compact form: the persona, the goal of the call, strict style rules (short sentences, Hinglish, one question at a time), and tool descriptions. Lead-specific context like name, project interest and source goes in as a few short fields, not a dump of the full record. ### Stream everything Stream STT results, start the LLM as soon as the turn ends, and start TTS on the first sentence of the reply instead of waiting for the whole answer. Short replies help here too. A voice agent that answers in one or two sentences is faster and sounds more human than one that reads a paragraph. ### Keep tools fast If the agent calls a tool mid-conversation, that API call is on the critical path. Keep tool endpoints lean, index the lookups they make, and have the agent say a brief filler ("Ek second, check karta hoon") when a call might take longer. ## Language and persona for your market For Indian real estate leads, pure English or formal Hindi both sound wrong. People speak Hinglish, switching mid-sentence, with English words for numbers, property types and amenities. That affects every layer: 1. **STT** must handle code-switching. I used Sarvam's speech models, which are built for Indian languages. 2. **LLM** prompts must ask for natural, conversational Hinglish and show the register you want. 3. **TTS** must pronounce both Hindi and English words naturally, including project names and locality names. 4. **Numbers** need care: "80 lakh", "2 BHK", "possession 2027" must be understood and spoken correctly. ## Tools: where the value is A voice agent that chats nicely but changes nothing is an expensive voicemail. The value comes from actions. Give the LLM a small set of well-described tools, such as: - `update_lead`: set budget, preferred location, property type, timeline. - `set_stage`: move the lead to interested, not interested or call back. - `schedule_callback` or `book_site_visit`: create a follow-up with date and time. - `add_note`: write a short call summary to the lead timeline. Validate every argument on the server before writing, because LLMs occasionally send malformed values. The [Gemini function calling documentation](https://ai.google.dev/gemini-api/docs/function-calling) explains how to declare tools and handle calls. ## How I built this in practice In [the Antoc case study](/work/antoc) the voice agent sits alongside lead capture, WhatsApp automation and the MCP server. It is a Hinglish sales agent built with Sarvam for speech-to-text and text-to-speech and Gemini as the LLM, orchestrated through a voice platform. The heaviest work went into latency: tuning VAD so the agent neither interrupted nor lagged, and compressing prompts so responses started quickly. During calls the agent updates leads through tool calls, so qualification details and outcomes land in the CRM without anyone typing them. Those updates flow into the same pipeline, assignment rules and WhatsApp follow-ups the sales team already uses, which is what turns a call into a next step. ## Common mistakes - Judging a voice agent on demo calls instead of real leads with background noise and code-switching. - Leaving VAD on defaults, causing interruptions or long silences. - Using a long, example-heavy system prompt that slows every turn. - Waiting for the full LLM reply before starting text-to-speech. - Building a conversational agent with no tools, so nothing reaches the CRM. - Trusting tool arguments from the LLM without server-side validation. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI case study: Hinglish AI voice calling agent](/work/antoc) - [Hire a full stack and AI developer for US teams](/hire/full-stack-developer-usa) - [MCP server development](/blog/mcp-server-development) - [WhatsApp Business API integration](/blog/whatsapp-business-api-integration) - [AI CRM integration](/blog/ai-crm-integration) - [LLM integration services](/blog/llm-integration-services) ## FAQ ### How long does AI voice agent development take? A working prototype on a voice platform can take a couple of weeks. Getting it production ready, with tuned latency, reliable tool calls, CRM integration and testing across real calls, typically takes one to three months. ### Can an AI voice agent speak Hindi or Hinglish? Yes. Speech providers focused on Indian languages, such as Sarvam, offer speech-to-text and text-to-speech that handle Hindi and mixed Hinglish speech. Prompting the LLM to reply in natural Hinglish matters just as much. ### What latency is acceptable for a voice agent? In my experience, responses need to begin within roughly one to one and a half seconds after the caller stops speaking to feel natural. Beyond that, callers start repeating themselves or talking over the agent. ### Do I need a voice platform or can I build everything myself? A voice platform handles telephony, streaming audio and turn-taking, which saves months. Build your own logic, prompts and tools on top, and only go fully custom if you have unusual scale or control needs. ### How does a voice agent update my CRM? Through tool calls. The LLM is given functions like update_lead or book_site_visit, and when it calls them during the conversation, your backend validates the arguments and writes to the CRM. ## Next step If you want an AI agent that calls leads, qualifies them and updates your systems, I can help you build one that holds up on real calls. See my [AI agent development](/services/ai-agent-development) work and [get in touch](/#contact). --- # MCP Server Development: Letting Claude Work Your CRM URL: https://webdevang.com/blog/mcp-server-development · Category: AI agents & automation · Updated: 2026-11-03 MCP server development is the fastest way I know to make an existing business product usable from inside Claude. Instead of building a chatbot into your app, you expose a set of tools, and the assistant your team already uses can look up leads, summarize a pipeline or log a follow-up on their behalf. I built a remote MCP server with OAuth for Antoc, a real-estate CRM used by 100+ firms in India with roughly 300K leads under management. This post covers what I learned about designing the tools, securing them and keeping the model from doing something dumb with real customer data. ## TL;DR An MCP server wraps your product's capabilities as typed tools that Claude can discover and call. For a SaaS product, build a remote server, authenticate users with OAuth, and scope every tool to the caller's business and role. Keep the tool list short, write descriptions for the model, start read-only, and add write tools gradually with validation and logging. ## Key takeaways - MCP server development is mostly API design: a small set of well-named, well-described tools beats a mirror of your entire REST API. - A remote MCP server needs real OAuth so each user's assistant acts with that user's permissions, not a shared admin key. - Every write tool should validate inputs, scope to the caller's business, and return a short human-readable result the model can relay. - Start read-only, watch real usage, then add write tools one at a time with clear confirmations. ## What an MCP server actually does The [Model Context Protocol](https://modelcontextprotocol.io/introduction) defines how an AI client discovers and calls capabilities on a server. Your server advertises tools, each with a name, a description and a JSON schema for its arguments. The client shows those tools to the model, the model decides when to call one, and your server runs the real logic and returns a result. That makes the server a translation layer. It does not hold intelligence; it holds your business rules. The model handles intent ("which of my leads from last week haven't been called?"), and your server turns that into a scoped database query that respects permissions. ### Local vs remote There are two deployment shapes, and they serve different buyers. | Shape | Transport | Auth | Best for | |---|---|---|---| | Local | stdio, runs on the user's machine | Usually an API key in config | Developer tools, personal scripts | | Remote | HTTP, hosted by you | OAuth per user | SaaS products, non-technical teams | For a CRM used by sales managers, local is a non-starter. Nobody in a real-estate office is editing a JSON config file. A remote server lets them add a connector, sign in with their normal account, and start asking questions. ## Designing tools the model can use well The biggest mistake in MCP server development is exposing every endpoint you have. Models pick tools based on names and descriptions, and a list of 60 near-identical tools leads to wrong picks and wasted tokens. I design tools around jobs, not tables. A good starting set for a CRM looks like this: 1. `search_leads` — filter by stage, source, assignee, date range, with a hard limit on results. 2. `get_lead` — full detail for one lead, including recent activity. 3. `pipeline_summary` — counts by stage for a period, so the model does not page through thousands of rows to answer "how is this month going?" 4. `list_followups_due` — what needs attention today. 5. `add_note` — append a note to a lead. 6. `update_lead_stage` — move a lead to a named stage, validated against the business's pipeline. Notice what is missing: no generic `update_lead` that takes arbitrary fields, no delete. Narrow write tools are easier to reason about and easier to audit. ### Write descriptions for the model, not for humans A tool description is a prompt. I include when to use it, when not to, and what the arguments mean in business terms. For example, the stage tool's description lists that stage names are per business and tells the model to call `pipeline_summary` first if it does not know the valid stages. Return values matter too. Instead of dumping raw documents, return compact objects with the fields a person would care about, plus IDs for follow-up calls. Smaller payloads mean faster responses and fewer hallucinated details. ## Auth, tenancy and guardrails This is where a demo becomes a product. The MCP spec includes an [authorization flow based on OAuth](https://modelcontextprotocol.io/specification/draft/basic/authorization), and for a multi-tenant SaaS you want it. The flow I use: 1. The user adds the connector in Claude and is redirected to your login page. 2. They sign in with their existing credentials and approve access. 3. Your server issues a token tied to that user and their active business. 4. Every tool call resolves the token to a user, business and role before touching data. That last step is the important one. Antoc supports multi-business organization switching, so a single person can belong to several businesses. The token must carry which business is active, and every query must filter by it. I never accept a business ID as a tool argument from the model. ### Guardrails worth having on day one - **Permission parity**: if a staff member cannot see a report in the app, the MCP tool should not return it either. - **Plan checks**: Antoc has plan-based feature locking, so tools respect the same feature flags as the UI. - **Argument validation**: reject unknown stages, malformed dates and oversized limits before hitting the database. - **Audit logging**: record which user, through which client, called which tool with which arguments. - **Rate limits**: models can loop. Cap calls per user per minute. ## How I built this in practice Antoc's backend is Node/Express on MongoDB with Mongoose, running on GCP VMs in asia-south1 behind Nginx with PM2. I built the remote MCP server with the official MCP SDK so it shares models and business logic with the main API rather than duplicating them. The OAuth layer plugs into the existing account system, so users connect Claude with the same login they use for the web app. Because the database had already been hardened as leads grew past 300K, with proper indexes and safe bulk operations that validate filters, the MCP tools could run real queries without risking full-collection scans or unscoped updates. That groundwork mattered more than any prompt. A tool that accidentally runs an update without a business filter is a disaster whether a human or a model triggered it. The result is that a business owner can ask Claude about their pipeline, pull up a lead before a call, or log a note, and it all lands in the same CRM their team sees. You can read more about the wider product in [the Antoc case study](/work/antoc). ## Common mistakes - Mirroring the full REST API as tools, which confuses the model and bloats context. - Using one shared API key for every user, so the assistant sees data the user should not. - Letting the model pass tenant or business IDs as arguments instead of deriving them from the token. - Returning huge raw documents when a compact summary would answer the question. - Shipping write tools before observing how people actually use the read tools. - Skipping audit logs, then having no way to explain who changed a record and how. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI real-estate CRM case study](/work/antoc) - [Hire a full stack developer for UK teams](/hire/full-stack-developer-uk) - [WhatsApp Business API integration step by step](/blog/whatsapp-business-api-integration) - [AI CRM integration use cases that pay off](/blog/ai-crm-integration) - [LLM integration services for existing software](/blog/llm-integration-services) - [Building a Hinglish voice bot for sales teams](/blog/hinglish-voice-bot) ## FAQ ### What is an MCP server in plain terms? An MCP server is a small service that exposes your software's actions and data as tools an AI assistant like Claude can call. It follows the Model Context Protocol, so any compatible client can discover the tools, read their descriptions and call them with structured arguments. ### How long does MCP server development take for an existing product? If your product already has a clean API and auth system, a focused read-only MCP server can be built in one to two weeks. Adding OAuth, write tools, multi-tenant scoping and proper logging typically takes another two to four weeks depending on how many tools you need. ### Is it safe to let Claude write to my CRM? It can be, if the server enforces the same permissions as your app, validates every argument and scopes every query to the authenticated business. I also recommend starting read-only and adding write tools with narrow, explicit purposes rather than a generic update endpoint. ### Do I need a remote MCP server or a local one? Local servers suit developer tools that run on one machine. For a SaaS product where customers use Claude on the web or desktop, a remote MCP server with OAuth is the right choice because users connect with their own account and nothing has to be installed. ## Next step If you want your product usable from inside Claude without rebuilding it, I can scope the tool set, auth and rollout with you. See my [AI agent development services](/services/ai-agent-development) or [get in touch](/#contact) with a short description of your product and data. --- # WhatsApp Business API Integration, Step by Step URL: https://webdevang.com/blog/whatsapp-business-api-integration · Category: AI agents & automation · Updated: 2026-11-03 A WhatsApp Business API integration is one of the highest-return features you can add to a sales or service product, especially for customers in India, the UAE and much of the world where WhatsApp is the default inbox. It is also easy to get wrong: templates get rejected, webhooks drop messages, and conversations end up scattered. I have built WhatsApp automation for Antoc, a real-estate CRM used by 100+ firms, including a visual flow builder with triggers and nurture drips. Here is the step-by-step path I follow, in the order that avoids rework. ## TL;DR Get Meta business verification and a phone number on the Cloud API first. Design your message templates and opt-in capture before coding. Build a fast, idempotent webhook for inbound messages and status updates, store everything keyed by WhatsApp message ID, and respect the 24-hour service window. Automation and AI come after the plumbing is reliable. ## Key takeaways - A WhatsApp Business API integration has two halves: sending through the Cloud API and receiving through a verified webhook. - The 24-hour customer service window decides whether you can send free-form text or must use an approved template. - Store every message with its WhatsApp message ID and status so delivery, read receipts and retries are traceable. - Design templates and opt-in capture before you write code, because approval and consent shape everything downstream. ## Step 1: Accounts, numbers and tokens Everything starts in Meta's business tooling. The [WhatsApp Cloud API documentation](https://developers.facebook.com/docs/whatsapp/cloud-api) covers the details, but the checklist looks like this: 1. Create or use a Meta Business portfolio and complete business verification. 2. Create an app and add the WhatsApp product. 3. Register a phone number that is not active on the consumer WhatsApp app. 4. Create a system user and generate a permanent access token with WhatsApp permissions. 5. Note the phone number ID and WhatsApp Business Account ID; you will use both constantly. If your product is multi-tenant, decide now whether each customer brings their own number (embedded signup) or whether you send from a shared one. For a CRM, customers almost always want their own number and their own brand name in the chat. ## Step 2: Templates and the 24-hour window WhatsApp separates conversations into two modes. When a customer messages you, a 24-hour customer service window opens and you can reply with free-form messages. Outside that window, the business can only start a conversation with a pre-approved template. | Situation | What you can send | Notes | |---|---|---| | Customer messaged within 24h | Free text, media, interactive buttons | Window resets on each inbound message | | No recent inbound message | Approved template only | Utility, marketing or authentication category | | Login or OTP | Authentication template | Strict format rules | | Promotional follow-up | Marketing template | Requires opt-in, priced higher | Plan templates around real moments: new enquiry acknowledgement, site visit reminder, follow-up after a missed call. Use variables (`{{1}}`, `{{2}}`) for names and dates, keep wording specific, and avoid anything that reads like spam. Rejections usually come from vague content or a mismatched category. ## Step 3: The webhook Inbound messages, delivery statuses and read receipts arrive at a webhook you register with Meta. This is the part most worth engineering carefully. ### Verification and security Meta first sends a GET request with a `hub.challenge` that you echo back when the verify token matches. After that, every POST includes a signature header computed with your app secret. Verify it on every request before trusting the payload. ### Handler design - **Acknowledge fast.** Return 200 immediately and push the payload onto a queue or background job. - **Be idempotent.** Use the WhatsApp message ID (`wamid`) as a unique key. Retries and duplicate deliveries happen. - **Separate messages from statuses.** A status update (`sent`, `delivered`, `read`, `failed`) should update an existing outbound record, not create a new one. - **Handle every type.** Text, image, document, audio, location, button replies and list replies all arrive with different shapes. ## Step 4: Data model A clean schema saves you months later. The minimum I use: - `conversations`: business ID, contact phone, linked lead ID, last inbound timestamp (for the 24h window), assigned user. - `messages`: conversation ID, direction, `wamid`, type, body or media reference, template name if any, status, timestamps per status, error code if failed. - `templates`: name, language, category, approval status, variable mapping. Link conversations to leads by normalized phone number in E.164 format. In a CRM with duplicate detection, this is where WhatsApp contacts merge with leads that came from ads or portals instead of creating duplicates. ## How I built this in practice In Antoc, WhatsApp sits next to lead capture from Meta lead ads, Google Ads, property portals, Google Sheets, webhooks and public forms. When a new lead arrives, duplicate detection and auto-assignment rules run first, and then WhatsApp automation can fire. The automation runs on a visual flow builder. Flows start from triggers such as an incoming message, a new lead, a reminder or a pipeline stage change. A typical real-estate nurture flow sends an acknowledgement on Day 0, a follow-up with project details on Day 2 and a check-in on Day 7, each as an approved template because the customer may not have replied. There is also an AI agent node that can answer free-form questions inside the service window. The backend is Node/Express with MongoDB, with Socket.IO pushing new messages to the agent inbox in real time. Because the flows depend on reliable inbound events, the webhook handler is the most defended piece of the system. Read more in [the Antoc case study](/work/antoc). ## Common mistakes - Writing code before templates are approved, then discovering the flow needs a template category you do not have. - Processing webhooks synchronously, so slow database writes cause timeouts and retries. - Not deduplicating by `wamid`, which creates double replies and duplicate leads. - Ignoring the 24-hour window and getting send failures for free-form messages. - Storing phone numbers in mixed formats, which breaks matching between WhatsApp contacts and CRM leads. - Sending marketing templates without recorded opt-in, which damages the number's quality rating. ## Internal links - [AI agent and automation development services](/services/ai-agent-development) - [How Antoc runs WhatsApp automation for real-estate firms](/work/antoc) - [Hire a full stack developer in India](/hire/full-stack-developer-india) - [AI CRM integration use cases](/blog/ai-crm-integration) - [LLM integration services for existing software](/blog/llm-integration-services) - [Building a Hinglish voice bot](/blog/hinglish-voice-bot) - [Cutting voice agent latency](/blog/voice-agent-latency) ## FAQ ### How long does a WhatsApp Business API integration take? A basic send-and-receive integration with templates and a webhook can be done in one to two weeks once Meta business verification is in place. A full inbox with assignment, automation flows and analytics usually takes four to eight weeks. ### Do I need a Business Solution Provider to use the WhatsApp API? No. Meta's Cloud API lets you integrate directly using a Meta business account and a system user token. A provider can help with onboarding and support, but many teams integrate directly to avoid an extra layer and markup. ### Can I send marketing messages to anyone on WhatsApp? No. You need the user's opt-in and an approved marketing template for business-initiated messages. Sending without consent risks quality rating drops, messaging limits and account restrictions. ### What happens if my webhook goes down? Meta retries failed webhook deliveries for a period, but you should acknowledge fast, queue processing, and make handlers idempotent using the message ID. That way retries and duplicates never create duplicate leads or replies. ## Next step If you are adding WhatsApp to a CRM, booking system or support tool, I can help you plan templates, webhooks and automation so it works on day one. Take a look at my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact). --- # AI CRM Integration: Use Cases That Pay Off URL: https://webdevang.com/blog/ai-crm-integration · Category: AI agents & automation · Updated: 2026-11-03 Most AI CRM integration pitches promise a smarter pipeline in vague terms. The projects that actually pay off are narrow: they make first contact faster, stop leads from going cold, and remove data entry that nobody wants to do. I work as a core engineer on Antoc, a real-estate CRM used by 100+ firms in India with around 300K leads managed, where we have shipped WhatsApp AI agents, a Hinglish voice calling agent and an MCP server for Claude. This post ranks the use cases I would build first and what each one needs. ## TL;DR Start with the gap between a lead arriving and a human responding. AI that acknowledges, qualifies and reminds within minutes usually pays back first. Clean up duplicates and pipeline stages before adding models, and make sure every AI action writes back to the lead record. Add voice, assistants and analytics after the basics prove themselves. ## Key takeaways - The best AI CRM integration targets slow, repetitive first-touch work, not the parts your sales team already does well. - AI features are only as good as the CRM data underneath, so deduplication and clean stages come before any model. - Every AI action should write back to the lead record, or the team will not trust or even see it. - Ship one use case, measure response time and follow-up coverage, then expand. ## Use cases ranked by payoff Here is how I rank common AI features for a sales-led business, based on effort and how directly they affect conversions. | Use case | Effort | Data needed | Typical payoff | |---|---|---|---| | Instant AI reply on new leads (WhatsApp) | Medium | Lead source, project info, FAQs | High: closes the response-time gap | | Follow-up drafting and reminders | Low | Activity history, stages | High: fewer leads forgotten | | Lead qualification questions | Medium | Qualification criteria, budget fields | High for high-volume funnels | | Call and conversation summaries | Low | Call transcripts or chat logs | Medium: saves manager time | | AI voice calling agent | High | Scripts, telephony, CRM tools | High at scale, costly to get right | | Assistant access to CRM (MCP) | Medium | Clean API and permissions | Medium: great for owners and managers | | Predictive lead scoring | High | Lots of historical outcomes | Variable: needs clean outcome data | Predictive scoring is the feature everyone asks for first and the one I recommend last. Without thousands of leads with reliable won/lost outcomes, a model just learns noise. Conversational features work with far less history. ## Fix the data before adding a model AI amplifies whatever is in your CRM. If the same buyer exists three times because they filled a Meta form, called from a portal listing and messaged on WhatsApp, the AI will greet them three times. Before any AI work, I check: 1. **Duplicate detection** on normalized phone and email across every lead source. 2. **Consistent pipeline stages** per business, with clear meanings like "contacted", "site visit scheduled", "negotiation". 3. **Assignment rules** so every lead has an owner the AI can hand off to. 4. **Activity logging** for calls, messages and visits, so the model has context. 5. **Source tracking** to compare AI performance across channels. This groundwork is unglamorous, but it is the difference between an AI agent that helps and one that embarrasses you in front of customers. ## Patterns that make AI trustworthy ### Write back everything If an AI agent qualifies a lead on WhatsApp, the answers must appear as fields on the lead, and the conversation must be visible in the timeline. Salespeople ignore anything that lives in a separate tool. ### Use tool calls, not text parsing Modern models support function calling. Instead of asking a model to write "budget: 80 lakh" and then parsing it, give it a `update_lead` tool with typed fields. The [Gemini function calling guide](https://ai.google.dev/gemini-api/docs/function-calling) explains the mechanism; Claude and others work similarly. This makes updates structured and validated. ### Define the handoff Decide exactly when AI stops and a human takes over: a request for a site visit, a pricing negotiation, anger or confusion. Make that handoff an explicit tool that assigns the lead and notifies the owner. ## How I built this in practice At Antoc, the AI features sit on top of a lead-capture layer that pulls from Meta lead ads, Google Ads, property portals, Google Sheets, webhooks and public forms, with duplicate detection and auto-assignment rules. That foundation is what makes the AI layer safe to run. On top of it we built a WhatsApp flow builder with an AI agent node, a Hinglish voice calling agent using Sarvam speech models and Gemini that updates leads through tool calls, and a remote MCP server with OAuth so business owners can query and update CRM data from Claude. Plan-based feature locking controls which businesses get which AI features. The stack is Next.js and React on the front, Node/Express with MongoDB on the back, with the Anthropic SDK and Google Gemini for models. The full story is in [the Antoc case study](/work/antoc), and if you sell property, my [real-estate industry page](/industries/real-estate) goes deeper on that vertical. ## Common mistakes - Starting with predictive scoring before you have clean historical outcomes. - Running AI on duplicated, unassigned leads, so customers get repeated or orphaned messages. - Keeping AI conversations in a separate dashboard that sales never opens. - Parsing free text from model output instead of using structured tool calls. - No clear handoff rule, so the AI keeps talking when a human should step in. - Measuring "AI usage" instead of response time, follow-up coverage and site visits booked. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI CRM case study](/work/antoc) - [CRM and automation for real-estate businesses](/industries/real-estate) - [LLM integration services for existing software](/blog/llm-integration-services) - [Building a Hinglish voice bot for Indian sales teams](/blog/hinglish-voice-bot) - [Cutting voice agent latency](/blog/voice-agent-latency) - [WhatsApp chatbot development with an AI agent node](/blog/whatsapp-chatbot-development) ## FAQ ### What is the easiest AI CRM integration to start with? Summaries and drafting are the lowest-risk starting point: summarizing a lead's history before a call or drafting a follow-up message for a human to approve. They need no new channels and the human stays in control. ### Can I add AI to my existing CRM or do I need a new one? You can usually add AI to an existing CRM if it has an API or webhooks. The AI service reads lead data, calls a model, and writes results back. A rebuild only makes sense when the current CRM cannot expose data or accept updates. ### How much does AI CRM integration cost? A single focused feature such as AI follow-up drafting or WhatsApp auto-replies typically takes two to six weeks of development. Voice agents and multi-channel agents take longer. Ongoing model costs depend on volume and are usually small compared to the time saved. ### Will AI replace my sales team? No. In practice AI handles first contact, reminders and data entry, so salespeople spend more time on qualified conversations and site visits. The human still closes the deal. ## Next step If you have a CRM full of leads and not enough hands to follow up, I can help you pick the one AI use case that pays back first and build it properly. See my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact). --- # LLM Integration Services: Adding AI to Existing Software URL: https://webdevang.com/blog/llm-integration-services · Category: AI agents & automation · Updated: 2026-11-03 Buying LLM integration services should not mean buying a chatbot widget. It should mean someone who understands your existing software adds model-powered features that behave like the rest of the product: predictable inputs, validated outputs, error handling, monitoring and a cost you can forecast. I have integrated Anthropic's Claude, Google Gemini and Groq-hosted LLaMA into production systems, including a real-estate CRM with 100+ firms, a government tender classifier and an automated SEO content pipeline. This is the engineering approach I use when adding AI to software that already exists. ## TL;DR Put model calls behind a small AI service layer with a provider abstraction. Use structured outputs or tool calls so results come back as validated data. Choose models per task based on speed, cost and difficulty. Log everything, keep a small evaluation set, and roll features out behind flags so you can measure before committing. ## Key takeaways - Good LLM integration services treat the model as one dependency behind a thin service layer, not as code sprinkled across the app. - Structured outputs and tool calls turn unpredictable text into validated data your existing code can trust. - Pick models per task: a fast, cheap model for classification and a stronger one for reasoning-heavy work. - Log prompts, outputs, latency and cost from day one, and keep a small evaluation set to catch regressions. ## Where the AI layer should sit The most common mess I clean up is model calls scattered through route handlers, each with its own prompt string, retry logic and API key handling. It works for a demo and becomes painful the first time you change providers or need to debug a bad answer. I structure it as a dedicated module or service with three parts: 1. **Prompt and tool definitions** as versioned files, not inline strings. 2. **A provider adapter** with one interface (`generate`, `generateStructured`, `callWithTools`) and implementations per vendor. 3. **A feature layer** that knows business context: it fetches the lead, builds the input, calls the adapter, validates output and writes results back. This lets the CRM code call something like `ai.qualifyLead(leadId)` without knowing which model ran. When a better or cheaper model appears, you change the adapter config, run your evals and ship. ### Sync vs async Not every AI feature belongs in the request path. User-facing chat or voice needs streaming and low latency. Classification, summaries and enrichment usually run better as background jobs with queues or cron, which also lets you batch and retry. ## Getting reliable output Free-text output is fine for drafts a human will edit. Anything your code consumes should be structured. - **JSON schema output**: Most major APIs can constrain output to a schema. Validate it again on your side anyway. - **Tool calls**: For actions, define tools with typed parameters. The [Anthropic tool use docs](https://docs.anthropic.com/en/docs/build-with-claude/tool-use/overview) show the pattern: the model returns a tool call, your code executes it, and you send the result back. - **Enums over strings**: If a field has five valid values, make it an enum. Models stick to enums far better than to instructions in prose. - **Fallback paths**: When validation fails, retry once with the error message, then route to a human or a safe default. ## Choosing models per task One model for everything is either too slow, too expensive or not smart enough somewhere. I match the model to the job. | Task type | What matters | Model choice pattern | |---|---|---| | Classification and tagging | Throughput, cost | Fast, small model; strict enum output | | Extraction from documents | Accuracy on fields | Mid-tier model with schema output | | Conversational agents | Latency, tone, tool use | Fast model with good function calling | | Multi-step reasoning, agents | Planning quality | Stronger model, fewer calls | | Bulk content generation | Cost per token | Inexpensive hosted open models | In my own builds, the tender bot uses Gemini to classify scraped tenders by relevance, the SEO blog pipeline runs on Groq-hosted LLaMA for cheap high-volume drafting, and the CRM uses both the Anthropic SDK and Gemini depending on the feature. ## Cost, latency and monitoring LLM features fail quietly. The answer looks plausible, nobody notices it got worse, and the bill creeps up. Build visibility early. Track per call: feature name, model, input and output tokens, latency, success or validation failure. Aggregate by feature so you can see that, for example, lead summaries cost far more than classification and deserve prompt compression. Keep an evaluation set of 30 to 100 real inputs with expected outputs per feature. Run it whenever you change a prompt or model. It does not need to be fancy; a script that reports pass rate is enough to catch regressions before customers do. Error tracking matters too. Timeouts, rate limits and malformed responses should show up in the same tool as your other errors, with the feature and model attached. ## How I built this in practice On Antoc, AI touches several surfaces: an AI agent node inside the WhatsApp flow builder, a Hinglish voice calling agent that updates leads through tool calls, and a remote MCP server so Claude can act on a business's CRM data. All of them sit on the existing Node/Express and MongoDB backend rather than a separate system, so they share auth, tenancy and plan-based feature locking with the rest of the product. Errors go to Sentry alongside the rest of the app, and services run on GCP VMs with PM2 and Nginx. Because AI features read and write the same lead records as the UI, the sales team sees AI activity in the timeline they already use. More detail is in [the Antoc case study](/work/antoc). If you are hiring for this kind of work from Australia, my [Australia hiring page](/hire/full-stack-developer-australia) covers how I work across time zones. ## Common mistakes - Hardcoding one vendor's SDK across the codebase, making every model change a refactor. - Consuming free-text output in code without schema validation. - Running every feature on the most expensive model by default. - Putting slow AI calls in request paths that should be background jobs. - No logging of tokens or latency per feature, so cost spikes are a mystery. - Changing prompts in production without a regression set. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI CRM case study](/work/antoc) - [Hire a full stack developer for Australian teams](/hire/full-stack-developer-australia) - [Building a Hinglish voice bot](/blog/hinglish-voice-bot) - [Cutting voice agent latency](/blog/voice-agent-latency) - [WhatsApp chatbot development with an AI agent node](/blog/whatsapp-chatbot-development) - [AI lead qualification for first contact](/blog/ai-lead-qualification) ## FAQ ### What do LLM integration services include? Typically: picking use cases, designing where the AI layer sits in your architecture, prompt and tool design, structured output handling, provider selection, cost and latency controls, evaluation, and production monitoring. The goal is AI features that behave like the rest of your software. ### Which LLM should I use for my product? It depends on the task. High-volume classification and extraction often run well on fast, inexpensive models, while multi-step reasoning or agent work benefits from stronger models. I usually keep a provider abstraction so you can switch or mix models without rewriting features. ### How do I keep LLM costs under control? Use smaller models where they suffice, compress prompts, cache repeated context, cap output length, and batch background jobs. Logging tokens per feature shows exactly where money goes so you can optimize the expensive paths first. ### Is my data safe when integrating an LLM? Send only the fields a task needs, avoid passing secrets or unnecessary personal data, and review each provider's data retention terms. For regulated data, consider region-specific hosting and keep sensitive processing on your own infrastructure. ### Can you add AI to a legacy system without a rewrite? Usually yes. An AI service can sit beside the existing app, read data through its API or database, and write results back through the same channels. The legacy code barely changes. ## Next step If you have working software and want AI features that are reliable rather than flashy, I can map the right use cases and integrate them cleanly. Read about my [AI agent development services](/services/ai-agent-development) or [get in touch](/#contact). --- # Building a Hinglish Voice Bot for Indian Sales Teams URL: https://webdevang.com/blog/hinglish-voice-bot · Category: AI agents & automation · Updated: 2026-11-03 A Hinglish voice bot is not an English voice bot with a translated script. Indian buyers switch between Hindi and English mid-sentence, say budgets in lakh and crore, mention localities that no Western speech model has heard of, and hang up quickly on anything that sounds like a call center robot. I built a Hinglish AI sales calling agent for Antoc, a real-estate CRM used by 100+ firms in India. It runs on Sarvam speech-to-text and text-to-speech with Gemini for reasoning, connected through a voice platform, and updates leads through tool calls. Here is what mattered in making it sound like someone a buyer would actually talk to. ## TL;DR Use speech models built for Indian languages, write prompts and responses in natural Roman-script Hinglish, and explicitly handle numbers, dates and place names. Keep the call goal narrow, such as qualification and site visit booking. Wire the bot to the CRM with tool calls so every call ends with an updated lead, and work hard on response speed because silence kills calls. ## Key takeaways - A Hinglish voice bot must handle code-mixed speech in both directions, so pick speech models trained on Indian languages, not generic English ones. - Write prompts and replies in the register buyers actually use, with Roman-script Hindi and English terms like site visit, BHK and possession left as-is. - Numbers, budgets and dates in lakh and crore are where voice bots break most, so normalize them explicitly. - The bot is only useful if it updates the CRM through tool calls and hands hot leads to a human. ## The pipeline: ears, brain, voice Every voice agent has the same loop: speech-to-text (STT) turns audio into text, a language model decides what to say and which tools to call, and text-to-speech (TTS) turns the reply into audio. A voice platform handles telephony, turn-taking and streaming between them. For Hinglish, each piece has specific requirements. | Component | Hinglish requirement | What I used | |---|---|---| | Speech-to-text | Code-mixed recognition, Indian names and localities | Sarvam STT | | Language model | Follows Hinglish register, reliable tool calls, fast | Gemini | | Text-to-speech | Natural Indian voice that pronounces both languages | Sarvam TTS | | Orchestration | Streaming, interruption handling, voice activity detection | A voice agent platform | [Sarvam's documentation](https://docs.sarvam.ai/) covers their speech APIs. The key reason I chose Indian-language speech models is that generic English STT mangles words like "possession", "carpet area" spoken with a Gujarati or Hindi accent, and hears locality names as random English words. ## Writing for the ear in Hinglish ### Script and register I write prompts and example replies in Roman-script Hinglish, because that is how the model should "think" for this register, and the TTS reads it naturally. A line like "Aapne humare project ke baare mein enquiry ki thi, kya abhi do minute baat kar sakte hain?" lands far better than a formal Hindi or full English version. Real-estate terms stay in English because buyers say them in English: BHK, site visit, possession, carpet area, loan, booking amount. Translating them makes the bot sound strange. ### Short turns Voice replies need to be much shorter than chat replies. I keep each bot turn to one or two sentences and one question. Long explanations get interrupted, and the bot then has to recover mid-sentence. ### Mirror the caller If the buyer answers in mostly English, the bot should shift toward English. If they answer in Hindi, shift toward Hindi. I instruct the model to follow the caller's language mix rather than forcing a fixed one. ## Numbers, dates and names This is where Hinglish voice bots fail most visibly. A checklist I now follow: 1. **Normalize budgets**: "80 lakh", "point eight crore", "assi lakh" and "8000000" should all become one numeric value in the CRM. I handle this in the tool layer, not in the prompt. 2. **Speak numbers naturally**: The bot should say "pachaas lakh" or "fifty lakh", not "five zero zero zero zero zero zero". 3. **Relative dates**: "Kal", "parso", "is Sunday" must resolve against the current date in the right time zone before being saved as a site visit. 4. **Names and localities**: Pass the lead's name and the project's locality into the prompt so the model and TTS use correct spellings. 5. **Confirm critical values**: Repeat back budget and visit time once, briefly, before saving. ## Call design that respects the buyer The bot calls people who submitted an enquiry, often from a Meta lead ad or a property portal. It should be polite, clear about who it is, and quick. A typical flow: greet and confirm the enquiry, ask whether now is a good time, ask two or three qualification questions (budget, preferred location, timeline, configuration like 2 or 3 BHK), answer simple project questions from provided details, then offer a site visit or a callback from the sales team. If the buyer is busy, the bot schedules a callback rather than pushing. Escalation rules matter. If the buyer asks about price negotiation, legal details or sounds frustrated, the bot offers a human callback and flags the lead. ## How I built this in practice In Antoc, the voice agent is one channel alongside WhatsApp automation and the regular sales team. When a call ends, the agent has already called CRM tools to save qualification answers, update the pipeline stage and create a site visit or follow-up task. Because Antoc has duplicate detection and auto-assignment, the right salesperson sees the result immediately. The hardest engineering work was latency. Code-mixed speech, a reasoning model and a TTS step add up, and a two-second pause sounds broken on a phone call. I spent a lot of time on VAD tuning and prompt compression, which I cover in detail in the latency post linked below. The wider product is in [the Antoc case study](/work/antoc). ## Common mistakes - Using an English-only speech model and blaming the LLM for misunderstanding callers. - Writing the bot's lines in formal, textbook Hindi that no buyer actually speaks. - Letting the model parse budgets as free text instead of normalizing lakh and crore in code. - Long, chat-style replies that invite interruptions and confusion. - No escalation path, so the bot argues price with a serious buyer. - Calls that end without writing anything back to the CRM. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI CRM and voice agent case study](/work/antoc) - [Hire a full stack developer in India](/hire/full-stack-developer-india) - [Cutting voice agent latency with VAD and prompt work](/blog/voice-agent-latency) - [WhatsApp chatbot development with an AI agent node](/blog/whatsapp-chatbot-development) - [AI lead qualification for first contact](/blog/ai-lead-qualification) - [Web scraping with Playwright for business intelligence](/blog/web-scraping-playwright) ## FAQ ### What is a Hinglish voice bot? It is an AI calling agent that speaks and understands a natural mix of Hindi and English, the way many urban Indian buyers actually talk. It listens with speech-to-text, reasons with a language model and replies with text-to-speech in the same mixed register. ### Why not just use an English voice bot in India? Many buyers switch languages mid-sentence and respond better to a familiar register. Pure English or formal Hindi bots often sound robotic or foreign, and English-only speech recognition struggles with Hindi words, Indian names and local place names. ### What can a Hinglish sales voice bot do on a call? Typically it confirms interest, asks qualification questions like budget, location and timeline, answers basic project questions, books a site visit or callback and records outcomes in the CRM. Complex negotiation stays with a human. ### How long does it take to build a Hinglish voice bot? A working prototype on an existing voice platform can come together in a few weeks. Getting it to sound natural, respond quickly and update the CRM reliably usually takes several more weeks of testing with real call recordings and tuning. ## Next step If your sales team cannot call every enquiry fast enough, a Hinglish voice agent can handle first contact and qualification. Explore my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact) to talk through your call volume and goals. --- # Cutting Voice Agent Latency: VAD, Prompts, Streaming URL: https://webdevang.com/blog/voice-agent-latency · Category: AI agents & automation · Updated: 2026-11-03 Voice agent latency is the gap between a caller finishing a sentence and hearing the agent's reply. In chat, a two-second delay is fine. On a phone call, it sounds like the line dropped, and the caller says "hello?" right as the bot starts talking, which derails the whole turn. I spent a significant part of building Antoc's Hinglish sales calling agent on latency: VAD tuning, prompt compression and making every stage stream. This post is the method I use, stage by stage, with the trade-offs at each step. ## TL;DR Break the delay into stages and measure each: end-of-speech detection, speech-to-text finalization, LLM time to first token, TTS time to first audio, and network hops. Tune VAD endpointing carefully, cut the system prompt and tool list down hard, stream LLM output straight into TTS, and keep tool calls fast or move them off the critical path. ## Key takeaways - Voice agent latency is a sum of stages, so measure each one separately before optimizing anything. - VAD endpointing is often the largest hidden delay, and tuning it is a trade-off between speed and cutting callers off. - Shorter system prompts and fewer tool definitions directly reduce time to first token. - Stream everything: partial transcripts, LLM tokens and TTS audio, so the caller hears the first words while the rest is still being generated. ## Build a latency budget first You cannot fix what you do not measure. Before changing anything, I log timestamps for every stage of a turn across a batch of real test calls. A simple budget looks like this: | Stage | What happens | Main lever | |---|---|---| | End-of-speech detection | VAD decides the caller has stopped | Silence threshold, endpointing settings | | STT finalization | Final transcript is produced | Streaming STT, model choice | | LLM time to first token | Model starts responding | Prompt size, model, region | | LLM to first sentence | Enough text exists to speak | Short replies, sentence chunking | | TTS time to first audio | First audio bytes are ready | Streaming TTS, voice choice | | Network and telephony | Audio travels to the caller | Co-locating services | Plot these per turn. You will usually find one or two stages dominate. In my experience, the surprises are endpointing and prompt size, not the model's raw speed. ## Stage 1: VAD and endpointing Voice activity detection decides when the caller has finished speaking. Set the silence threshold too long and every turn starts with dead air. Set it too short and the agent jumps in while the caller is pausing mid-thought, which is worse. What I tune: 1. **Silence duration before end of turn.** Start conservative, then reduce in small steps while listening to real calls. 2. **Minimum speech length.** Ignore very short noises like coughs or "hmm" so they do not trigger a turn. 3. **Context-aware waiting.** After the agent asks for a phone number or budget, callers pause more while thinking, so a slightly longer wait there avoids cutting them off. 4. **Interruption handling.** When the caller starts talking during agent speech, stop TTS immediately and listen. Code-mixed Hinglish speech made this harder, because natural pauses differ when people switch languages or search for a word. There is no universal setting; you tune against recordings of your actual callers. ## Stage 2: Prompt compression Time to first token grows with input size. A voice agent prompt often starts as a long document: persona, rules, project details, objection handling, examples and a dozen tool schemas. Every turn pays for all of it. How I cut it down: - **Remove prose, keep rules.** Rewrite paragraphs as terse bullet rules. Models follow compact instructions well. - **Inject only relevant context.** Pass the specific project and lead details for this call, not the whole inventory. - **Trim tools.** Keep only the tools this call type needs, with short descriptions and minimal parameters. - **Summarize history.** On long calls, compress earlier turns rather than resending the full transcript. - **Use provider caching where available.** Stable prefixes can be cached by several providers; see the [Gemini context caching docs](https://ai.google.dev/gemini-api/docs/caching) for one approach. Prompt compression also tends to improve behavior. A shorter prompt has fewer contradictions for the model to trip over. ## Stage 3: Stream every stage The single biggest structural win is never waiting for a stage to finish completely. - **Streaming STT** sends partial transcripts, so the system can prepare while the final transcript arrives. - **Streaming LLM output** lets you cut the reply at the first sentence boundary and send that to TTS immediately. - **Streaming TTS** starts playing audio as soon as the first chunk is synthesized. Combined with short replies, this means the caller hears the start of the answer while the rest is still being generated. Instruct the model to put the most important words first, so even if the caller interrupts, the key point landed. ## Stage 4: Tool calls on the critical path A voice agent that updates a CRM calls tools mid-conversation. If saving a site visit takes a second on the backend, that second is added to the pause. My rules for tool calls in voice: - Make endpoints narrow and indexed. A tool that updates one lead by ID should be fast. - Defer non-critical writes. Logging a call note can happen after the turn or at the end of the call. - Avoid chained calls in one turn. Design tools so one call does the job. - Keep services close. Run the backend in the same region as the voice infrastructure when possible. ## How I built this in practice Antoc's voice agent is a Hinglish sales caller using Sarvam STT and TTS with Gemini, connected through a voice platform, and it updates leads through tool calls into a Node/Express and MongoDB backend running on GCP in asia-south1. The latency work was iterative: record test calls, read the per-stage timings, change one thing, repeat. VAD tuning and prompt compression gave the most noticeable improvements, because the early versions waited too long to decide a caller had finished and carried a heavy prompt into every turn. Keeping the CRM tools narrow, backed by an indexed database that had already been hardened as leads grew past 300K, meant tool calls did not become the new bottleneck. Read more in [the Antoc case study](/work/antoc), or see my [US hiring page](/hire/full-stack-developer-usa) if you are building a voice product from the States. ## Common mistakes - Optimizing the model choice before measuring where the delay actually is. - Using one VAD silence threshold for every question type. - Shipping a long, prose-heavy system prompt that every turn has to process. - Waiting for the full LLM response before starting text-to-speech. - Doing slow, chained backend writes inside the conversation turn. - Hosting STT, LLM, TTS and backend in different regions far from callers. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI voice agent case study](/work/antoc) - [Hire a full stack developer for US teams](/hire/full-stack-developer-usa) - [WhatsApp chatbot development with an AI agent node](/blog/whatsapp-chatbot-development) - [AI lead qualification for first contact](/blog/ai-lead-qualification) - [Web scraping with Playwright](/blog/web-scraping-playwright) - [Tender scraping automation bot](/blog/tender-scraping-automation) ## FAQ ### What is a good response time for an AI voice agent? Human conversation has very short gaps between turns, so the closer you get to about a second from the caller stopping to the agent speaking, the more natural it feels. Beyond roughly two seconds, callers start repeating themselves or assume the line dropped. ### What causes the most latency in voice bots? In my experience the usual culprits are conservative end-of-speech detection, large prompts that slow the first LLM token, waiting for a full LLM response before starting TTS, and slow tool calls to backend systems. Network distance between components adds up too. ### Does a faster LLM fix voice agent latency? It helps, but it is rarely the whole answer. If VAD waits too long or TTS only starts after the full reply is generated, a faster model still leaves noticeable pauses. Fix the pipeline first, then pick the model. ### How do you handle slow tool calls during a call? Make the backend endpoints fast and narrow, run non-critical writes after the turn, and let the agent say a short natural acknowledgment while a necessary lookup runs. Avoid chaining several tool calls inside one turn. ## Next step If your voice agent works but feels slow or awkward on real calls, I can profile the pipeline and fix the stages that matter. See my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact). --- # WhatsApp Chatbot Development With an AI Agent Node URL: https://webdevang.com/blog/whatsapp-chatbot-development · Category: AI agents & automation · Updated: 2026-11-03 WhatsApp chatbot development has split into two camps. One builds rigid menu bots ("Reply 1 for pricing") that frustrate anyone with a real question. The other plugs a language model straight into the inbox and hopes it behaves. Neither works well for a business that needs both reliability and natural conversation. On Antoc, a real-estate CRM used by 100+ firms, we built a visual WhatsApp flow builder where an AI agent is one node among many. Fixed steps stay fixed, and the AI only takes over where conversation is genuinely open-ended. This post explains how to design that kind of hybrid bot. ## TL;DR Model the chatbot as a flow of nodes triggered by events. Use deterministic nodes for messages, delays, conditions and CRM updates. Add an AI agent node with a narrow goal, scoped context, a few tools and explicit exit conditions. Store per-contact flow state, and always provide a human handoff. ## Key takeaways - The best approach to WhatsApp chatbot development is hybrid: fixed nodes for predictable steps and an AI agent node only where conversation is open-ended. - An AI node needs a narrow goal, scoped knowledge, a small set of tools and explicit exit conditions back into the flow. - Flow state must be stored per contact so delays, reminders and replies resume in the right place. - Business users should be able to edit flows visually without touching the AI configuration underneath. ## The building blocks of a flow A flow is a directed graph. It starts at a trigger and moves through nodes based on events and conditions. These are the node types I consider essential: | Node type | Purpose | Example | |---|---|---| | Trigger | Starts the flow | Incoming message, new lead, reminder, pipeline stage change | | Send message | Sends text, media or a template | Project brochure, greeting | | Wait / delay | Pauses for time or a reply | Wait 2 days, wait for reply up to 24h | | Condition | Branches on data | Lead source is Meta ads, budget above a value | | Buttons / list | Structured choices | "Book visit", "Talk to sales", "More details" | | CRM action | Updates the record | Change stage, assign owner, add tag | | AI agent | Handles open conversation | Answer questions, collect details | | Handoff | Routes to a human | Assign and pause automation | Triggers matter most because they decide when automation runs. A "new lead" trigger fires when a lead lands from any source. A "pipeline stage" trigger fires when sales moves a lead to, say, site visit done, which is a natural moment for a feedback message. ### Drips are just flows with delays A Day 0, Day 2, Day 7 nurture sequence is a chain of send and wait nodes, with a condition before each send that checks whether the lead has replied or progressed. If a salesperson has already moved the lead forward, the drip should stop rather than send an out-of-date nudge. ## Designing the AI agent node The AI node is where most teams overreach. A good one is configured like a tightly scoped employee, not a general assistant. Here is the checklist I use for every AI node: 1. **Goal**: one sentence, such as "Answer questions about this project and find out the buyer's budget and preferred configuration." 2. **Context**: only what it needs, like the project's details, pricing ranges the business is happy to share, and the lead's name and source. 3. **Tools**: a small set, for example `save_qualification`, `book_site_visit`, `request_human`. 4. **Exit conditions**: goal achieved, handoff requested, a set number of turns reached, or no reply within a time limit. 5. **Fallback**: what the flow does next on each exit path. 6. **Tone and language**: follow the customer's language mix and keep replies short, because WhatsApp is a chat app, not email. The exit conditions are what make the hybrid work. When the AI node finishes, the flow moves to the next node, which might be a CRM action, a delay or a handoff. The AI never wanders off and owns the conversation forever. ### Respect WhatsApp's rules inside the AI node The AI node can send free-form replies only within the 24-hour customer service window. If the customer goes quiet and the window closes, the flow must fall back to an approved template. I enforce this in the send layer so the model cannot accidentally break the rule. Meta's [messaging documentation](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-messages) covers the details. ## State, concurrency and handoff Every contact in a flow has state: current node, variables collected so far, when the next wait expires, and whether automation is paused. I store this per contact per flow, and a scheduler resumes waiting flows when delays expire. A few rules prevent chaos: - **One active flow per contact per trigger type**, so a contact does not receive two greetings from overlapping flows. - **Replies route to the waiting node**, not to a fresh flow start. - **Human takeover pauses automation** for that contact until the agent closes or releases the conversation. - **Idempotent sends**, so a retry never sends the same message twice. ## How I built this in practice In Antoc, the flow builder supports triggers on incoming messages, new leads, reminders and pipeline stage changes, with Day 0/2/7 nurture drips as a standard pattern and an AI agent node for open conversation. Flows run on top of the lead-capture layer, so a lead from a Meta ad or a property portal passes through duplicate detection and auto-assignment before any message goes out. The backend is Node/Express with MongoDB, with Socket.IO updating the shared inbox in real time when the bot or a human replies. The AI node uses the same model integrations as the rest of Antoc's AI features. A separate project, an Instagram DM automation tool on the official Instagram API, used the same idea of visual flows built with reactflow plus a Gemini step, which confirmed that the hybrid pattern carries across channels. Details are in [the Antoc case study](/work/antoc), and the [real-estate industry page](/industries/real-estate) shows how this fits a property sales process. ## Common mistakes - Building a pure menu bot that cannot handle any question outside the buttons. - Giving the AI node the entire knowledge base and no clear goal. - No exit conditions, so the AI keeps the conversation forever and the flow never continues. - Letting drips continue after a salesperson has already moved the lead forward. - Overlapping flows that send a contact multiple greetings at once. - No pause on human takeover, so the bot replies over a live salesperson. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI WhatsApp automation case study](/work/antoc) - [WhatsApp and CRM automation for real-estate](/industries/real-estate) - [AI lead qualification for first contact](/blog/ai-lead-qualification) - [Web scraping with Playwright](/blog/web-scraping-playwright) - [Building a government tender intelligence bot](/blog/tender-scraping-automation) - [Gemini vs Claude for business automation](/blog/gemini-vs-claude) ## FAQ ### Should my WhatsApp chatbot be fully AI or rule-based? For most businesses, neither alone. Rule-based flows are predictable for greetings, menus, reminders and drips, while an AI agent handles free-form questions. A hybrid gives control where it matters and flexibility where customers ask unexpected things. ### What does an AI agent node do in a WhatsApp flow? It hands the conversation to a language model with a specific goal, context and tools, such as answering project questions or collecting qualification details. When the goal is met or a handoff condition triggers, the node exits and the flow continues. ### How much does WhatsApp chatbot development cost? A simple flow-based bot on top of an existing WhatsApp integration can take a couple of weeks. A full visual flow builder with triggers, delays, AI nodes and CRM integration is a larger product feature that usually takes a few months. ### Can the chatbot hand over to a human agent? Yes, and it should. A handoff node or AI tool assigns the conversation to a team member, pauses automation for that contact and notifies the assignee, so the customer never gets bot replies while talking to a person. ## Next step If you want a WhatsApp chatbot that is predictable where it needs to be and smart where customers need it, I can design and build it with you. See my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact). --- # AI Lead Qualification: Automating First Contact URL: https://webdevang.com/blog/ai-lead-qualification · Category: AI agents & automation · Updated: 2026-11-03 Every sales team knows the pattern. A lead fills a form on a Meta ad at 9 pm, nobody calls until the next afternoon, and by then the buyer has spoken to three competitors. AI lead qualification fixes the gap between interest and first contact by having an agent reach out within minutes, ask the right questions and hand a sorted lead to a human. I have built this as part of Antoc, a real-estate CRM used by 100+ firms in India with around 300K leads managed, across both WhatsApp and a Hinglish voice calling agent. This is the playbook I follow when designing qualification for a sales team. ## TL;DR Define qualification criteria with your sales team as structured fields. Trigger first contact instantly when a lead arrives, over WhatsApp or voice depending on the source and intent. Have the AI ask three to five questions, save answers through tool calls, score with clear rules, and route hot leads to a salesperson with a next action. Measure contact speed and qualified-lead rate, not AI chat volume. ## Key takeaways - AI lead qualification works best when the criteria are defined by your sales team first, in plain fields like budget, timeline and location. - The channel matters: WhatsApp suits leads who prefer text, while a voice agent suits high-intent leads who expect a call. - Score with transparent rules on structured answers before reaching for a predictive model. - The output of qualification is a routed, prioritized lead with a next action, not just a label. ## Step 1: Define what "qualified" means Most qualification projects stall because nobody wrote down what a good lead looks like. Before building anything, I sit with the sales head and turn their instincts into fields. For a real-estate developer or broker, that usually means: | Field | Type | Why sales cares | |---|---|---| | Budget | Number (normalized from lakh/crore) | Matches lead to the right project or unit | | Preferred location | Enum or free text mapped to localities | Routes to the right project team | | Configuration | Enum (1/2/3 BHK, plot, commercial) | Filters inventory | | Timeline | Enum (immediate, 3 months, 6+ months, just exploring) | Sets urgency | | Purpose | Enum (self-use, investment) | Changes the pitch | | Site visit interest | Boolean plus preferred date | The real conversion step | Other industries swap these out. A B2B service might use company size, decision role and project start date. The principle stays the same: every field must change what the salesperson does next. If it does not, do not ask it. ## Step 2: Choose the channel per lead Not every lead should get the same first touch. I route by source and intent. - **WhatsApp first** for leads from ads and forms where the buyer may be at work or casually browsing. They can reply when convenient, and it feels low pressure. - **Voice first** for high-intent sources, such as a buyer who requested a callback or enquired on a specific unit. A short call confirms interest faster. - **Both, staggered**, for important leads that do not respond: a WhatsApp message first, then a voice call later if there is no reply. The [Meta lead ads documentation](https://developers.facebook.com/docs/marketing-api/guides/lead-ads) explains how to receive leads in real time through webhooks, which is what makes instant first contact possible for ad leads. ## Step 3: Design the conversation Whether by text or voice, first contact should feel like a helpful salesperson, not a survey. 1. Greet by name and reference what they enquired about. 2. Ask permission or check timing ("is now a good time?" on voice). 3. Ask the highest-value question first, usually budget or configuration. 4. Answer any question they ask before continuing, using project details provided to the agent. 5. Offer the next step: site visit, brochure or callback. 6. Close politely, and confirm what happens next. Each answer is saved through a tool call into the lead's structured fields as soon as it is given. If the conversation drops halfway, you still keep the answers you collected. ## Step 4: Score and route Once answers exist as fields, scoring is straightforward. I start with transparent rules that sales can read: - **Hot**: budget matches available inventory, timeline immediate or within 3 months, wants a site visit. - **Warm**: budget fits, timeline 3 to 6 months, or no visit yet. - **Nurture**: just exploring, long timeline or budget mismatch. - **Unreachable**: no response after the defined attempts. Hot leads get assigned immediately with a notification and a task, such as "call within 30 minutes" or "confirm site visit". Warm leads go to the regular queue. Nurture leads enter a WhatsApp drip. Rules like these are easy to adjust when sales says "we are getting too many hot leads that are not really hot". Predictive scoring can come later, once months of leads with won and lost outcomes exist. Until then, rules on clean answers beat a model guessing from sparse data. ## How I built this in practice In Antoc, leads arrive from Meta lead ads, Google Ads, property portals, Google Sheets, webhooks and public forms. Duplicate detection runs first so a returning buyer is not qualified twice, and auto-assignment rules decide ownership. From there, qualification can run through the WhatsApp flow builder, where an AI agent node collects details and Day 0/2/7 drips handle non-responders, or through the Hinglish voice calling agent, which updates the lead through tool calls during the call. Site-visit and call reporting then show managers what happened to qualified leads, closing the loop between first contact and actual visits. The full product is described in [the Antoc case study](/work/antoc), and my [real-estate industry page](/industries/real-estate) covers how this maps to property sales teams. ## Common mistakes - Letting the AI ask ten questions because "more data is better", which kills response rates. - Saving qualification answers as a chat transcript instead of structured fields. - Treating every lead source the same, regardless of intent. - Starting with a predictive scoring model before any outcome history exists. - Labeling leads hot without assigning an owner and a deadline. - Qualifying duplicates because lead sources are not deduplicated first. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI lead management case study](/work/antoc) - [Lead management for real-estate firms](/industries/real-estate) - [Web scraping with Playwright](/blog/web-scraping-playwright) - [Tender scraping automation](/blog/tender-scraping-automation) - [Gemini vs Claude for automation work](/blog/gemini-vs-claude) - [Building an AI content automation pipeline](/blog/ai-content-automation-pipeline) ## FAQ ### What is AI lead qualification? It is using an AI agent to make first contact with new leads, ask the questions a salesperson would ask, record the answers as structured data and decide who should follow up and how urgently. It replaces the slow, manual first call or message. ### Which questions should an AI ask to qualify a lead? Only the ones that change what sales does next. For real estate that is usually budget, preferred location, configuration, timeline to buy and whether they want a site visit. Three to five questions is plenty for first contact. ### Is AI lead scoring better than rule-based scoring? Not at first. Rule-based scoring on clear answers is transparent and easy for sales to trust. Predictive models make sense later, once you have enough historical leads with reliable outcomes to train on. ### Will leads be annoyed by an AI asking questions? Not if it is fast, polite, brief and relevant to what they enquired about. Most people prefer an immediate useful reply over waiting hours for a call. Always offer a human option for anyone who asks. ### How quickly should a new lead be contacted? As fast as possible, ideally within minutes while the buyer is still thinking about your listing or ad. That speed is the main reason to automate first contact at all. ## Next step If leads are slipping through because first contact is slow, I can design and build AI qualification around your sales process. See my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact). --- # Web Scraping With Playwright for Business Intelligence URL: https://webdevang.com/blog/web-scraping-playwright · Category: AI agents & automation · Updated: 2026-11-03 Most web scraping Playwright tutorials stop at grabbing a page title. In real projects, Playwright is my default when business data lives on websites that were never designed to be read by machines: government portals, listing sites, supplier catalogs, competitor pages. These sites often depend on JavaScript, session cookies and multi-step forms, which break simple HTTP scrapers. I used Playwright to build a government tender intelligence bot as part of the Antoc product work, scraping .gov.in portals on a GCP VM under Xvfb and classifying results with Gemini. This post covers the engineering patterns that keep a scraper running unattended for months, not just in a demo. ## TL;DR Use Playwright when you need a real browser; otherwise fetch HTML or call the underlying API. Write selectors against stable attributes, rely on Playwright's auto-waiting and explicit waits for data, and parse defensively. Run on a VM with a virtual display if headless mode misbehaves, store raw and parsed data separately, deduplicate, and alert when a run finds nothing or fails. ## Key takeaways - Use web scraping with Playwright when pages need JavaScript, sessions or real interactions; use plain HTTP requests when the data is in the HTML or an API. - Stable selectors, explicit waits and defensive parsing matter more than speed for scrapers that must run unattended. - Running a headed browser under Xvfb on a cloud VM helps with sites that behave differently in headless mode. - Store raw snapshots and parsed records separately, deduplicate by a natural key and alert on failures. ## When a browser is actually needed A browser is the most expensive way to fetch a page. Before writing Playwright code, I check the network tab. | What you see | Best approach | |---|---| | Data is in the initial HTML | HTTP request plus an HTML parser | | Page calls a JSON API you can reproduce | Call the API directly | | Content rendered by JavaScript, no clean API | Playwright | | Multi-step forms, filters, session state | Playwright | | Downloads behind clicks or generated links | Playwright with download handling | Many government and enterprise portals fall into the last three rows: search forms with dropdowns that load dynamically, session tokens in hidden fields and results that only appear after a click. That is where Playwright earns its cost. ## Writing scrapers that do not break weekly ### Locators Playwright's [locator guide](https://playwright.dev/docs/locators) recommends user-facing locators, and that advice applies to scraping too. In order of preference: 1. Role and accessible name, like a button named "Search". 2. Stable attributes such as `id`, `name` or `data-*`. 3. Text content for labels that rarely change. 4. CSS structure only as a last resort, scoped as tightly as possible. Long CSS paths like `div > div:nth-child(3) > table tr td` break the first time the site adds a banner. ### Waiting Playwright auto-waits for elements to be actionable, but data loading is a different problem. After submitting a search, wait for the results table or for a "no results" message, whichever comes first. Avoid fixed sleeps; they are either too long, which wastes time, or too short, which causes random failures. ### Pagination and lists Loop through pages by clicking "next" until it is disabled or absent, with a hard maximum to prevent infinite loops. Extract rows into plain objects on each page before moving on, so a failure on page 12 does not lose pages 1 to 11. ### Defensive parsing Real-world pages are inconsistent. Dates come in multiple formats, values have stray whitespace, some rows have missing cells. Parse each field with a small function that returns null on failure and logs the raw value, instead of throwing and killing the run. ## Running scrapers in production A scraper that runs on your laptop is a prototype. Production needs a home, a schedule and monitoring. - **Host**: a small cloud VM is often simpler than serverless for browser workloads, because browsers need memory, disk for downloads and longer run times. - **Headed under Xvfb**: some sites behave differently in headless mode. Running Chromium headed inside an Xvfb virtual display on a Linux VM avoids those differences without needing a real screen. - **Process management**: run on a schedule with cron or a process manager, and make sure the browser is always closed, even on errors. - **Politeness**: low concurrency, small delays between requests, and only the pages you need. - **Alerting**: alert not just on crashes but on suspicious success, such as zero results from a source that usually returns dozens. That usually means the site changed. ## Turning scraped data into intelligence Raw scraped rows are not intelligence. The value comes from what happens after. 1. **Store raw snapshots** (HTML or extracted text) so you can re-parse when your parser improves. 2. **Normalize** into a clean schema with consistent dates, amounts and categories. 3. **Deduplicate** by a natural key such as a reference number plus source, so re-runs do not create duplicates. 4. **Classify or enrich**, often with an LLM, to decide which records matter to the business. 5. **Deliver** to where people work: a dashboard, a CRM record or a message. ## How I built this in practice The tender intelligence bot scrapes .gov.in tender portals with Playwright running on a GCP VM with Xvfb, because headed Chromium proved more reliable on those portals than headless mode. Scraped tenders are stored in MongoDB, deduplicated, and then a Gemini classifier decides which tenders are relevant to the business before anyone sees them. The same infrastructure habits from the Antoc platform apply: GCP VMs, process management with PM2, and clear separation between collecting data and processing it. The follow-up post on tender scraping goes deeper into the classifier and delivery side. See [the Antoc case study](/work/antoc) for the wider platform, or my [UK hiring page](/hire/full-stack-developer-uk) if you need a developer for a data project from the UK. ## Common mistakes - Reaching for a browser when a simple HTTP request or the site's own API would do. - Brittle CSS paths and fixed sleeps that make the scraper flaky. - Throwing on the first malformed field and losing the whole run. - Running only on a laptop with no schedule, logs or alerts. - Treating zero results as success instead of a likely breakage. - Storing only parsed data, so a parser bug means re-scraping everything. ## Internal links - [AI agent and automation development services](/services/ai-agent-development) - [Antoc AI platform case study](/work/antoc) - [Hire a full stack developer for UK teams](/hire/full-stack-developer-uk) - [Building a government tender intelligence bot](/blog/tender-scraping-automation) - [Gemini vs Claude for automation](/blog/gemini-vs-claude) - [AI content automation pipeline](/blog/ai-content-automation-pipeline) - [AI workflow automation for operations](/blog/ai-workflow-automation) ## FAQ ### Is Playwright better than Puppeteer or Selenium for scraping? For most new projects I prefer Playwright because of its auto-waiting, reliable locators, multi-browser support and good tooling for debugging. Puppeteer and Selenium can do the job, but Playwright usually means less flaky code. ### Is web scraping legal? It depends on the site, the data and your jurisdiction. Public, non-personal data is generally lower risk, but you should respect terms of service and robots.txt, avoid personal data, keep request rates low and get legal advice for anything sensitive. ### Why does my scraper work locally but fail on a server? Common causes are missing browser dependencies, sites behaving differently for headless browsers, different time zones or locales, and IP-based restrictions. Running a headed browser under a virtual display like Xvfb and matching locale settings often fixes it. ### How often should a business scraper run? As often as the data actually changes and the business needs it, and no more. Daily or a few times a day is typical for listings and notices. Running more often adds load on the source site without adding value. ## Next step If your team copies data from websites by hand, or relies on a fragile scraper, I can build a Playwright pipeline that runs reliably and feeds your systems. Explore my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact). --- # Building a Government Tender Intelligence Bot URL: https://webdevang.com/blog/tender-scraping-automation · Category: AI agents & automation · Updated: 2026-11-03 Companies that sell to government spend hours every week checking procurement portals, scanning long lists of notices, and still miss relevant tenders. Tender scraping automation replaces that routine with a bot that collects notices, reads them and surfaces only the opportunities worth a bid team's attention. I built a government tender intelligence bot as part of the work around Antoc at Passdn Technologies. It scrapes .gov.in portals with Playwright on a GCP VM running Xvfb, stores tenders in MongoDB and uses a Gemini classifier to decide relevance. This post walks through how I would design one end to end. ## TL;DR Write one Playwright scraper per portal, normalize every notice into a shared tender schema, and deduplicate by a stable key. Give an LLM a written business profile and have it label each tender with a relevance category and a reason. Deliver a deadline-ordered digest to the team, and monitor each portal for silent failures. ## Key takeaways - Tender scraping automation is valuable only when it filters thousands of notices down to the handful your business can actually bid on. - A clean tender schema with a reliable unique key is what makes deduplication across portals and re-runs possible. - An LLM classifier works best with a written business profile, clear relevance labels and a reason field for every decision. - Deadlines drive everything, so alerts and digests should be ordered by bid submission date, not by when a tender was found. ## The pipeline at a glance A tender bot has four stages, and keeping them separate makes each easier to fix. | Stage | Job | Tools I use | |---|---|---| | Collect | Search portals, open notices, extract fields | Playwright on a GCP VM with Xvfb | | Store | Normalize and deduplicate tenders | MongoDB | | Classify | Label relevance with a reason | Gemini | | Deliver | Send digests and deadline reminders | Scheduled jobs to email or chat | Separation means a portal layout change only breaks collection for that portal, and you can re-run classification with an improved prompt without re-scraping anything. ## Collecting from government portals Government portals are a good case for browser automation. Many use search forms with dropdowns, session state and paginated result tables that only render after interaction. I cover general Playwright techniques in the companion post on web scraping; here are the tender-specific points. - **One scraper per portal.** Layouts differ enough that a generic scraper becomes a mess of special cases. Each scraper outputs the same normalized shape. - **Headed browser under Xvfb.** On the .gov.in portals I worked with, headed Chromium inside a virtual display was more dependable than headless mode on a server. - **Search by recency.** Pull tenders published or updated since the last successful run, with a small overlap window to catch late postings. - **Respect manual gates.** If a portal requires a captcha or login step for certain pages, treat that as a boundary. Collect what is publicly listed and link the team to the portal for the rest. - **Low frequency.** Tenders are not stock prices. One to a few runs a day is enough and keeps load on public infrastructure low. ## A tender schema that survives reality Notices vary wildly between portals, so I define the target schema first and map each portal into it. 1. `source` and `sourceTenderId`: together form the unique key for deduplication. 2. `title` and `organization`: the issuing department or body. 3. `category` and `location` as published. 4. `estimatedValue` where available, normalized to a number. 5. `publishedAt`, `bidSubmissionDeadline` and `bidOpeningDate` as proper dates in IST. 6. `documentLinks` for the notice and attachments. 7. `rawText`: the extracted text used for classification. 8. `classification`: label, reason, model and timestamp. Upserting on `source + sourceTenderId` means re-runs update existing tenders, for example when a deadline is extended, instead of creating duplicates. A MongoDB unique compound index enforces that at the database level; the [MongoDB unique index docs](https://www.mongodb.com/docs/manual/core/index-unique/) explain the setup. ## Classifying relevance with an LLM Keyword filters miss tenders that describe your service in different words and flood you with false matches on common terms. An LLM reading the actual scope does much better, if you set it up carefully. ### Write a business profile The classifier prompt includes a short profile: what the company does, what it does not do, typical project size, regions it serves and eligibility constraints it cannot meet. This is the single most important input. Vague profiles produce vague labels. ### Use fixed labels and a reason I ask for one of three labels, `relevant`, `maybe` or `irrelevant`, plus a one-sentence reason and the key matching phrases. Structured output makes this easy to store and filter. The reason field is what earns the team's trust, because they can see why a tender was flagged and correct the profile when it gets something wrong. ### Keep it cheap Classification runs on every new tender, so it should use a fast, inexpensive model and only the text needed: title, organization, category and the scope section. There is no need to send every attachment for a first-pass decision. ## Delivering intelligence, not noise The output is a short, actionable list. A good digest shows relevant tenders first, then maybe tenders, each with organization, value, deadline, reason and a link. Order by bid submission deadline so the most urgent items are on top. Add reminders a few days before deadlines for tenders the team marked as interested. Monitoring matters as much as scraping. If a portal that normally yields dozens of notices returns zero, alert the developer, because the layout probably changed. ## How I built this in practice The tender bot runs Playwright scrapers on a GCP VM with Xvfb, writes tenders into MongoDB and passes new ones through a Gemini classifier for relevance. It sits alongside other automation built in the same environment, including an automated SEO blog pipeline running on a GitHub Actions self-hosted runner and the Antoc CRM itself, which shares the same GCP, PM2 and Nginx operational setup. You can see the wider platform in [the Antoc case study](/work/antoc). If you are in India and want a similar bot for your bid team, my [India hiring page](/hire/full-stack-developer-india) explains how I take on projects. ## Common mistakes - Trying to build one universal scraper for every portal instead of one per source. - No unique key, so the same tender appears several times after re-runs or extensions. - Relying on keyword filters that miss relevant tenders and flag irrelevant ones. - Classifier prompts with no business profile, producing labels nobody trusts. - Sorting results by scrape time instead of bid deadline. - No alert when a portal silently returns zero results. ## Internal links - [AI agent and automation development services](/services/ai-agent-development) - [Antoc AI and automation case study](/work/antoc) - [Hire a full stack developer in India](/hire/full-stack-developer-india) - [Gemini vs Claude for automation tasks](/blog/gemini-vs-claude) - [AI content automation pipeline](/blog/ai-content-automation-pipeline) - [AI workflow automation for operations](/blog/ai-workflow-automation) - [Instagram DM automation with the official API](/blog/instagram-dm-automation) ## FAQ ### What is tender scraping automation? It is software that regularly collects tender notices from government and public procurement portals, stores them in a structured format and filters them for relevance. The team then gets a short list of opportunities instead of checking many portals by hand. ### Can AI decide which tenders are relevant to my company? Yes, with a well-defined business profile. A language model can read a tender's title, scope and eligibility text and label it relevant, maybe or irrelevant with a reason. A human should still make the final bid decision. ### Which portals can a tender bot monitor? Most public tender portals that display notices on the web can be monitored, including many .gov.in sites. Each portal needs its own scraper because layouts and search forms differ, and some portals require manual steps that should not be bypassed. ### How much does a tender intelligence bot cost to run? Running costs are usually modest: a small cloud VM for the browser, a database and model calls for classification. Development effort depends mostly on how many portals you need and how different their layouts are. ## Next step If your team is still checking tender portals by hand, I can build a bot that collects, filters and delivers the opportunities that matter. See my [AI agent development services](/services/ai-agent-development) and [get in touch](/#contact). --- # Gemini vs Claude for Business Apps: A Builder View URL: https://webdevang.com/blog/gemini-vs-claude · Category: AI agents & automation · Updated: 2026-11-03 Founders ask me about Gemini vs Claude almost every week, usually framed as "which one should we standardize on?" My honest answer is that the question is slightly wrong. I have shipped both inside the same production CRM, and each earns its place on different jobs. This post is the builder's view: what I actually route to each model, how the trade-offs show up in latency, cost and reliability, and how to make the choice for your own business app without burning a month on experiments. ## TL;DR Use Gemini for high-volume, latency-sensitive tasks such as classification, extraction and voice conversation turns. Use Claude for multi-step agent work, careful tool calling and integrations through the Model Context Protocol. Wrap both behind one internal interface so you can switch per task. Decide with a small evaluation set built from your real data, not from public leaderboards. ## Key takeaways - Gemini vs Claude is rarely an either-or decision; most production apps should route different tasks to different models. - Gemini fits high-volume, latency-sensitive work like classification and voice turns where cost per call matters most. - Claude fits multi-step agent work, careful tool use and MCP integrations where reasoning quality matters more than raw speed. - A thin provider abstraction and a small evaluation set let you switch models in days instead of rewriting features. ## Where each model fits in a real business app Most business apps do not need one "smartest" model. They need several distinct jobs done reliably. When I break a feature into jobs, the right model usually becomes obvious. | Job | What matters most | My usual pick | | --- | --- | --- | | Classifying leads, tenders or messages | Volume, cost, consistency | Gemini | | Real-time voice conversation turns | Latency, short outputs | Gemini | | Extracting fields from messy text | Structured output, cost | Gemini (Claude for hard cases) | | Multi-step agent with tools | Instruction following, safe actions | Claude | | Acting on CRM data through MCP | Native MCP client support | Claude | | Long drafting and summarization | Tone, structure | Either; test both | ### High-volume classification If you are classifying thousands of items a day, a few hundred milliseconds and a fraction of a cent per call add up. For yes/no or category decisions with a clear rubric, the faster Gemini tiers have been accurate enough for me, and the savings fund better models elsewhere. ### Agentic work with tools When the model has to decide which tool to call, in what order, with which arguments, and then stop at the right time, I lean toward Claude. It tends to respect constraints like "never change the lead owner without confirmation" more consistently in my testing. Anthropic's [tool use documentation](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) is also clear about how to structure tool definitions, which shortens development time. ## Latency, cost and reliability trade-offs Model quality is only one axis. In production, three other things decide whether a feature survives. ### Latency For a chat widget, two seconds is fine. For a phone call, it is not. Voice agents need the first token back fast, so a lighter model with a compressed prompt often beats a stronger model with a long one. I measure time to first token, not just total response time. ### Cost Calculate cost per completed business outcome, not per token. A cheaper model that needs two retries and a human correction can cost more than a stronger model that gets it right once. I keep a simple log of tokens in, tokens out and outcome for every call so these numbers are real. ### Reliability Every provider has bad hours. If a feature matters to revenue, it needs a fallback. My pattern is a primary model per task plus a secondary from the other provider, with the same prompt adapted slightly. Google's [Gemini API docs](https://ai.google.dev/gemini-api/docs) and Anthropic's docs both cover rate limits and error codes; handle 429s and 5xx responses with backoff before you fall back. ## How to choose for your project Here is the checklist I run with clients before we commit to a model for any feature. 1. Write down the job in one sentence, including the output format. 2. Collect 30 to 100 real inputs with the answer a good human would give. 3. Write one prompt and run it against both models with identical settings. 4. Score accuracy, median latency, worst-case latency and cost per item. 5. Check failure modes: does the model refuse, hallucinate fields or ignore the schema? 6. Pick the cheapest model that clears your accuracy bar, then add a fallback. 7. Re-run the same set whenever a provider ships a new model version. That evaluation set is the single most valuable asset in an AI feature. It turns "I think the new model is better" into a number, and it makes switching models a configuration change. ### Build a thin provider layer I keep a small internal module with functions like `classify(input, schema)` and `runAgent(messages, tools)`. Each function knows which provider and model to call. Product code never imports a vendor SDK directly. When a better model ships, I change one file and re-run the evaluation set. ## How I built this in practice At Passdn Technologies I am a core engineer on Antoc AI, a real-estate CRM used by 100+ firms in India with roughly 300K leads under management. We use both the Anthropic SDK and Google Gemini in production, and the split follows the table above. You can see the full product in [the Antoc case study](/work/antoc). Gemini powers our Hinglish AI voice calling agent, paired with Sarvam for speech-to-text and text-to-speech. Latency was the whole game there: we tuned voice activity detection and compressed prompts so turns felt natural, and the agent updates leads through tool calls during the call. Gemini also classifies tenders in a government tender intelligence bot that scrapes .gov.in portals with Playwright, and it drives replies in an Instagram DM automation tool built on the official Instagram API. Claude sits on the other side of the business. We built a remote MCP server with OAuth so Claude can act on a business's CRM data: look up leads, check inventory and update records with the user's permissions. For that kind of agentic, permissioned work, Claude's tool use and MCP support made it the natural fit. For bulk blog generation, we used neither: a Groq-hosted LLaMA model inside a GitHub Actions pipeline was cheaper for that specific job. That is the point. Pick per task. ## Common mistakes - Standardizing on one model for every feature because it is simpler to explain, then overpaying for simple tasks. - Choosing a model from a public benchmark instead of testing on your own data. - Importing a vendor SDK throughout the codebase, which makes switching models a rewrite. - Ignoring time to first token on voice or chat features where users feel every pause. - Shipping without a fallback provider for revenue-critical flows. - Never re-testing after providers release new model versions. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI real-estate CRM case study](/work/antoc) - [Hire a full stack AI developer in the USA](/hire/full-stack-developer-usa) - [Building an AI content automation pipeline](/blog/ai-content-automation-pipeline) - [AI workflow automation for small businesses](/blog/ai-workflow-automation) - [Instagram DM automation with the official API](/blog/instagram-dm-automation) - [Designing safe AI agent tool calling](/blog/ai-agent-tool-calling) ## FAQ ### Is Gemini or Claude better for a business chatbot? It depends on what the chatbot does. For short, high-volume replies and classification, Gemini is usually cheaper and fast enough. For a chatbot that takes actions through tools and has to follow business rules carefully, I usually prefer Claude. ### Can I use both Gemini and Claude in the same app? Yes, and I recommend it for most products. Put both behind one internal interface, route each task to the model that fits, and keep a fallback so an outage at one provider does not take your feature down. ### Which model is cheaper to run in production? Pricing changes often, so check the current rate cards. In practice, the cheaper tiers of Gemini have worked well for bulk classification, while I reserve stronger, pricier models for the smaller share of calls that need deep reasoning. ### How do I evaluate Gemini vs Claude for my own use case? Collect 30 to 100 real inputs with known good outputs, run both models with the same prompt, and score accuracy, latency and cost. That small set beats any public benchmark for your specific workflow. ## Next step If you are deciding how to add AI to your product and want a second opinion from someone who runs both models in production, [get in touch](/#contact). I can help you scope the jobs, build the evaluation set and ship the feature through my [AI agent development service](/services/ai-agent-development). --- # An LLM Content Pipeline With GitHub Actions URL: https://webdevang.com/blog/ai-content-automation-pipeline · Category: AI agents & automation · Updated: 2026-11-03 An AI content automation pipeline sounds like a single script that turns keywords into blog posts. The versions that actually work in production look more like a small assembly line: a queue of topics, a generation step, validation, review and publishing, each one boring and testable on its own. I have built this kind of pipeline on GitHub Actions with a self-hosted runner and a Groq-hosted LLaMA model. This post walks through the design, the quality gates that matter, and the mistakes that turn automated content into a liability. ## TL;DR Break the pipeline into stages: topic queue, brief, draft, validate, open a pull request, human approve, publish. Run it on a GitHub Actions schedule so you get logs, secrets and review for free. Use a fast, cheap model for drafts and invest your effort in the brief and the validator. Never auto-publish without a human approval step. ## Key takeaways - An AI content automation pipeline is a sequence of small, testable stages, not one giant prompt. - GitHub Actions gives you scheduling, logs, secrets and pull-request review without running extra infrastructure. - Automated quality gates such as schema checks, word counts and link validation catch most bad drafts before a human sees them. - Fast, cheap models are usually enough for drafting when the brief and validation are strong. ## The stages of a content pipeline Each stage should have one input, one output and one way to fail loudly. That makes it easy to rerun a single step when something breaks. | Stage | Input | Output | Fails when | | --- | --- | --- | --- | | Topic queue | Keyword plan (JSON or sheet) | Next unclaimed topic | Queue empty | | Brief builder | Topic + site facts | Structured brief | Missing required fields | | Draft | Brief | Markdown with frontmatter | Model error or timeout | | Validate | Markdown | Pass/fail report | Any rule broken | | Pull request | Valid file | PR with diff | Git conflict | | Publish | Merged PR | Live page | Build fails | ### The topic queue Keep topics in a versioned file such as `content/plan.json` with fields like `slug`, `title`, `primaryKeyword`, `status` and `relatedPosts`. The job picks the first row with `status: "todo"`, which makes progress visible in git history and prevents duplicate posts. ### The brief The brief does most of the quality work. It includes the target keyword, the audience, the required sections, internal links to include, and a strict list of facts the model may cite. A good brief turns a mediocre model into a reliable drafter. ### The draft Ask for the complete file in one call, frontmatter included, and set a low-to-moderate temperature. If the topic is long, generate an outline first and then each section, but in my experience a single pass against a detailed brief is fine for 1,200 to 1,600 words. ## Running it on GitHub Actions GitHub Actions is a good fit because the pipeline is periodic, short-lived and produces files that belong in your repository. A scheduled workflow with `on: schedule` and a `cron` expression kicks off the job, and `workflow_dispatch` lets you run it by hand. The [GitHub Actions workflow syntax docs](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions) cover both triggers. ### Hosted or self-hosted runner Hosted runners are fine to start. A self-hosted runner on a small VM makes sense when you want to reuse cached dependencies, call internal services, or avoid per-minute costs on frequent jobs. I run self-hosted runners for several projects, managed with systemd so they restart on reboot. ### Secrets and model calls Store the model API key as a repository secret and read it as an environment variable. Wrap the model call with a timeout and one or two retries with backoff. Log token counts so you know what each post costs. ### Open a pull request, not a direct commit The job should commit the new file to a branch and open a pull request. The PR diff is your review interface, and the preview deployment from your hosting provider lets an editor see the rendered page before merge. ## Quality gates that catch bad drafts Validation is where most pipelines are weak. A model will occasionally drop a section, invent a statistic or link to a page that does not exist. Automated checks catch most of this cheaply. 1. Parse the frontmatter and fail if any required field is missing. 2. Check title and meta description length against your SEO limits. 3. Confirm the primary keyword appears in the first 100 words. 4. Verify every internal link points to a real route or known slug. 5. Enforce a word-count range so you do not ship thin pages. 6. Scan for banned phrases and filler your brand never uses. 7. Flag any number or percentage for a human to verify against the fact list. When a check fails, feed the error messages back to the model for one repair attempt, then stop. If it still fails, mark the topic `needs_review` and move on. Endless repair loops waste tokens and rarely fix a bad brief. ## How I built this in practice At Passdn Technologies, alongside my core engineering work on the Antoc AI real-estate CRM, we built an automated SEO blog pipeline using Groq-hosted LLaMA for generation and a GitHub Actions self-hosted runner to schedule and run it. You can read more about the wider product in [the Antoc case study](/work/antoc). We chose Groq because drafting is a high-volume, cost-sensitive job, and fast inference kept each run short. The runner lived on the same kind of GCP infrastructure we already managed with PM2, Nginx and systemd, so there was no new platform to learn. The pipeline reused patterns from the rest of our AI work: Gemini for classification in our tender intelligence bot, Claude and MCP for agentic CRM actions, and a cheap model where a cheap model is enough. The biggest lesson was that the validator and the brief mattered more than the model. Once the rules live in code, a reviewer can read for accuracy and voice instead of fixing formatting by hand. ## Common mistakes - Auto-publishing straight to production with no human approval step. - Writing one enormous prompt instead of a structured brief with an explicit fact list. - Letting the model invent statistics, client names or quotes. - Skipping link validation, which leads to broken internal links across dozens of posts. - Generating near-duplicate posts because the topic plan has overlapping keywords. - Retrying failed drafts forever instead of flagging them for a person. ## Internal links - [AI agent and automation development](/services/ai-agent-development) - [Antoc AI case study with AI pipelines in production](/work/antoc) - [Hire a full stack developer in Australia](/hire/full-stack-developer-australia) - [AI workflow automation for small businesses](/blog/ai-workflow-automation) - [Instagram DM automation using the official API](/blog/instagram-dm-automation) - [Safe tool calling for AI agents](/blog/ai-agent-tool-calling) - [Meta lead ads to CRM integration](/blog/meta-lead-ads-crm-integration) ## FAQ ### Can AI-generated blog posts rank on Google? They can if they are genuinely useful, accurate and reviewed. Google's guidance focuses on helpful content rather than how it was produced, so the pipeline must enforce facts, structure and human review instead of mass-producing thin pages. ### Why use GitHub Actions instead of a separate server? Actions already gives you cron schedules, secret storage, logs and pull requests. For a content pipeline that runs a few times a day, that is usually all the infrastructure you need, and the output lands as a reviewable commit. ### Which LLM should I use for content generation? For first drafts against a detailed brief, a fast open model such as LLaMA served by Groq is often good enough and cheap. Use a stronger model for editing passes or technical topics where accuracy matters more. ### How much human review does an automated pipeline need? At minimum, a person should approve every post before it goes live. Automation should handle formatting, validation and scheduling so the reviewer spends their time on accuracy and voice. ## Next step If you want a content pipeline that respects your brand and your facts instead of flooding your site with filler, [get in touch](/#contact). I design and build these systems as part of my [AI agent development service](/services/ai-agent-development). --- # AI Workflow Automation for Small Businesses URL: https://webdevang.com/blog/ai-workflow-automation · Category: AI agents & automation · Updated: 2026-11-03 Most small businesses I talk to want AI workflow automation, but what they describe is a mix of three things: tasks that need plain rules, tasks that need integrations, and a small number of tasks that genuinely need AI. Getting that split right is the difference between a system that runs quietly for years and one that needs babysitting. This guide is how I scope automation for owners and operations heads. It covers how to map a workflow, where rules beat AI, where AI earns its keep, and the guardrails I put around every automated action. ## TL;DR Map the workflow first and make the data structured. Automate the deterministic steps with rules, database logic and integrations. Add AI only where the input is unstructured or the decision needs judgment: reading messages, classifying, summarizing, drafting. Keep humans in the loop for anything involving money or customer records, and start with one workflow before expanding. ## Key takeaways - Good AI workflow automation starts with a clean, structured workflow; AI cannot fix messy data or undefined processes. - Most small-business automation should be deterministic rules, with AI reserved for reading, classifying and drafting. - Every AI step needs a fallback path and a human checkpoint for actions that touch money or customers. - Start with one high-frequency, low-risk workflow, measure it, then expand. ## Map the workflow before you automate it Automation amplifies whatever process you already have. If enquiries live in three inboxes and nobody agrees on what "qualified" means, an AI model will just produce inconsistent results faster. ### Write the workflow as steps For each workflow, list the trigger, each step, who does it today, what data they look at and what they produce. A typical enquiry workflow looks like this: message arrives, someone reads it, decides if it is a real lead, assigns it, sends a reply, sets a follow-up reminder. ### Mark each step by type Now label every step. Is it a rule ("assign to whoever handles this city"), an integration ("copy the lead from the ad platform"), or judgment ("is this a serious buyer?")? In my experience, most steps in a small business are rules and integrations. Judgment steps are usually a minority, and those are your AI candidates. | Step type | Example | Best tool | | --- | --- | --- | | Trigger | New form submission, new message | Webhook or API listener | | Rule | Assign by city, remind after 2 days | Code or a rule engine | | Calculation | Wallet balance, tax totals | Database functions | | Integration | Push lead from ad platform | API connector | | Judgment | Classify intent, summarize a call | AI model | | Communication | Draft a reply in the customer's language | AI model with review | ## Where rules beat AI Rules are cheap, instant, testable and explainable. When a staff member asks "why was this lead assigned to me?", a rule gives a clear answer. Anything numeric, financial or compliance-related belongs in deterministic code. Balances, stock levels and tax figures are the classic examples. These should be computed by the system from source records, never estimated by a model. A database function that sums transactions will be correct every time; a language model asked to "work out the balance" will not. Scheduling is another. "Send a reminder on Day 0, Day 2 and Day 7" is a cron job, not an AI problem. The same goes for duplicate detection on phone numbers or emails, which is a database query. ## Where AI earns its place AI is worth the cost and the uncertainty when the input is messy or the output needs language. 1. **Reading unstructured input.** Turning a free-text WhatsApp message or a call transcript into fields like budget, location and intent. 2. **Classification.** Deciding whether a message is a new enquiry, a complaint or spam, or whether a document matches a category. 3. **Summarization.** Turning a day of activity into a short report for the owner. 4. **Drafting.** Writing a first reply that a staff member approves or edits. 5. **Conversation.** Handling first-touch chat or voice where a human would otherwise answer the same questions repeatedly. For each AI step, define the output schema and what happens when the model is unsure. A good pattern is to return a confidence label and route low-confidence cases to a person. Anthropic's guide on [building effective agents](https://www.anthropic.com/engineering/building-effective-agents) makes a similar argument: prefer simple, composable workflows over open-ended autonomy. ### Guardrails for every automated action - Limit the AI to specific tools such as "create follow-up task" or "update lead stage". - Enforce permissions on the server, not in the prompt. - Log every action with the input, output and model used. - Require human confirmation for refunds, deletions, price changes and bulk messages. ## How I built this in practice A good example of the "structure first" principle is HNEFA, a gaming cafe POS and ERP I contributed to with the Exlaso team. You can see the details in [the HNEFA case study](/work/hnefa). It runs a live floor of PCs and consoles with real-time timed sessions, bookings, touch POS billing, cash drawers with denomination counting and around 15 reports. The automation there is deliberately deterministic. Prepaid customer wallet balances are computed by database functions rather than stored as editable columns, inventory uses FIFO batches, and each tenant's data is isolated with Postgres row-level security. Reports like the day summary, P&L and GST/HSN tax come straight from the transaction records. That clean foundation is what makes an AI layer safe to add later, for example a plain-language daily summary generated from report data a model can read but not change. The [gaming cafe industry page](/industries/gaming-cafes) covers that domain in more depth. The AI-heavy side of my work is Antoc AI, the real-estate CRM where I am a core engineer. Its WhatsApp flow builder runs triggers, Day 0/2/7 nurture drips and reminders as rules, and adds an AI agent node only where a conversation needs judgment. Same principle: rules for the predictable parts, AI for language. ## Common mistakes - Automating a process nobody has written down, so the AI inherits the confusion. - Using a language model for calculations, balances or stock counts. - Letting the model decide permissions through prompt instructions alone. - Launching five automations at once and being unable to tell which one caused a problem. - No logging, so nobody can explain why an action happened. - No fallback when the model provider is slow or down. ## Internal links - [AI agent and automation development services](/services/ai-agent-development) - [HNEFA gaming cafe POS and ERP case study](/work/hnefa) - [Software for gaming cafes](/industries/gaming-cafes) - [Instagram DM automation with the official API](/blog/instagram-dm-automation) - [Designing safe AI agent tool calling](/blog/ai-agent-tool-calling) - [Meta lead ads to CRM in real time](/blog/meta-lead-ads-crm-integration) - [WhatsApp automation for business](/blog/whatsapp-automation-for-business) ## FAQ ### What is AI workflow automation? It is the use of software to run a business process end to end, with AI models handling the steps that need judgment, such as reading a message, classifying a request or drafting a reply. The rest of the workflow is usually plain rules and integrations. ### Which tasks should a small business automate first? Start with high-frequency, low-risk tasks like lead routing, follow-up reminders, enquiry replies and daily summaries. Avoid starting with anything that moves money or changes records customers rely on. ### Do I need AI, or are rules enough? If the input is structured and the decision can be written as an if-then rule, rules are cheaper and more reliable. Use AI when the input is unstructured text or voice, or when the decision needs context a rule cannot capture. ### How much does AI workflow automation cost to build? A single focused workflow can often be built in a few weeks, while a broader system with dashboards, roles and integrations takes longer. Model usage costs are usually small compared to development time when you route simple tasks to cheaper models. ### Is it safe to let AI take actions in my business software? It is safe when actions are limited to well-defined tools, permissions are enforced on the server, and anything risky requires a human to confirm. The AI should suggest or draft, while the system decides what is allowed. ## Next step If you have a workflow that eats hours every week and want to know which parts should be rules and which should be AI, [get in touch](/#contact). I scope and build these systems through my [AI agent development service](/services/ai-agent-development). --- # Instagram DM Automation With the Official API URL: https://webdevang.com/blog/instagram-dm-automation · Category: AI agents & automation · Updated: 2026-11-03 For many businesses, Instagram is where enquiries actually start. Someone sees a reel, comments "price?" and expects an answer in minutes. Instagram DM automation handles that first response, captures the lead and hands serious buyers to your team, but only if it is built on the official API and designed with the platform's rules in mind. I built an Instagram DM automation tool using Meta's official Instagram API, Next.js, Mongoose, a reactflow-based flow builder, Gemini and scheduled cron jobs. Here is how that architecture works and what to watch out for. ## TL;DR Use the official Instagram messaging API with a professional account and an approved Meta app. Receive DMs and comments by webhook, run them through a flow (keyword triggers, buttons, AI replies, handoff), and reply through the Graph API within the allowed messaging window. Store every contact and conversation in your own database so DMs turn into trackable leads. Avoid any tool that asks for your Instagram password. ## Key takeaways - Instagram DM automation should run on Meta's official API; scraping or password-based bots put the account at risk. - Webhooks deliver incoming messages and comments, and your server replies through the Graph API within Meta's messaging window. - A visual flow builder lets non-developers change replies without touching code, while AI handles open-ended questions. - Store every conversation and contact in your own database so DMs become leads you can follow up on. ## How the official Instagram API works for messaging Meta's [Instagram Platform documentation](https://developers.facebook.com/docs/instagram-platform) is the source of truth, and it changes, so check it before you build. The overall shape has been stable for a while. ### Account and app setup You need an Instagram professional account (business or creator) and a Meta developer app. The app requests messaging permissions, goes through Meta's app review, and the business connects its account through an OAuth login. Your server stores the resulting access token per connected account, encrypted at rest. ### Webhooks in, Graph API out When someone sends a DM or comments on a post, Meta sends a webhook to your HTTPS endpoint. You verify the signature, store the event, and respond quickly with a 200 so Meta does not retry. Processing happens asynchronously. Replies go out through a Graph API call using the account's token. ### The messaging window The API is designed for conversations the user starts. You can reply within a standard window after their last message, and outside that window your options are limited. Your flow design has to respect this: ask for a phone number or email early, so you can continue the conversation on another channel if needed. ## Designing the automation flows A flow is a small graph: a trigger, a series of steps and an end. Building it as a visual editor means a marketing person can change copy without a deploy. | Node type | What it does | Example | | --- | --- | --- | | Trigger | Starts a flow | DM contains "price", or comment on a specific post | | Message | Sends text or quick replies | "Which city are you looking in?" | | Collect | Saves an answer to a contact field | `contact.city`, `contact.phone` | | Condition | Branches on data | If budget is set, go to booking step | | AI reply | Answers open questions with context | Product FAQ answered by Gemini | | Handoff | Pauses automation, notifies a human | Assign to sales, mute bot for 24 hours | | Delay | Waits, then continues | Follow-up after a set time inside the window | ### Store flows as data I store each flow as JSON nodes and edges, which is exactly what reactflow produces in the editor. The runtime walks the graph: load the contact's current node, evaluate the incoming message, move to the next node, send the output, save state. Keeping the editor format and the runtime format the same avoids translation bugs. ### Where AI fits AI handles the messages that do not match a button or keyword: "do you deliver to Dubai Marina?" or "what is the difference between these two plans?". The model gets the business's FAQ, the contact's collected fields and the last few messages, and returns either a reply or a `handoff` signal. Never let the model invent prices or availability; give it the data or tell it to hand off. ## Operational details that matter 1. **Idempotency.** Meta can deliver the same webhook more than once. Store the message ID and skip duplicates. 2. **Rate limits.** Queue outgoing replies and respect the API's limits instead of firing everything at once. 3. **Token health.** Run a scheduled job that checks each connected account's token and alerts the business before it expires. 4. **Human takeover.** When a staff member replies manually, pause the bot for that contact so the two do not talk over each other. 5. **Scheduled jobs.** Use cron for timed follow-ups, cleanup of stale flow states and daily summaries. 6. **Audit trail.** Log every inbound and outbound message with the node that produced it. ## How I built this in practice I built the Instagram DM automation tool as part of my work at Passdn Technologies, where I am also a core engineer on the Antoc AI real-estate CRM. The tool uses the official Instagram API, Next.js for the dashboard and webhook routes, Mongoose models for accounts, contacts, flows and messages, reactflow for the visual flow builder, Gemini for AI replies and cron for scheduled work. Much of the design came from Antoc's WhatsApp automation, which has a visual flow builder with triggers for incoming messages, new leads, reminders and pipeline stages, Day 0/2/7 nurture drips and an AI agent node. Reusing that mental model meant the Instagram tool felt familiar and the same flow patterns applied across channels. You can see the broader system in [the Antoc case study](/work/antoc), where captured conversations become leads with duplicate detection and auto-assignment. Gemini was the right fit for replies because DM volume can be high and responses are short. For agentic actions on CRM data, we use Claude through an MCP server instead. ## Common mistakes - Using a third-party tool that logs in with your Instagram password instead of the official API. - Designing flows that assume you can message users any time, ignoring the messaging window. - Processing webhooks synchronously and timing out, which causes retries and duplicate replies. - Letting the AI quote prices or stock it was never given. - No human takeover, so the bot keeps replying while a salesperson is mid-conversation. - Keeping conversations only inside Instagram, so DMs never become follow-up tasks in a CRM. ## Internal links - [AI agent and automation development](/services/ai-agent-development) - [Antoc AI CRM case study](/work/antoc) - [Hire a full stack developer in Dubai](/hire/full-stack-developer-dubai) - [Designing safe AI agent tool calling](/blog/ai-agent-tool-calling) - [Meta lead ads to CRM integration](/blog/meta-lead-ads-crm-integration) - [WhatsApp automation for business](/blog/whatsapp-automation-for-business) - [AI voice agent development](/blog/ai-voice-agent-development) ## FAQ ### Is Instagram DM automation allowed? Yes, when it uses Meta's official Instagram messaging API with a professional account and an approved app. Tools that log in with your password or simulate a browser break Instagram's terms and can get the account restricted. ### Can I send automated DMs to anyone on Instagram? No. The official API is built for replying to people who contact you first, such as by sending a DM or commenting, and it enforces a messaging window. Cold outreach to strangers is not what the API is for. ### Can AI reply to Instagram DMs automatically? Yes. A model like Gemini can draft or send replies based on your business information, but it should work inside a flow with clear rules, a handoff to a human and logging of every message. ### What do I need to set up Instagram DM automation? You need an Instagram professional account linked as Meta requires, a Meta developer app with the messaging permissions approved, a server that receives webhooks over HTTPS, and a database to store contacts and conversations. ## Next step If Instagram is a real lead source for your business and replies are falling through the cracks, [get in touch](/#contact). I build official-API messaging automation, flow builders and AI replies through my [AI agent development service](/services/ai-agent-development). --- # AI Agent Tool Calling: Designing Safe CRM Actions URL: https://webdevang.com/blog/ai-agent-tool-calling · Category: AI agents & automation · Updated: 2026-11-03 AI agent tool calling is what turns a chatbot into something that does work: moving a lead to "site visit scheduled", logging a call outcome, creating a follow-up task. It is also where things can go wrong quickly, because the model is now writing to the same records your sales team depends on. I have shipped tool calling in a production real-estate CRM, both from a live voice agent and through an MCP server that lets Claude act on a business's data. This post covers the design rules I follow so agents stay useful without becoming a risk. ## TL;DR Treat the model as an untrusted caller that proposes actions. Expose a few narrow, business-level tools with strict schemas. Enforce authentication, tenant scoping, permissions and validation on the server for every call. Require confirmation for destructive or bulk actions, and log every tool call with inputs and results. ## Key takeaways - In AI agent tool calling, the model only proposes actions; your server decides whether they are allowed and executes them. - Narrow, task-shaped tools with strict schemas are safer and more accurate than generic database access. - Permissions, tenant scoping and validation must live in code, never only in the system prompt. - Destructive or bulk actions need confirmation, and every tool call needs an audit log entry. ## Design tools around business actions The most common mistake is exposing something like `run_query(collection, filter, update)`. It is flexible, but the model has to understand your schema perfectly, and one bad filter can change thousands of records. ### Prefer narrow tools Design tools the way you would design buttons in your UI. Each one does one business action with a small set of arguments. | Tool | Arguments | Risk level | Confirmation | | --- | --- | --- | --- | | `search_leads` | `query`, `stage`, `limit` (max 20) | Read | No | | `get_lead` | `leadId` | Read | No | | `add_note` | `leadId`, `text` | Low write | No | | `update_lead_stage` | `leadId`, `stage` (enum) | Medium write | Optional | | `create_follow_up` | `leadId`, `dueAt`, `note` | Low write | No | | `reassign_lead` | `leadId`, `userId` | High write | Yes | | `bulk_update` | Avoid exposing | High | Always, if at all | ### Write descriptions for the model Tool descriptions are prompts. Say when to use the tool, when not to, and what each argument means. Use enums for stages and statuses so the model cannot invent a value like "hot-ish". Anthropic's [tool use guide](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) recommends detailed descriptions for exactly this reason. ### Return useful results Return compact, structured results: the updated record's key fields, or a clear error like `{"error": "stage_not_allowed", "allowed": ["visit_scheduled", "lost"]}`. Good errors let the model correct itself instead of guessing. ## Enforce safety on the server The system prompt can say "never reassign leads", but a prompt is guidance, not a control. Every safety rule needs to exist in the code that executes the tool. ### The execution checklist Every tool handler in my agents runs the same steps before touching data. 1. Authenticate the caller and resolve the user and business from the session or token, never from model arguments. 2. Scope every query to the current tenant, so a `leadId` from another business returns "not found". 3. Check the user's role and plan permissions for this specific action. 4. Validate arguments against the schema: types, enums, length limits, date ranges. 5. Reject empty or overly broad filters on anything that writes. 6. Execute the change in a single, small operation. 7. Write an audit entry: who, which tool, arguments, result, model and timestamp. 8. Return a compact result or a clear error. ### Confirmation for risky actions For actions like reassigning or bulk changes, the tool should return a pending confirmation rather than executing. In a chat interface, the user sees "Reassign 1 lead to the selected teammate? Confirm / Cancel". In a voice call, the agent reads back the change. Only a confirmed token executes the action. ### Limits and loops Cap the number of tool calls per conversation turn and per session. Agents occasionally loop, calling the same search repeatedly. A hard limit and a timeout stop runaway costs and accidental mass updates. ## Tool calling in real time vs. through MCP The same rules apply in two different settings I work with. In a **voice agent**, tool calls happen mid-conversation, so they must be fast. Keep tools few and arguments simple, and do slow work like syncing to other systems after the call. The agent should say something natural while a tool runs. Through **MCP**, an external AI client such as Claude discovers your tools from a server. The [Model Context Protocol docs](https://modelcontextprotocol.io) describe how servers expose tools; what they cannot do is enforce your business rules for you. OAuth gives you the user's identity, and your handlers still need the full checklist above. ## How I built this in practice I am a core engineer at Passdn Technologies on Antoc AI, a real-estate CRM used by 100+ firms in India with about 300K leads. Tool calling shows up in two places, both covered in [the Antoc case study](/work/antoc). The first is our Hinglish AI voice calling agent, built with Sarvam for speech and Gemini through a voice platform. During a call, it updates the lead through tool calls: interest level, budget, preferred location, a site-visit time. We kept the tool set small because every extra tool adds tokens to the prompt, and in voice, latency is everything. The second is a remote MCP server with OAuth that lets Claude act on a business's CRM data. Every tool resolves the business and user from the OAuth token, respects plan-based feature locking and role permissions, and scopes queries to the current organization, which matters because users can switch between multiple businesses. The data layer underneath was hardened as leads grew past 300K: proper indexes, safe bulk operations that validate filters before running, and authentication plus network restrictions on the database. That hardening is what makes it reasonable to let an agent write at all. ## Common mistakes - Exposing raw database queries as a tool instead of business actions. - Trusting `userId` or `businessId` arguments supplied by the model. - Relying on the system prompt to enforce permissions. - Allowing update operations with empty or broad filters. - No audit trail, so nobody can tell whether a change came from a person or the agent. - No cap on tool calls, letting an agent loop and rack up cost. ## Internal links - [AI agent development services](/services/ai-agent-development) - [Antoc AI CRM case study](/work/antoc) - [Hire a full stack AI developer in the UK](/hire/full-stack-developer-uk) - [Meta lead ads to CRM integration](/blog/meta-lead-ads-crm-integration) - [WhatsApp automation for business](/blog/whatsapp-automation-for-business) - [AI voice agent development](/blog/ai-voice-agent-development) - [Building an MCP server for your product](/blog/mcp-server-development) ## FAQ ### What is tool calling in an AI agent? Tool calling lets a language model request that your application run a specific function, such as updating a lead, with arguments the model fills in. Your code executes the function and returns the result so the model can continue. ### How do I stop an AI agent from deleting or corrupting data? Do not give it delete tools unless absolutely needed, validate every argument on the server, scope every query to the current user and tenant, and require human confirmation for destructive or bulk actions. Prompt instructions alone are not a safety control. ### Should an AI agent get direct database access? No. Give it a small set of business-level tools like update_lead_stage or create_follow_up instead of raw queries. That keeps permissions and validation in one place and makes the model's job easier. ### Is function calling the same as MCP? They are related. Function calling is how a model requests a tool within one API call, while the Model Context Protocol is a standard way to expose tools from a server so different AI clients can discover and use them. ## Next step If you want an AI agent that can act inside your CRM or internal tools without putting your data at risk, [get in touch](/#contact). I design and build safe agent integrations through my [AI agent development service](/services/ai-agent-development). --- # Meta Lead Ads to CRM: Real-Time Integration URL: https://webdevang.com/blog/meta-lead-ads-crm-integration · Category: AI agents & automation · Updated: 2026-11-03 If you run Facebook or Instagram lead ads, the minutes after a form submission matter more than almost anything else in your funnel. A proper Meta lead ads CRM integration gets that lead into your system, assigned to the right person and receiving a first message before they have scrolled past the next ad. I work on this exact flow in Antoc AI, a real-estate CRM used by more than 100 firms in India. This post walks through the architecture: webhooks, Graph API fetches, field mapping, deduplication, assignment and the monitoring that keeps it reliable. ## TL;DR Subscribe each connected Facebook Page to your Meta app's `leadgen` webhook. When a lead arrives, fetch the full record from the Graph API using the lead ID and a page access token. Map form answers to CRM fields per form, check for duplicates by phone and email, apply assignment rules and trigger follow-up automation. Monitor tokens and run a backfill job so no lead is lost. ## Key takeaways - A real-time Meta lead ads CRM integration uses the leadgen webhook to get a lead ID, then fetches the full lead from the Graph API. - Field mapping per form is essential because every campaign asks slightly different questions. - Duplicate detection and auto-assignment rules decide whether speed actually turns into sales conversations. - Token expiry, missed webhooks and form changes are the usual failure points, so monitor and backfill. ## How the integration works end to end Meta's [lead ads documentation](https://developers.facebook.com/docs/marketing-api/guides/lead-ads) covers the API details. Here is the practical flow I implement. ### 1. Connect the page The business logs in with Facebook through your app and grants the permissions needed to read leads for their pages. Your server exchanges the user token for long-lived page access tokens and stores them encrypted, one per page. It then subscribes each page to the app for the `leadgen` field. ### 2. Receive the webhook When someone submits an instant form, Meta posts a webhook to your HTTPS endpoint. The payload contains identifiers, not answers: `leadgen_id`, `form_id`, `page_id`, `ad_id` and a timestamp. Verify the request signature with your app secret, store the raw event, return 200 quickly and process it in the background. ### 3. Fetch the lead Call the Graph API for the `leadgen_id` with that page's token. The response includes `field_data`, an array of question names and values such as `full_name`, `phone_number`, `email` and any custom questions like budget or preferred city. ### 4. Create or update the CRM lead Map the fields, normalize phone numbers, check for duplicates, assign an owner and save. Then fire whatever comes next: a WhatsApp welcome, a task for the agent, or a call from an AI voice agent. ## Field mapping, dedupe and assignment The webhook is the easy part. The business logic after it is what sales teams actually feel. ### Map per form Every campaign has a slightly different form. One asks "Budget?", another asks "What is your price range?". Store a mapping per `form_id` that links each question key to a CRM field, with a default mapping for standard fields. Unmapped answers should go into a notes field rather than disappearing. | Form question key | CRM field | Normalization | | --- | --- | --- | | `full_name` | `name` | Trim, title case | | `phone_number` | `phone` | Strip spaces, add country code | | `email` | `email` | Lowercase | | `budget` / custom | `budgetRange` | Map options to enum | | `city` / custom | `preferredLocation` | Match to known locations | | (metadata) `ad_id`, `form_id` | `source`, `campaign` | Store for attribution | ### Detect duplicates The same person often fills two forms or comes back weeks later. Match on normalized phone first, then email, scoped to the business. On a match, update the existing lead, append the new source and notify the current owner instead of creating a second record that two agents might call. ### Assign automatically Common assignment rules include round-robin within a team, routing by project or campaign, routing by location, and respecting who is on duty that day. Keep rules in data so a manager can change them without a deploy, and always log which rule fired. ## Keeping it reliable Lead integrations fail quietly, which is the worst way to fail. A checklist I use for every deployment: 1. Make webhook processing idempotent by storing `leadgen_id` with a unique index. 2. Run a scheduled job that checks every page token and alerts the business when one is invalid. 3. Run a backfill that pulls recent leads per form and inserts any the webhook missed. 4. Alert on unmapped required fields when a marketer edits a form. 5. Show a "last lead received" timestamp per form on the integration screen. 6. Test with Meta's lead ads testing tool before each new campaign goes live. ## How I built this in practice At Passdn Technologies, I am a core engineer on Antoc AI, a real-estate CRM used by 100+ firms in India with about 300K leads managed. Meta lead ads are one of several sources feeding it, alongside Google Ads, property portals in the style of 99acres and OLX, Google Sheets, generic webhooks and public forms. The full product is in [the Antoc case study](/work/antoc). Every source goes through the same pipeline after normalization: duplicate detection, auto-assignment rules and then automation. That shared pipeline is what makes adding a new source a small job instead of a rewrite. Once a lead lands, the WhatsApp flow builder can trigger on "new lead" and start Day 0/2/7 nurture drips, and our Hinglish AI voice calling agent can call the lead and update fields through tool calls. As lead volume grew past 300K, we hardened the MongoDB layer with indexes for dedupe lookups, safe bulk operations with filter validation, and authentication plus network restrictions. For more on the real-estate side, see the [real estate industry page](/industries/real-estate). ## Common mistakes - Relying only on the webhook with no backfill, so leads vanish when a token expires. - Creating a new lead for every submission instead of matching existing contacts. - Hard-coding field names, which breaks when marketing edits a form. - Processing the webhook synchronously and timing out under load. - Dropping `ad_id` and `form_id`, losing campaign attribution for reporting. - Assigning leads without checking who is actually working that day. ## Internal links - [AI agent and automation development](/services/ai-agent-development) - [Antoc AI real-estate CRM case study](/work/antoc) - [CRM and automation for real estate](/industries/real-estate) - [WhatsApp automation for business](/blog/whatsapp-automation-for-business) - [AI voice agent development](/blog/ai-voice-agent-development) - [MCP server development](/blog/mcp-server-development) - [WhatsApp Business API integration](/blog/whatsapp-business-api-integration) ## FAQ ### How do Facebook lead ads get into a CRM automatically? Meta sends a leadgen webhook to your server when someone submits a lead form. Your server uses the lead ID to fetch the full submission from the Graph API, maps the answers to CRM fields and creates or updates the lead. ### Do I need Zapier to connect Meta lead ads to my CRM? No. Zapier and similar tools work for small volumes, but a direct webhook integration is faster, cheaper at scale and lets you run your own dedupe and assignment logic. It does require a Meta app and some development work. ### Why are some Facebook leads missing from my CRM? The common causes are an expired or revoked page token, the page not being subscribed to the app, permission changes, or webhook delivery failures. A scheduled backfill job that pulls recent leads for each form catches anything the webhook missed. ### How fast should a lead from Meta ads be contacted? As fast as you can manage. With a direct integration, the lead can be in the CRM, assigned and receiving a first WhatsApp message within seconds, which gives your team the best chance of reaching them while they are still interested. ### Does this work for Instagram lead forms too? Yes. Instant forms on Instagram ads are part of the same Meta lead ads system, so the same webhook and Graph API flow brings those leads into the CRM. ## Next step If your ad leads sit in a spreadsheet or arrive hours late, [get in touch](/#contact). I build real-time lead capture and follow-up automation through my [AI agent development service](/services/ai-agent-development). --- # Getting a Flutter WebView App Approved on the App Store URL: https://webdevang.com/blog/flutter-webview-app-store-approval · Category: Mobile & DevOps · Updated: 2026-11-03 Wrapping a working web app in Flutter is one of the fastest ways to get onto both app stores. Android usually goes smoothly. iOS is where teams get stuck, because Flutter WebView App Store approval hinges on convincing a reviewer that your app is more than a website in a frame. I shipped Client Mitra, a CRM for photography studios, to the App Store this way: one Flutter wrapper around the Next.js web app, with native features added where Apple expects them. This is what review asked for and how I would plan the same path again. ## TL;DR A WebView app can pass App Store review if it adds real native value. Add native sign-in, including Sign in with Apple when you offer social login. Use Apple in-app purchase for digital subscriptions sold in the app, verified on your server. Add push notifications, proper error and offline states, and give the reviewer a working demo account. ## Key takeaways - Flutter WebView App Store approval depends on adding genuine native value, not just loading a URL in a frame. - If you offer Google or other third-party login on iOS, plan for Sign in with Apple as a native option. - Digital subscriptions sold inside an iOS app generally need Apple in-app purchase with server-side receipt verification. - A reviewer demo account, clear metadata and no dead-end screens prevent most avoidable rejections. ## Why WebView apps get rejected Apple's [App Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) are the reference. Three areas cause most trouble for wrapped web apps. | Guideline area | What triggers rejection | What fixes it | | --- | --- | --- | | Minimum functionality (4.2) | App is a website with no native features | Native sign-in, push, IAP, native error screens | | Login services (4.8) | Google login offered, no Apple equivalent | Native Sign in with Apple | | In-app purchase (3.1.1) | Subscription sold through a web payment page | Apple IAP paywall on iOS | | Account deletion | No way to delete the account in-app | Delete-account flow in settings | | Completeness (2.1) | Broken links, placeholder content, crashes | Demo account, tested flows | The core idea is simple: the iOS app should feel like it belongs on iOS. That means native capabilities where users expect them and no moments where the user lands on a raw browser error or a web payment form. ## The native layer that makes the difference I use `flutter_inappwebview` for the WebView because it gives fine control over JavaScript channels, cookies, navigation and file uploads. The architecture is a thin native shell with a bridge to the web app. ### A JavaScript bridge The web app detects it is running inside the shell (for example through a user agent suffix or an injected flag) and calls native handlers instead of web flows: `nativeSignIn("apple")`, `nativePurchase(productId)`, `registerPush()`. The shell returns results back to the page through a callback. Keep the bridge small and versioned so old app builds keep working when the web app changes. ### Native sign-in On iOS, the login screen shows Sign in with Apple and Google as native buttons. The shell gets the identity token, sends it to your backend, and the backend verifies it and issues your normal session token, which the shell injects into the WebView. Your existing auth system stays the single source of truth. ### In-app purchase paywall On iOS, the upgrade button opens a native paywall backed by Apple IAP instead of the web checkout. After purchase, the app sends the transaction to your server, which verifies it with Apple and updates the subscription. The web app reads subscription status from your API, so the same account works on web, Android and iOS. ### Push and local notifications Native push is one of the clearest signals of native value. The shell registers for notifications, sends the device token to your backend, and handles taps by navigating the WebView to the right page. ## A submission checklist This is the list I work through before pressing submit. 1. Native Sign in with Apple works, including the "hide my email" relay address. 2. The iOS paywall uses IAP only, with no links to external payment pages. 3. Restore purchases is available and works. 4. Account deletion is reachable from settings. 5. Push permission is requested in context, not on first launch. 6. A native screen handles no internet and server errors, with retry. 7. External links open in the system browser, not inside the app. 8. The reviewer has a demo account with realistic sample data. 9. Screenshots and description show the app as it actually works on iOS. 10. Crash reporting is live, so any reviewer crash is visible immediately. ## How I built this in practice Client Mitra is a solo build: a multi-tenant CRM for Indian photography studios and creative businesses covering enquiries, bookings, payments, crew calendars for multi-day weddings, GST invoices with UPI QR codes, expenses and reports. The web app runs on Next.js App Router with a Node/Express and MongoDB backend. The full story is in [the Client Mitra case study](/work/clientmitra). For mobile, I built one Flutter wrapper around the web app using `flutter_inappwebview`, shipping native Android and iOS apps from the same codebase. The shell adds native sign-in, in-app purchase, FCM push plus local notifications and Crashlytics. App Store review specifically required three things before approval: native Sign in with Apple (the web app offered WhatsApp OTP and Google login), an IAP paywall for subscriptions instead of the Razorpay checkout used on the web, and server-side verification of Apple transactions, which I implemented with `@apple/app-store-server-library` in Node. Once those were in place, the same backend handled Razorpay subscriptions on web and Apple subscriptions on iOS, with one subscription status per business. ## Common mistakes - Submitting a WebView that just loads the website with no native features. - Offering Google login on iOS without Sign in with Apple. - Leaving the web checkout reachable inside the iOS app. - Trusting the client's purchase result without verifying it on the server. - No offline or error screen, so the reviewer sees a blank page. - Forgetting the demo account, which causes an instant rejection. ## Internal links - [Flutter app development services](/services/flutter-app-development) - [Client Mitra case study](/work/clientmitra) - [Hire a full stack and Flutter developer in the USA](/hire/full-stack-developer-usa) - [Flutter app development cost in 2026](/blog/flutter-app-development-cost) - [Apple in-app purchase server verification](/blog/in-app-purchase-server-verification) - [FCM push notifications across web and mobile](/blog/fcm-push-notifications) - [Building a Flutter video player](/blog/flutter-video-player) ## FAQ ### Will Apple reject a Flutter app that uses a WebView? Not automatically. Apple rejects apps that feel like a repackaged website with little native functionality. A WebView app that adds native sign-in, push notifications, in-app purchase and proper offline and error handling can be approved. ### Do I need Sign in with Apple if my web app uses Google login? In most cases, yes. Apple's guidelines require an equivalent privacy-focused login option, and Sign in with Apple is the usual way to satisfy that when you offer third-party social login on iOS. ### Can I use Razorpay or Stripe for subscriptions in my iOS app? For digital subscriptions sold inside the app, Apple generally requires in-app purchase. Keep your web payment provider for the web app, and use Apple IAP on iOS with the subscription state synced to your server. ### How long does App Store review take for a WebView app? Review itself is often quick, but WebView apps tend to go through more back-and-forth. Budget time for at least one rejection and resubmission when planning a launch date. ## Next step If you have a web app and want it on the App Store and Google Play without rebuilding it from scratch, [get in touch](/#contact). I handle the native layer and review process through my [Flutter app development service](/services/flutter-app-development). --- # Flutter App Development Cost for Businesses in 2026 URL: https://webdevang.com/blog/flutter-app-development-cost · Category: Mobile & DevOps · Updated: 2026-11-03 "How much will the app cost?" is usually the first question I get, and the honest answer is that Flutter app development cost depends less on Flutter than on everything around it: the backend, the integrations, payments, and what Apple and Google require before they publish you. This guide breaks down realistic ranges for 2026, the features that push budgets up, the running costs people forget, and how to scope a first version that ships without wasting money. The ranges are estimates from my experience, not quotes. ## TL;DR The biggest cost drivers are backend work, integrations, payments, real-time features and store compliance, not the screen count. If you already have a good web app, a Flutter wrapper with native sign-in, push and in-app purchase is often the cheapest credible way onto both stores. New apps with their own backend cost several times more. Budget for ongoing maintenance from day one. ## Key takeaways - Flutter app development cost depends far more on backend, integrations and store requirements than on the number of screens. - If you already have a solid web app, a Flutter wrapper with native features is often the cheapest credible path to both stores. - Payments, sign-in, push, offline support and real-time features are the line items that most often expand budgets. - Plan for ongoing costs: store fees, OS updates, backend hosting, monitoring and review cycles. ## Cost ranges by app type These are broad USD ranges for a capable freelancer or small team. Agencies in the US, UK and Australia often charge more; very low quotes usually skip testing, backend quality or store compliance. | App type | What it includes | Typical range (estimate) | Typical timeline | | --- | --- | --- | --- | | Web app wrapper | Flutter shell, native sign-in, push, IAP if needed | $3K to $15K | 3 to 6 weeks | | Focused utility app | Few screens, local storage, one or two native features | $5K to $20K | 1 to 2 months | | Business app with backend | Auth, roles, API, admin panel, notifications | $25K to $70K | 3 to 5 months | | Marketplace or multi-tenant SaaS | Payments, multiple user types, real-time, reporting | $60K and up | 5 months and up | The wrapper row assumes your web app already works well on mobile screens. If the web app needs a responsive redesign first, that work belongs in the budget too. ### Why Flutter saves money One codebase builds Android and iOS, and the [Flutter documentation](https://docs.flutter.dev) covers both from the same toolchain. You avoid writing every feature twice and keeping two teams in sync. Platform-specific code still exists for things like Apple sign-in or picture-in-picture, but plugins cover most of it. ## What actually drives the price When I scope an app, I price features, not screens. These are the line items that move the number most. 1. **Backend and data model.** Multi-tenant data, roles and permissions, reporting. Often 40 percent or more of total effort in my experience. 2. **Authentication.** Phone OTP, Google, Sign in with Apple, session handling across web and app. 3. **Payments.** Web payments, Apple and Google in-app purchase, server-side verification, subscription state. 4. **Notifications.** Push tokens per device, local reminders, deep links when a notification is tapped. 5. **Real-time features.** Chat, live status, presence. These need sockets and careful state handling. 6. **Offline support.** Caching and sync conflicts add significant complexity. 7. **Media.** Image uploads, video playback, PDFs, documents. 8. **Store compliance.** Privacy labels, account deletion, review cycles and resubmissions. 9. **Admin panel.** Someone has to manage users, plans and content. ### Native apps vs. a wrapper A full native-feeling Flutter app with its own UI gives the best experience but costs the most. A wrapper reuses your web UI and adds native features at the edges. For B2B tools and SaaS dashboards where users already know the web app, a wrapper is often the right first step. ## Running costs after launch The build is not the last invoice. Plan for these every year. | Item | Typical cost | Notes | | --- | --- | --- | | Apple Developer Program | Annual fee | Required to publish on iOS | | Google Play developer account | One-time fee | Required to publish on Android | | Backend hosting | Varies with usage | VM, database, file storage | | Crash reporting and analytics | Often free tier to start | Firebase Crashlytics is common | | Push notifications | Usually free via FCM | Server costs are minimal | | Maintenance retainer | Monthly | OS updates, SDK upgrades, store policy changes | Every year, Apple and Google ship new OS versions and raise minimum SDK targets. Apps that are not updated eventually get flagged or hidden, so maintenance is not optional. ## How I built this in practice Client Mitra is a good reference point because it shows the wrapper approach end to end. It is a solo build: a multi-tenant CRM for Indian photography studios with enquiries, bookings, payments, crew calendars, GST invoices, expenses and reports across about 30 app pages, an admin panel and 15 data models. Details are in [the Client Mitra case study](/work/clientmitra). The web app came first, built on Next.js with a Node/Express and MongoDB backend. Then I built one Flutter wrapper with `flutter_inappwebview` that ships native Android and iOS apps. The wrapper added native sign-in (including Sign in with Apple on iOS), Apple in-app purchase with server-side verification, FCM push plus local notifications and Crashlytics. Most of the product cost lived in the backend and web app; the mobile layer was a much smaller addition because the business logic already existed. For a fully native-style Flutter app, my open-source Peek video player is the other end of the spectrum: Flutter plus libVLC, picture-in-picture and lock-screen controls, all native UI. ## Common mistakes - Pricing by number of screens instead of by features and integrations. - Forgetting that iOS may require Sign in with Apple and in-app purchase. - Skipping the admin panel in the estimate, then building it in a hurry. - Treating launch as the end of the budget instead of planning maintenance. - Building a new native UI when a wrapper around a good web app would serve users fine. - Choosing the lowest quote without asking what testing and store support it includes. ## Internal links - [Flutter app development services](/services/flutter-app-development) - [Client Mitra web and mobile case study](/work/clientmitra) - [Hire a full stack developer in Australia](/hire/full-stack-developer-australia) - [Apple in-app purchase server verification](/blog/in-app-purchase-server-verification) - [FCM push notifications across web and mobile](/blog/fcm-push-notifications) - [Building a Flutter video player](/blog/flutter-video-player) - [Deploying Next.js on GCP](/blog/deploy-nextjs-on-gcp) ## FAQ ### How much does a Flutter app cost in 2026? As rough ranges, a wrapper around an existing web app with native features often lands in the low thousands to low five figures in USD, a standard business app with its own backend in the mid five figures, and complex platforms higher. Location, team model and scope move these numbers a lot. ### Is Flutter cheaper than building native iOS and Android apps? Usually, yes. One codebase serves both platforms, so you avoid building and maintaining most features twice. Native code is still needed for some platform features, but in my experience it is a small share of the work. ### What are the ongoing costs of a Flutter app? Expect Apple's annual developer fee, Google Play's one-time fee, backend hosting, crash reporting, push notifications and periodic updates for new OS versions and store policy changes. Maintenance is often budgeted as a monthly retainer. ### How long does it take to build a Flutter app? A focused wrapper around an existing web app can be ready in a few weeks, including store review. A new business app with backend and admin panel usually takes a few months, depending on features and integrations. ## Next step If you want a realistic estimate for your app, or advice on whether a wrapper or a full Flutter build fits your situation, [get in touch](/#contact). I scope and build mobile apps through my [Flutter app development service](/services/flutter-app-development). --- # Apple In-App Purchase Server Verification in Node.js URL: https://webdevang.com/blog/in-app-purchase-server-verification · Category: Mobile & DevOps · Updated: 2026-11-03 If your iOS app sells subscriptions, Apple will expect in-app purchase, and your business should expect in app purchase server verification. The app saying "purchase succeeded" is not proof. Your server needs to confirm the transaction came from Apple, belongs to your app and still grants access, then record that entitlement where every client can see it. I implemented this in Node.js for Client Mitra, where subscriptions are sold through Razorpay on the web and Apple in-app purchase on iOS. Here is the flow, the code shape and the edge cases that matter. ## TL;DR Send the signed transaction from the app to your server. Verify it with Apple's official App Store Server Library, check the bundle ID, product and expiry, and save the entitlement against the account. Subscribe to App Store Server Notifications V2 so renewals, refunds and expirations update automatically. Let clients read plan status from your API, never from local purchase state. ## Key takeaways - In app purchase server verification means your backend, not the app, decides whether a purchase is real and what the user is entitled to. - Apple's App Store Server Library for Node verifies signed transactions and notifications against Apple's certificate chain. - App Store Server Notifications keep renewals, refunds and expirations in sync without waiting for the user to open the app. - Store one subscription state per account so web payments and Apple purchases enable the same features. ## How Apple purchase verification works today With StoreKit 2, each transaction is a JWS: a signed payload containing fields like `transactionId`, `originalTransactionId`, `productId`, `bundleId`, `purchaseDate`, `expiresDate` and `environment`. Your server verifies the signature chain back to Apple's root certificate, then trusts the decoded fields. The older `verifyReceipt` endpoint is deprecated. Apple's [App Store Server API documentation](https://developer.apple.com/documentation/appstoreserverapi) covers the replacement, and the official `@apple/app-store-server-library` package for Node handles signature verification and API calls. ### The pieces you need | Piece | Where it comes from | Used for | | --- | --- | --- | | Apple root certificates | Apple PKI site | Verifying signed data | | In-app purchase key (`.p8`), key ID, issuer ID | App Store Connect | Calling the App Store Server API | | Bundle ID and app Apple ID | App Store Connect | Binding verification to your app | | Notification URL | Your server | Receiving renewals, refunds, expirations | ## Verifying a transaction in Node.js The app completes the purchase and sends the signed transaction to an authenticated endpoint such as `POST /api/billing/apple/verify`. The server code looks roughly like this. ```js import { SignedDataVerifier, Environment } from '@apple/app-store-server-library'; const verifier = new SignedDataVerifier( appleRootCerts, // array of Buffers loaded at startup true, // enable online revocation checks Environment.PRODUCTION, // or SANDBOX for test builds process.env.APPLE_BUNDLE_ID, Number(process.env.APPLE_APP_ID) ); const tx = await verifier.verifyAndDecodeTransaction(signedTransaction); ``` After decoding, apply your own business checks before granting anything. 1. Confirm `tx.bundleId` matches your app and `tx.productId` is a product you sell. 2. Check `tx.expiresDate` is in the future and `tx.revocationDate` is not set. 3. Look up `tx.originalTransactionId`; if it is already linked to a different account, reject or flag it. 4. Upsert a subscription record: `provider: "apple"`, `originalTransactionId`, `productId`, `expiresAt`, `status`. 5. Map the product to your internal plan and update the account's entitlement. 6. Return the new plan status to the app. ### Handle sandbox and production TestFlight and review builds use the sandbox. A common pattern is to try production verification first and fall back to a sandbox verifier when the environment field says so. Store the environment on every record so test purchases never upgrade real accounts or count in reporting. ### Use appAccountToken When starting a purchase, the app can pass an `appAccountToken` (a UUID you generate per account). It comes back inside the signed transaction, which makes linking purchases to the right account much more reliable than matching by device. ## Keeping subscriptions in sync with notifications Verification at purchase time is only half the job. Subscriptions renew, fail billing, get refunded and expire while the app is closed. App Store Server Notifications V2 tell your server about each event. Configure the production and sandbox URLs in App Store Connect, then on each request verify the payload with `verifier.verifyAndDecodeNotification(signedPayload)`. The decoded notification includes a `notificationType` and a signed transaction you verify the same way. | Notification type | What to do | | --- | --- | | `SUBSCRIBED` | Create or activate the subscription | | `DID_RENEW` | Extend `expiresAt` | | `DID_FAIL_TO_RENEW` | Mark billing issue, keep grace period if enabled | | `EXPIRED` | Downgrade the account to the free plan | | `REFUND` | Revoke access and log the refund | | `DID_CHANGE_RENEWAL_STATUS` | Record whether auto-renew is on | Make the handler idempotent by storing each `notificationUUID`, and respond with a 200 quickly. Also run a daily job that rechecks subscriptions near expiry using the App Store Server API, in case a notification was missed. ## How I built this in practice Client Mitra is a solo build: a multi-tenant CRM for Indian photography studios, with a Next.js web app, Node/Express API and MongoDB. It ships native Android and iOS apps through one Flutter wrapper around the web app. The full story is in [the Client Mitra case study](/work/clientmitra). On the web, subscriptions run through Razorpay. On iOS, App Store review required an in-app purchase paywall, native Sign in with Apple and server-side verification. I implemented verification with `@apple/app-store-server-library` in the Node backend, so the Flutter shell only passes the signed transaction to the API and waits for the updated plan. The key design decision was one subscription state per business, regardless of where it was bought. Plan-gated features read that state from the API on web and in the app, so a studio that pays through Apple sees the same features on the web dashboard. The backend already runs node-cron for reminders, which makes it a natural home for a scheduled recheck job like the one described above. ## Common mistakes - Enabling paid features based on the app's local purchase result without server verification. - Building new code on the deprecated `verifyReceipt` endpoint. - Not configuring server notifications, so refunds and expirations never downgrade the account. - Ignoring the sandbox environment, letting test purchases look like real revenue. - Linking purchases by device instead of by account, which breaks on reinstall or a new phone. - Keeping separate plan logic for web and iOS instead of one server-owned entitlement. ## Internal links - [Flutter and mobile app development services](/services/flutter-app-development) - [Client Mitra case study](/work/clientmitra) - [Hire a full stack developer in the UK](/hire/full-stack-developer-uk) - [FCM push notifications across web and mobile](/blog/fcm-push-notifications) - [Building a Flutter video player](/blog/flutter-video-player) - [Deploying Next.js on GCP](/blog/deploy-nextjs-on-gcp) - [MongoDB security hardening](/blog/mongodb-security-hardening) ## FAQ ### Why do I need server-side verification for in-app purchases? A purchase result reported by the app can be faked or replayed on a modified device. Verifying the signed transaction on your server confirms it came from Apple, belongs to your app and is still valid before you grant access to anything. ### Is Apple's verifyReceipt endpoint still the right approach? Apple has deprecated the old verifyReceipt flow in favor of signed transactions and the App Store Server API. New builds should verify JWS transactions, for example with the official App Store Server Library. ### How do I handle subscription renewals and refunds? Configure App Store Server Notifications V2 to call an endpoint on your server. Verify each signed notification, then update the subscription's expiry, status or revocation in your database based on the notification type. ### Can one subscription work across web and iOS? Yes, if your server owns the entitlement. Record purchases from both Apple and your web payment provider against the same account or business, and have every client ask your API what plan is active. ## Next step If you need iOS subscriptions that pass review and stay in sync with your web billing, [get in touch](/#contact). I build this end to end through my [Flutter app development service](/services/flutter-app-development). --- # FCM Push Notifications Across Web and Mobile URL: https://webdevang.com/blog/fcm-push-notifications · Category: Mobile & DevOps · Updated: 2026-11-03 Notifications are where a business app proves it is useful outside the moment someone opens it. A studio owner hears about a new enquiry, a crew member gets tomorrow's shoot details, a client knows their invoice is ready. FCM push notifications let one backend deliver all of that to web browsers, Android phones and iPhones through a single API. I use Firebase Cloud Messaging in Client Mitra, a photography studio CRM with web, Android and iOS apps, and in Sublet, an open-source classifieds board. This post covers the architecture, token management, push versus local notifications, and the details that decide whether people keep notifications switched on. ## TL;DR Register each device with FCM, send its token to your backend, and store tokens per user and per device. Send from Node.js with the Firebase Admin SDK, targeting a user's tokens and cleaning up any FCM reports as invalid. Use local notifications for scheduled reminders and push for server events. Include a deep link in every message so tapping it opens the right screen. ## Key takeaways - FCM push notifications let one backend reach web browsers, Android and iOS through a single API. - Store device tokens per user and per device, refresh them on every app start, and delete tokens FCM reports as invalid. - Use push for server events and local notifications for scheduled reminders the device already knows about. - Every notification should deep link to the exact screen it is about, or users learn to ignore them. ## How FCM works across platforms FCM sits between your server and each platform's delivery channel. The [Firebase Cloud Messaging docs](https://firebase.google.com/docs/cloud-messaging) cover the setup per platform; here is the practical picture. | Platform | Client setup | Delivery path | Gotchas | | --- | --- | --- | --- | | Android | Firebase SDK, notification channel | FCM directly | Battery optimization on some devices, Android 13+ permission prompt | | iOS | Firebase SDK, APNs key uploaded to Firebase | FCM to APNs | Permission prompt timing, background modes | | Web | Firebase JS SDK, service worker, VAPID key | FCM to browser push service | Permission must come from a user action; iOS Safari needs the site added to the home screen | ### Device tokens Each app install or browser gets an FCM registration token. Tokens change: after reinstalling, clearing data, restoring a phone, or sometimes for no visible reason. Treat them as disposable and refresh on every launch. ### Message types A **notification message** has a title and body that the OS displays when the app is in the background. A **data message** carries key-value pairs your code handles. Most of my sends include both: a visible notification plus data like `type: "booking"` and `url: "/bookings/abc123"` for routing. ## Backend design: tokens, targeting and sending ### Store tokens properly I keep a `DeviceToken` collection rather than a single token field on the user, because one person often uses a phone, a tablet and a browser. 1. On login and on every app start, the client sends `{ token, platform, deviceId, appVersion }` to an authenticated endpoint. 2. Upsert by `token`, setting `userId`, `businessId`, `platform` and `lastSeenAt`. 3. On logout, delete that device's token so the next user of the device does not get your notifications. 4. When a send fails with an unregistered or invalid-token error, delete the token immediately. 5. Periodically remove tokens not seen in a long time. ### Send with Firebase Admin From Node.js, the Firebase Admin SDK's `messaging().sendEachForMulticast()` takes up to 500 tokens and returns a per-token result, which is exactly what you need for cleanup. Build a small `notifyUser(userId, { title, body, url, type })` helper that loads the user's tokens, sends, and prunes failures. Product code calls the helper and never touches FCM directly. ### Respect roles and preferences In a multi-user business app, not everyone should get every alert. Decide recipients by role and by user preference: owners get payment alerts, crew get schedule changes, staff who cannot see money never get payment amounts in a notification body. The lock screen is a public surface, so keep sensitive figures out of it. ## Push vs. local notifications Not every reminder needs a server round trip. | Use case | Best choice | Why | | --- | --- | --- | | New enquiry or booking | Push | Server knows first | | Payment received | Push | Event happens on the server | | Reminder 1 hour before a shoot | Local, with push backup | Device knows the schedule, works offline | | Daily task digest | Push from a cron job | Server builds the summary | | Chat message | Push | Other user triggers it | In Flutter, local notifications are scheduled on the device with a plugin, and they fire even with no connection. For critical reminders, I pair them with a server-side cron push so a reinstall or a new device does not silently lose the reminder. ### Deep links Every message carries a `url`. When the user taps it, the app routes there. In a WebView-based app, the native shell receives the tap and tells the WebView to navigate to that path, so one routing scheme works on web and mobile. ## How I built this in practice Client Mitra is my solo build: a multi-tenant CRM for photography studios and creative businesses, with enquiries, bookings, crew calendars for multi-day weddings, tasks, GST invoices and payments. It runs as a Next.js web app with a Node/Express and MongoDB backend, and ships native Android and iOS apps through one Flutter wrapper using `flutter_inappwebview`. The details are in [the Client Mitra case study](/work/clientmitra). The Flutter shell handles FCM push plus local notifications natively, and the backend sends through Firebase Admin. node-cron drives scheduled reminders from the server. Because roles matter (owner, manager and staff, with staff unable to see money), recipients and message content follow the same permission rules as the app itself. The shell also runs Crashlytics, which helps diagnose notification-handling crashes on specific devices. For context on how studios use these alerts, see the [photography studios industry page](/industries/photography-studios). In Sublet, my open-source classifieds board for sharing spare Claude and ChatGPT capacity, FCM delivers chat notifications alongside Firebase Auth, while 1:1 chat itself runs on Socket.IO with REST polling as a fallback on serverless hosting. ## Common mistakes - Storing a single token per user, so only the last device ever receives notifications. - Never deleting invalid tokens, which slows sends and clutters logs. - Asking for notification permission on first launch, before the user sees any value. - Putting sensitive amounts or personal details in notification text visible on the lock screen. - Sending notifications with no deep link, dropping users on the home screen. - Forgetting to upload an APNs key, then wondering why iOS gets nothing. ## Internal links - [Flutter app development services](/services/flutter-app-development) - [Client Mitra case study](/work/clientmitra) - [Software for photography studios](/industries/photography-studios) - [Building a Flutter video player](/blog/flutter-video-player) - [Deploying Next.js on GCP](/blog/deploy-nextjs-on-gcp) - [MongoDB security hardening](/blog/mongodb-security-hardening) - [GitHub Actions self-hosted runner setup](/blog/github-actions-self-hosted-runner) ## FAQ ### Can FCM send push notifications to iOS devices? Yes. FCM delivers to iOS through Apple Push Notification service. You upload an APNs authentication key to your Firebase project, and FCM handles the handoff to Apple. ### Does FCM work for web push notifications? Yes. FCM supports web push in browsers that implement the Push API, using a service worker and a VAPID key. Users must grant notification permission in the browser first. ### What is the difference between push and local notifications? Push notifications are sent from your server through FCM when something happens, like a new booking. Local notifications are scheduled on the device itself, which suits reminders the app already knows about, and they work without a network connection. ### Why are my FCM notifications not arriving? Common causes are stale or invalid tokens, missing notification permission, missing APNs configuration for iOS, battery optimization on some Android devices, or sending data-only messages that the app does not handle in the background. ### Is FCM free to use? Firebase Cloud Messaging itself has no per-message charge at the time of writing. Your costs are the backend that decides when to send and any other Firebase services you use. ## Next step If your app needs notifications that people actually keep switched on, across web, Android and iOS, [get in touch](/#contact). I build this as part of my [Flutter app development service](/services/flutter-app-development). --- # Building an Android Video Player With Flutter and libVLC URL: https://webdevang.com/blog/flutter-video-player · Category: Mobile & DevOps · Updated: 2026-11-03 A Flutter video player sounds like a weekend toy until you open a real folder of downloaded files. MKV containers, AC3 audio, two subtitle tracks, a 4K HEVC clip and an old AVI all sit next to each other, and the default plugin chokes on half of them. I built Peek, an open-source Android video player, in a single day with Flutter and libVLC. This post covers the decisions that mattered: which playback engine to pick, how to wire picture-in-picture and lock-screen controls, how to handle subtitles and audio tracks, and the native library alignment problem that nearly blocked the build. ## TL;DR Use the official video_player package when you control the media (streaming MP4 or HLS from your own backend). Use a libVLC-based plugin when users bring their own files. Budget a little native Android code for picture-in-picture and MediaSession, and check that every native plugin you ship supports 16KB memory pages before you target modern devices. ## Key takeaways - The stock video_player plugin is fine for streaming known formats, but local files with odd codecs need a libVLC-based engine. - Picture-in-picture and lock-screen controls are native Android features, so plan a small amount of platform code from day one. - Android's 16KB memory page requirement can break native plugins, and vendoring a compliant build is often the fastest fix. - Resume position, history and gesture controls are what make a player feel finished, and they are cheap to build in Flutter. ## Choosing the playback engine The first decision shapes everything else. Flutter does not decode video itself; every option is a bridge to a native engine. | Option | Engine underneath | Strengths | Weak spots | |---|---|---|---| | video_player (official) | ExoPlayer on Android, AVPlayer on iOS | Small, well maintained, great for HLS/MP4 | Limited container and codec coverage for local files | | libVLC plugin | VLC's libVLC | Plays almost anything, embedded subtitle and audio tracks | Larger APK, native .so files to manage | | media_kit style wrappers | libmpv | Wide format support, desktop friendly | Another native dependency chain to keep aligned | For a player meant for a user's own files, codec coverage beats APK size. I went with libVLC because it reads embedded tracks directly, which means subtitle and audio switching come almost for free. If you are building a course app or an OTT client where you encode the media yourself, the trade flips. Encode to H.264/AAC in HLS and use the official plugin. The [video_player documentation on pub.dev](https://pub.dev/packages/video_player) covers that path well. ## Native features you cannot skip on Android A Flutter video player that stops when the user leaves the app feels broken. Two native features fix that. ### Picture-in-picture PiP is an activity-level feature. The steps I follow: 1. Add `android:supportsPictureInPicture="true"` and the right `configChanges` to the main activity in the manifest. 2. Expose a method channel call such as `enterPip(aspectRatio)` that builds `PictureInPictureParams` with the video's aspect ratio. 3. Trigger it on `onUserLeaveHint` so pressing Home while playing drops into PiP automatically. 4. Listen for PiP mode changes on the Flutter side and hide controls, overlays and the app bar while in the small window. The last step is the one people forget. If your controls stay visible, the PiP window shows a cramped toolbar instead of the video. The [Android picture-in-picture guide](https://developer.android.com/develop/ui/views/picture-in-picture) explains the activity lifecycle details. ### MediaSession and lock-screen controls MediaSession is how Android shows play, pause and seek on the lock screen, in the notification shade and on Bluetooth headsets. Without it, headphone buttons do nothing. I register a session when playback starts, push metadata (title, duration) and map the callbacks back to the libVLC controller. Keep the playback state in one place in Dart so the lock screen, the in-app controls and the PiP window never disagree. ## Subtitles, audio tracks and gestures This is where libVLC pays for itself. **Subtitles.** Embedded tracks in MKV files show up as a list from the engine. For external files, Peek loads SRT and VTT sidecars, either picked manually or matched by filename. A simple rule works: if `movie.mkv` sits next to `movie.srt` or `movie.en.vtt`, offer it automatically. **Audio tracks.** Dual-audio files are common in the files people actually keep on their phones. The engine exposes track IDs and language tags, so the UI is a simple bottom sheet. **Gestures.** Users expect the conventions from popular players: - Horizontal drag to seek, with a preview of the target time. - Vertical drag on the right half for volume, left half for brightness. - Double-tap left or right to jump back or forward ten seconds. - Pinch to switch between fit and fill. Gesture code in Flutter is mostly a `GestureDetector` with careful thresholds so a seek drag does not also change volume. Lock the axis after the first few pixels of movement. **Resume and history.** Store the last position per file path, plus a recent list. When a file opens, seek to the saved position if it is more than a few seconds in and not near the end. ## The 16KB page size problem Newer Android devices can run with 16KB memory pages instead of 4KB. Native libraries that were linked assuming 4KB alignment can fail to load on those devices, and Google Play is moving toward requiring 16KB support for apps that ship native code. A video player is almost all native code underneath. The libVLC plugin I started with pulled in prebuilt `.so` files that were not aligned for 16KB pages. Waiting for an upstream release was not an option for a one-day build, so I vendored a 16KB-page-safe version of the plugin into the repo and pointed the pubspec at the local path. My checklist for any Flutter app with native dependencies: 1. List every plugin that ships `.so` files (video, image processing, crypto, ML). 2. Check each one's changelog or issues for 16KB page support. 3. Build a release APK and inspect alignment of the native libraries before shipping. 4. Vendor or fork when upstream lags, and note the reason in the README so it gets revisited. I also set min SDK 24, which keeps the device range wide without carrying very old API workarounds. ## How I built this in practice Peek is a real, open-source project: Flutter on top of libVLC, using the vendored 16KB-page-safe plugin, with picture-in-picture, MediaSession lock-screen controls, SRT/VTT subtitles, audio track switching, gesture controls, resume and history, and min SDK 24. The full write-up is in [the Peek case study](/work/peek). It went from empty repo to a usable app in a day because the scope was ruthless: no backend, no accounts, no casting. Every hour went into the things that make playback feel right: PiP that triggers on Home, headphone buttons that work, and files that resume where you left them. The same approach carries into client apps. In Client Mitra I shipped Android and iOS apps through one Flutter wrapper with native sign-in, in-app purchase, push and Crashlytics added only where the platform demanded it. Flutter for the UI, small native pieces only where needed, is a pattern that keeps maintenance low. ## Common mistakes - Picking the official plugin for a local-files player, then discovering half the user's library will not play. - Leaving overlays visible in picture-in-picture mode, so the small window shows controls instead of video. - Skipping MediaSession, which makes Bluetooth and lock-screen buttons silently do nothing. - Shipping native libraries without checking 16KB page alignment on newer devices. - Letting seek and volume gestures fire together because the drag axis is never locked. ## Internal links - [Flutter app development services](/services/flutter-app-development) - [Peek: open-source Flutter and libVLC video player](/work/peek) - [Hire a full stack developer in India](/hire/full-stack-developer-india) - [How to deploy Next.js on GCP with PM2 and Nginx](/blog/deploy-nextjs-on-gcp) - [MongoDB security hardening checklist](/blog/mongodb-security-hardening) - [GitHub Actions self-hosted runner setup](/blog/github-actions-self-hosted-runner) - [Azure data residency for Australian apps](/blog/azure-data-residency-australia) ## FAQ ### Which package should I use for a Flutter video player? For streaming common formats like MP4 and HLS, the official video_player package is enough. For local files with MKV containers, unusual audio codecs or embedded subtitle tracks, a libVLC-based plugin handles far more formats without extra work. ### Does Flutter support picture-in-picture on Android? Not out of the box. You enable PiP in the Android manifest, call the platform API from a small method channel or plugin, and adjust your Flutter layout when the activity shrinks into the PiP window. ### What is the Android 16KB page size issue? Newer Android devices can use 16KB memory pages, and native libraries compiled assuming 4KB alignment can fail to load. Any plugin shipping .so files needs builds aligned for 16KB pages, which is why I vendored a compliant libVLC plugin. ### How long does it take to build a Flutter video player app? A focused player with PiP, subtitles, gestures and resume took me a day because the scope was tight and the engine was mature. A player with DRM, casting, downloads and a content backend is a multi-week project. ## Next step If you need a media app, or any Flutter app that has to behave like a proper native citizen on Android and iOS, I can help you scope it and ship it. Look at my [Flutter app development services](/services/flutter-app-development) and [get in touch](/#contact) with what you are building. --- # Deploy Next.js on GCP With PM2 and Nginx URL: https://webdevang.com/blog/deploy-nextjs-on-gcp · Category: Mobile & DevOps · Updated: 2026-11-03 If you have searched for how to "deploy nextjs on gcp", you have probably seen five different answers: App Engine, Cloud Run, Firebase Hosting, GKE and plain VMs. They all work. The right one depends on what else runs next to your Next.js app. My default for SaaS products with a Node API, Socket.IO and background jobs is a Compute Engine VM running PM2 behind Nginx. It is what I use on Antoc's infrastructure in asia-south1. This guide walks through the exact setup, the decisions behind it, and when I would pick something else. ## TL;DR Create a Compute Engine VM in the region nearest your users, reserve a static IP, install Node and Nginx, run `next start` and your API under PM2, and let Nginx handle TLS and proxying. Deploy by pulling, building and reloading PM2. Choose Cloud Run instead if the app is stateless and traffic is spiky. ## Key takeaways - A single Compute Engine VM with PM2 and Nginx is a cheap, predictable way to run Next.js plus a Node API and background workers. - Pick the region closest to your users, such as asia-south1 for India, because latency matters more than raw VM size. - Nginx should handle TLS, compression, request size limits and WebSocket upgrades so the Node processes only serve the app. - Cloud Run is better for spiky, stateless traffic, while a VM wins when you have Socket.IO, cron jobs and long-running workers. ## VM or Cloud Run: picking the target Before touching a terminal, be honest about the workload. | Factor | Compute Engine VM + PM2 | Cloud Run | |---|---|---| | Socket.IO / long connections | Native, no limits beyond the box | Possible, but request timeouts and instance churn complicate it | | Cron jobs and workers | Run as extra PM2 apps | Needs Cloud Scheduler + separate jobs | | Headless browsers (Playwright) | Works with Xvfb if needed | Heavier images, cold starts hurt | | Cost at steady traffic | Flat monthly price | Can be higher if always warm | | Spiky or near-zero traffic | Paying for idle | Scales to zero | | Ops effort | You patch the OS | Google manages the runtime | For a CRM with realtime notifications, reminder crons and webhook consumers, the VM column wins almost every row. For a marketing site or a stateless API, Cloud Run is less work. Google's [Compute Engine documentation](https://cloud.google.com/compute/docs) covers machine types and regions in detail. ## Step-by-step VM setup This is the sequence I follow on a fresh Ubuntu LTS VM. 1. **Create the VM** in your users' region (asia-south1 for India). Start with 2 vCPU and 4 to 8 GB RAM. Use a balanced persistent disk of at least 30 GB so builds and logs do not fill it. 2. **Reserve a static external IP** and attach it. Ephemeral IPs change on stop/start and break DNS. 3. **Firewall rules**: allow 80 and 443 from anywhere. Restrict SSH to your IP range or use IAP tunneling. Never expose the app port (3000) or the database port publicly. 4. **Create a deploy user** without root, add your SSH key, and disable password login. 5. **Install Node** through nvm or NodeSource, pinned to the same major version you use locally and in CI. 6. **Install PM2** globally and run `pm2 startup systemd` so processes come back after a reboot. 7. **Install Nginx and Certbot**, point DNS at the static IP, and issue certificates with `certbot --nginx`. 8. **Clone, install, build**: `npm ci`, then `npm run build`. Store secrets in an `.env` file readable only by the deploy user, or pull them from Secret Manager at boot. 9. **Start with an ecosystem file** and save the process list with `pm2 save`. A minimal `ecosystem.config.js` looks like this: ```js module.exports = { apps: [ { name: 'web', script: 'node_modules/next/dist/bin/next', args: 'start -p 3000', instances: 2, exec_mode: 'cluster' }, { name: 'api', script: 'server/index.js', env: { PORT: 4000 } }, { name: 'cron', script: 'workers/cron.js', instances: 1 } ] }; ``` Keep cron workers at one instance. Two copies of a reminder job means every customer gets two reminders. ## Nginx configuration that matters Most Nginx tutorials stop at `proxy_pass`. These are the extra lines that prevent real production problems: - `proxy_set_header Upgrade $http_upgrade;` and `Connection "upgrade"` on the Socket.IO location, or realtime silently falls back to polling. - `client_max_body_size` set deliberately (for example 10m) so file uploads do not fail with a 413. - `gzip on` for text types, and long cache headers on `/_next/static/`, which is content-hashed and safe to cache for a year. - `proxy_read_timeout` raised for endpoints that legitimately run long, such as report exports. - Separate `server` blocks for the app domain and the API domain, so each can have its own limits and logs. Test with `nginx -t` before every reload. A typo in a config file takes down every site on the box. ## Logs, monitoring and deploys A VM you cannot see into is a liability. My baseline: - **PM2 logs** rotated with `pm2-logrotate` so disks do not fill. - **Sentry** in both the Next.js app and the Node API for exceptions with stack traces. - **Uptime checks** from outside GCP hitting a lightweight `/health` route. - **Disk and memory alerts** through Cloud Monitoring. For deploys, the simplest reliable flow is a GitHub Actions job that SSHes in (or runs on a self-hosted runner on the VM), pulls the branch, runs `npm ci && npm run build`, and calls `pm2 reload ecosystem.config.js`. `reload` restarts cluster instances one at a time, so users do not see an outage during the swap. ## How I built this in practice On [Antoc](/work/antoc), the real-estate CRM I work on at Passdn Technologies, the stack runs on GCP VMs in asia-south1 with PM2 and Nginx. The product serves 100+ real estate firms in India and around 300K leads, so most traffic comes from Indian users and Mumbai is the obvious region. The VM approach fits because Antoc is more than a web app. There is a Next.js client, a Node/Express API, Socket.IO for realtime updates, scheduled WhatsApp nurture drips, and webhook receivers for Meta lead ads and Google Ads. A separate GCP VM runs the government tender intelligence bot, which drives Playwright inside Xvfb to scrape portals. None of that maps cleanly to scale-to-zero containers. Sentry is wired into both client and server, and an automated SEO blog pipeline runs on a GitHub Actions self-hosted runner. The lesson from running it: keep each VM's job narrow and its PM2 process list readable, and you can reason about the whole system at a glance. ## Common mistakes - Building on a tiny VM and running out of memory during `next build`, then blaming Next.js. - Leaving port 3000 open in the firewall so users bypass Nginx and TLS entirely. - Running cron workers in cluster mode, which duplicates every scheduled job. - Forgetting `pm2 startup` and `pm2 save`, so a routine reboot leaves the site down. - Putting the database in another region from the app and adding latency to every query. - Using `pm2 restart` instead of `pm2 reload` for cluster apps and causing brief outages on each deploy. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [Antoc real-estate CRM case study](/work/antoc) - [Hire a full stack developer in the USA](/hire/full-stack-developer-usa) - [MongoDB security hardening checklist](/blog/mongodb-security-hardening) - [Setting up a GitHub Actions self-hosted runner](/blog/github-actions-self-hosted-runner) - [Azure data residency for Australian compliance apps](/blog/azure-data-residency-australia) - [Production Node.js on AWS EC2](/blog/nodejs-aws-ec2-production) ## FAQ ### Is a VM or Cloud Run better for Next.js on GCP? Cloud Run is great for stateless apps with spiky traffic and no background work. A VM is simpler and cheaper when you also run Socket.IO, cron jobs, queues or headless browsers alongside the web app. ### What machine size do I need for a Next.js app on Compute Engine? Many small production apps run comfortably on a 2 vCPU, 4 to 8 GB VM. The build step is usually the memory peak, so either size for the build or build in CI and ship the output. ### Do I need Nginx if PM2 is already running Next.js? Yes, in practice. PM2 keeps the Node process alive, while Nginx terminates TLS, compresses responses, caches static assets and proxies WebSocket upgrades. They do different jobs. ### How do I get HTTPS on a GCP VM? Point your domain's A record at a static external IP, open ports 80 and 443 in the VPC firewall, and use Certbot with the Nginx plugin to issue and auto-renew a Let's Encrypt certificate. ### Which GCP region should I choose for an Indian user base? asia-south1 in Mumbai is the usual choice for India. Put the database in the same region so every API call does not cross a continent. ## Next step If you want your Next.js product running on GCP with sane deploys, monitoring and security from day one, I can set it up or review what you have. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # MongoDB Security Hardening: A Production Checklist URL: https://webdevang.com/blog/mongodb-security-hardening · Category: Mobile & DevOps · Updated: 2026-11-03 MongoDB security hardening is rarely exciting work, and that is why it gets postponed. The database starts on a developer's laptop with no password, gets deployed with the same defaults, and stays that way until the data inside it becomes valuable. This is the checklist I work through before calling a MongoDB deployment production-ready. It covers the obvious layers (authentication and network access) and the less obvious one that causes a lot of real damage: application code that sends a destructive query with the wrong filter. ## TL;DR Enable authentication, keep MongoDB off the public internet, use TLS, give every app its own least-privilege user, and store credentials as secrets. Then protect the data from your own code by validating filters on bulk writes, and prove your backups work by restoring them on a schedule. ## Key takeaways - Authentication must be on and the database must never be reachable from the public internet, regardless of how strong the password is. - Give each application its own database user with only the roles it needs, and keep admin credentials out of app servers. - Many real data-loss risks come from your own code, so guard bulk updates and deletes against empty or malformed filters. - Backups only count if you have restored one recently, so schedule a restore drill alongside the backup job. ## Layer 1: authentication and network access These two controls stop most opportunistic attacks. Automated scanners constantly look for open database ports, so an unauthenticated MongoDB on a public IP is a matter of when, not if. **Authentication.** On self-hosted MongoDB, set `security.authorization: enabled` in `mongod.conf`, create an admin user, then restart. On Atlas it is on by default. Use SCRAM-SHA-256 or x.509 certificates. **Network.** The database should only accept connections from your app servers. - Set `net.bindIp` to localhost and the private interface, never `0.0.0.0` unless a firewall sits in front. - Use cloud firewall rules or security groups that allow port 27017 only from app server IPs or a private subnet. - On Atlas, keep the IP access list tight and avoid `0.0.0.0/0`, even "temporarily". - Prefer private networking (VPC peering or private endpoints) between app and database. **Encryption in transit.** Turn on TLS for client connections and replica set traffic. Atlas enforces it. Self-hosted clusters need certificates and `net.tls.mode: requireTLS`. The official [MongoDB security checklist](https://www.mongodb.com/docs/manual/administration/security-checklist/) is worth reading alongside this one. ## Layer 2: users, roles and secrets Once only your servers can connect, limit what each connection can do. | User | Roles | Used by | |---|---|---| | `app_api` | `readWrite` on the app database only | Node API servers | | `app_worker` | `readWrite` on the app database only | Cron jobs, queue workers | | `reporting_ro` | `read` on the app database | BI tools, analysts | | `backup_svc` | `backup` | Backup job | | `dba_admin` | `userAdminAnyDatabase`, `clusterAdmin` | Humans, rarely, from a bastion | Separate users for API and workers seem fussy until you need to rotate one credential without restarting everything. A read-only user for reporting means a spreadsheet integration cannot accidentally write. **Secrets handling:** 1. Keep connection strings out of the repo, including `.env.example` files with real hosts. 2. Store them in your cloud's secret manager or a locked-down env file readable only by the service user. 3. Rotate passwords when someone with access leaves, and on a regular schedule. 4. Never log full connection strings. Sentry breadcrumbs and error messages are common leak paths. ## Layer 3: protect the data from your own code This is the layer most checklists skip. A perfectly locked-down database can still lose a collection to one bad `updateMany`. ### Guard bulk operations Consider `Lead.updateMany({ assignedTo: req.body.userId }, { $set: { status: 'lost' } })`. If `userId` is undefined, some drivers and ODM settings can turn that into a filter that matches far more documents than intended. Defensive patterns: - Wrap `updateMany`, `deleteMany` and `bulkWrite` in a helper that rejects empty filters (`{}`) and filters where every value is `undefined` or `null`. - Always include the tenant key (for example `businessId`) in multi-tenant filters, and assert it is present in the helper. - Run `countDocuments(filter)` first for destructive operations and refuse if the count exceeds a sane threshold without an explicit `force` flag. - Log the filter, matched count and modified count for every bulk operation. ### Validate input before it reaches a query - Enable Mongoose `strictQuery` so unknown fields in filters are dropped. - Reject objects where you expect strings, which blocks operator injection like `{ "$ne": null }` in a login form. - Validate IDs with `isValidObjectId` before querying. ### Indexes are a security control too An unindexed query on a large collection can pin CPU and make the whole app unavailable. Add indexes for every hot filter and sort, and use `explain()` to confirm they are used. Slow queries are a denial-of-service risk you created yourself. ## Layer 4: backups, monitoring and patching 1. **Automated backups**: Atlas continuous backup, or scheduled `mongodump` / filesystem snapshots for self-hosted clusters, stored in a separate account or bucket. 2. **Restore drills**: restore last night's backup into a staging cluster monthly and run a smoke test against it. 3. **Audit and alerts**: alert on failed authentication spikes, new users or roles, and unusual connection sources. 4. **Patching**: track MongoDB and driver releases and upgrade on a planned cadence rather than once something breaks. 5. **Disable what you do not use**: server-side JavaScript, HTTP interfaces on old versions, and unused default databases. ## How I built this in practice On [Antoc](/work/antoc), the real-estate CRM used by 100+ firms in India, the MongoDB database had to be scaled and hardened as the number of managed leads grew past 300K. The work covered all of the layers above rather than any single fix. In practice that meant three things. First, indexes on the queries that power lead lists, pipelines and reports, so heavy filters stayed fast as data grew. Second, safe bulk operations with filter validation, because lead imports from Meta lead ads, Google Sheets and portals plus auto-assignment rules generate a lot of bulk writes, and a missing filter value must never touch the wrong businesses. Third, authentication and network restrictions so the database is only reachable from the application servers. The multi-tenant angle matters. In both Antoc and Client Mitra, every query is scoped by business, and in Client Mitra tenant isolation lives in middleware so a route cannot forget it. Treat the tenant key as part of your security model, not just your data model. ## Common mistakes - Opening the database to `0.0.0.0/0` during a deploy and never closing it. - Running the app with an admin user because "it was easier during setup". - Passing raw request bodies into filters, which allows operator injection. - Allowing `deleteMany` or `updateMany` with filters built from possibly undefined values. - Taking backups for months without ever restoring one. - Committing connection strings to the repo or printing them in error logs. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [How Antoc scaled MongoDB for 300K+ leads](/work/antoc) - [Hire a full stack developer in Dubai](/hire/full-stack-developer-dubai) - [GitHub Actions self-hosted runner setup and gotchas](/blog/github-actions-self-hosted-runner) - [Azure data residency for Australian compliance apps](/blog/azure-data-residency-australia) - [Production Node.js on AWS EC2 checklist](/blog/nodejs-aws-ec2-production) - [Building a self-hosted LAN file transfer app](/blog/lan-file-transfer) ## FAQ ### What is the first step in MongoDB security hardening? Turn on authentication and close the database to the public internet. Bind MongoDB to private interfaces, restrict access with firewall rules or an IP access list, and only then worry about finer controls. ### Is MongoDB Atlas more secure than self-hosting? Atlas gives you encryption, TLS, backups and access lists by default, which removes many easy mistakes. Self-hosting can be just as secure, but you own every setting, patch and backup. ### How do I stop a bad query from wiping a collection? Wrap bulk updates and deletes in a helper that rejects empty or missing filters, logs the filter and matched count, and requires an explicit flag for operations above a threshold. Mongoose's strictQuery setting also helps by dropping unknown filter fields. ### Should application users have the readWrite role on all databases? No. Scope each app user to the one database it needs, and create separate read-only users for analytics or reporting tools so a leaked credential has limited reach. ## Next step If your product runs on MongoDB and you are not sure every layer of this checklist is covered, I can audit the setup and fix the gaps. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # GitHub Actions Self-Hosted Runners: Setup and Gotchas URL: https://webdevang.com/blog/github-actions-self-hosted-runner · Category: Mobile & DevOps · Updated: 2026-11-03 A GitHub Actions self hosted runner is a small agent you install on your own machine that picks up workflow jobs from GitHub. Instead of running on a fresh GitHub-hosted VM, the job runs on your server, with your network access, your disks and your tools already installed. I use self-hosted runners for deploys, scheduled content pipelines and builds that need to sit close to production. They are simple to install and easy to get subtly wrong. This post covers when they are worth it, the setup I use, and the gotchas that have cost me time. ## TL;DR Use a self-hosted runner when a job needs private network access, a persistent environment, special hardware or long runtimes. Install it under a dedicated user as a systemd service, label it, keep it off public repositories, and schedule cleanup of workspaces and caches. Treat the runner machine like production, because for deploy jobs it effectively is. ## Key takeaways - Self-hosted runners make sense for deploys to private servers, long jobs, scheduled pipelines and work that needs specific hardware or network access. - Install the runner as a systemd service under a dedicated non-root user so it survives reboots and has limited power. - Never attach self-hosted runners to public repositories, because a pull request from a fork could run code on your machine. - Runners keep state between jobs, so clean workspaces, prune caches and watch disk space or builds will fail in confusing ways. ## When a self-hosted runner is worth it GitHub-hosted runners are excellent for tests and builds that need nothing special. Reach for self-hosted when one of these is true: | Situation | Why self-hosted helps | |---|---| | Deploying to a VM without opening SSH to the world | The runner lives on or next to the server and pulls jobs outbound over HTTPS | | Scheduled pipelines that run for a long time | No per-minute billing pressure, and persistent caches speed reruns | | Jobs needing private resources | Database replicas, internal APIs or VPC-only services are reachable | | Heavy builds | A large VM with warm dependency caches beats a cold hosted runner | | Multiple projects on one server | Several runners, each labeled, share one box | The outbound-only connection is the underrated benefit. The runner polls GitHub, so you do not need inbound ports for CI, and your SSH can stay restricted to a bastion or your own IP. ## Setup on a Linux VM This is the sequence I use on Ubuntu. GitHub's [self-hosted runner documentation](https://docs.github.com/en/actions/hosting-your-own-runners) has the canonical commands for your OS and architecture. 1. **Create a dedicated user**, for example `runner`, with no sudo by default. Grant narrow sudo rules later only if a job truly needs them (such as reloading Nginx). 2. **Download the runner** into a directory like `/home/runner/actions-runner-app1` using the commands from the repo's Settings, Actions, Runners page. 3. **Configure it** with `./config.sh --url --token --labels gcp,deploy,app1 --name app1-vm1`. Labels are how workflows target the right machine. 4. **Install as a service** with `sudo ./svc.sh install runner` and `sudo ./svc.sh start`. Now it restarts on reboot and logs to journald. 5. **Install toolchains** the jobs need: Node via nvm, PM2, Python, Playwright browsers. Pin versions so jobs do not change behavior when the machine updates. 6. **Target it in workflows**: ```yaml jobs: deploy: runs-on: [self-hosted, deploy, app1] concurrency: deploy-app1 steps: - uses: actions/checkout@v4 - run: npm ci && npm run build - run: pm2 reload ecosystem.config.js ``` The `concurrency` key matters. Without it, two quick pushes can run overlapping deploys on the same server. For parallel jobs, register multiple runners in separate directories. Each runner handles one job at a time. ## Security rules I do not break A self-hosted runner executes whatever the workflow file tells it to. That makes the workflow file part of your attack surface. - **Private repositories only.** GitHub explicitly warns against self-hosted runners on public repos, since a fork's pull request could run arbitrary code. - **Non-root user.** If a job is compromised, it should not own the machine. - **Scoped secrets.** Use environment-level secrets with required reviewers for production deploys. - **Limit who can edit workflows.** Branch protection and CODEOWNERS on `.github/workflows/` stop a casual change from adding `curl | bash`. - **Separate runners per trust level.** Do not let an experimental repo share a runner with the production deploy job. - **Pin third-party actions** to a commit SHA rather than a moving tag. ## Gotchas that break things These are the problems I have actually hit or seen. 1. **Disk fills up.** Workspaces, `node_modules`, Docker layers and Playwright browsers accumulate. Add a weekly cleanup cron and an alert at 80 percent disk. 2. **State leaks between jobs.** A file left in the workspace by a previous run makes a broken build pass. Use `actions/checkout` with `clean: true` and avoid writing outside the workspace. 3. **Environment differs from your shell.** The service does not load your `.bashrc`, so `node` or `pm2` may be missing from `PATH`. Set `PATH` in the runner's `.env` file or use absolute paths. 4. **Runner version drift.** Runners auto-update by default. If you disable that, you must update manually or GitHub will eventually refuse old versions. 5. **Registration tokens expire quickly.** Script the setup so re-registering a runner after a rebuild takes minutes, not an afternoon. 6. **Long jobs and timeouts.** Set `timeout-minutes` on every job so a hung scraper does not occupy the runner forever. ## How I built this in practice On the [Antoc](/work/antoc) side at Passdn Technologies, an automated SEO blog pipeline runs on a GitHub Actions self-hosted runner. It uses Groq-hosted LLaMA to generate content inside the workflow. An automated, long-running content job is exactly the workload where a self-hosted runner on our own GCP infrastructure makes more sense than a hosted one. On X4ET, a B2B tech marketplace I built solo, I ran four GitHub Actions runners on AWS EC2 alongside Nginx and SSL, serving a Next.js frontend and a FastAPI backend. Multiple runners meant jobs did not queue behind each other, and labels kept every workflow pointed at the right runner. Across GCP I also run self-hosted runners next to PM2, Nginx and systemd services. The pattern is the same each time: one dedicated user, labeled runners, concurrency groups on deploy jobs, and a cleanup cron. ## Common mistakes - Attaching a self-hosted runner to a public repository. - Running the runner as root, or giving its user blanket sudo. - Forgetting `concurrency` on deploy jobs, so overlapping deploys corrupt builds. - Never cleaning the work directory and running out of disk mid-deploy. - Relying on interactive shell `PATH` settings that the service never loads. - Using one shared runner for every repo and trust level. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [Antoc case study: CRM infrastructure on GCP](/work/antoc) - [Hire a full stack developer in the UK](/hire/full-stack-developer-uk) - [Azure data residency for Australian compliance apps](/blog/azure-data-residency-australia) - [Production Node.js on AWS EC2 checklist](/blog/nodejs-aws-ec2-production) - [Building a self-hosted LAN file transfer app](/blog/lan-file-transfer) - [Next.js Core Web Vitals fixes](/blog/nextjs-core-web-vitals) ## FAQ ### When should I use a GitHub Actions self hosted runner instead of GitHub-hosted? Use one when a job needs access to a private network, specific hardware, long runtimes, or a persistent environment such as the server you are deploying to. For ordinary tests on public infrastructure, GitHub-hosted runners are less maintenance. ### Are self-hosted runners free? GitHub does not bill Actions minutes for self-hosted runners in the usual model, but you pay for the machine, its storage and your time to maintain it. Check GitHub's current pricing page because billing terms can change. ### Is it safe to use a self-hosted runner on a public repo? GitHub recommends against it. Anyone who can open a pull request could potentially run code on the runner machine, so keep self-hosted runners on private repositories. ### How many self-hosted runners can I run on one VM? Each runner processes one job at a time, so you can register several runners in separate directories on one VM to run jobs in parallel. Size CPU, memory and disk for the heaviest jobs running together. ## Next step If your deploys are manual, flaky or depend on one person's laptop, I can set up runners and pipelines that make releases boring. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # Azure Data Residency for Australian Compliance Apps URL: https://webdevang.com/blog/azure-data-residency-australia · Category: Mobile & DevOps · Updated: 2026-11-03 When an Australian accounting or compliance client asks "where is our data stored?", they want a precise answer. Planning Azure data residency Australia-first is one of the cleanest ways to give it, because a single region can host the app, the database, the documents and the outbound email. I built an audit portal for an Australian accounting firm with all data hosted in Azure Australia East. This post explains the architecture, the services that tend to leak data offshore, and how to document residency so clients and auditors are satisfied. It is an engineering guide, not legal advice. ## TL;DR Put every service that stores or processes customer data in one Australian region, usually Australia East. That means compute, database, file storage, email, backups and logs. Then audit your third-party tools, keep production data out of CI/CD, and write a short data map that shows where each data category lives. ## Key takeaways - Data residency is an architecture decision across every service, not a single region dropdown on the web app. - Azure Australia East can host the app, database, file storage and email together, which keeps the data path simple to explain to auditors. - Third-party tools for logging, error tracking, email and AI are the usual places data quietly leaves the country. - Document where every category of data lives and travels, because clients will ask and a one-page data map answers most questions. ## Why residency matters for Australian compliance apps Accounting, legal and financial services firms in Australia handle trust account records, bank statements, client identities and tax data. Their own clients and regulators expect that data to be handled carefully, and many firms prefer or contractually require that it stays onshore. The Australian Privacy Principles include rules about disclosing personal information overseas (APP 8), and staying onshore simplifies that conversation considerably. Beyond the law, residency is a sales question. A firm evaluating a portal will ask where data lives, who can access it and how long it is kept. A clear answer shortens procurement. ## A reference architecture on Azure Australia East This is the layout I use for a compliance-grade web app. Microsoft's [Azure geographies documentation](https://learn.microsoft.com/en-us/azure/reliability/regions-overview) explains region pairs and service availability. | Layer | Azure service | Residency notes | |---|---|---| | Web and API | Azure App Service | Deploy to Australia East; scale up or out within the region | | Database | Azure Database for PostgreSQL (Flexible Server) | Same region; automated backups stay in the region or its Australian pair | | Documents | Azure Blob Storage | Private containers, short-lived SAS URLs for downloads | | Transactional email | Azure Communication Services Email | Choose Australia as the data location when creating the resource | | Secrets | Azure Key Vault or App Service settings | Region-scoped, never in the repo | | CI/CD | GitHub Actions | Moves code and build artifacts only, never production data | Two principles make this work. First, colocate everything so data never crosses a region boundary during normal operation. Second, keep every storage resource private and hand out access only through the application, which enforces permissions. ## Services that quietly move data offshore The core stack is easy. The risk lives in the extras teams add later. 1. **Error tracking and logging.** Exceptions often include request bodies, emails and IDs. Choose a provider region carefully or scrub payloads before sending. 2. **Email providers.** A third-party email API may store message content and logs in another country. Azure Communication Services with an Australian data location avoids that. 3. **AI features.** Sending documents to a model API can process data offshore. Use a regional deployment or keep AI features off sensitive records. 4. **Analytics and session replay.** These can capture form inputs. Mask fields or skip them in authenticated areas. 5. **Support tools.** Screenshots and exports pasted into a ticketing system are still customer data. 6. **Developer laptops.** Production dumps on a laptop break residency instantly. Use anonymized seed data for development. ## Controls that go with residency Residency answers "where". Auditors will also ask "who" and "how". - **Strong sign-in**: password, then email OTP, with optional TOTP authenticator apps for staff. - **Token handling**: short-lived access tokens kept in memory, refresh tokens in httpOnly cookies, so a script cannot read them. - **Role separation**: different portals or roles for external users and internal reviewers. - **Signed file URLs**: SAS links that expire in minutes, generated only after a permission check. - **Audit trails**: record who viewed, verified, rejected or downloaded what, and when. - **Retention**: decide how long engagement data stays after the job ends and automate deletion. ### Writing the data map A one-page data map answers most procurement questions. For each data category (user accounts, uploaded documents, bank and ledger lines, reports, emails, logs), list the service it lives in, the region, who can access it, and the retention period. Keep it in the repo next to the infrastructure code and update it when services change. ## How I built this in practice The [audit portal case study](/work/audit) covers a solo build for an Australian accounting firm that audits estate agents' trust accounts. Agents upload preliminary and per-property documents, auditors verify, reject or raise queries, sample around 5 percent of properties, run a data-driven audit programme, reconcile trust accounts from CSV and XLSX imports, and release the final report and audit pack. All of it is hosted in Azure Australia East: Azure App Service for the app, Azure PostgreSQL through Prisma for roughly 31 models, Azure Blob Storage for documents with time-limited signed URLs, and Azure Communication Email for notifications and OTPs. GitHub Actions handles CI/CD and only ever touches code. Sign-in is password, then email OTP, then optional TOTP, with short-lived access tokens in memory and httpOnly refresh cookies. Real-time query threads between agents and auditors run over Socket.IO inside the same App Service, so even the chat traffic stays in the region. ## Common mistakes - Choosing Australia East for the web app but leaving storage or email in a default US region. - Making blob containers public "just for the logo" and later reusing them for documents. - Sending full request payloads, including client data, to an offshore error tracker. - Copying production databases to developer machines or staging in another region. - Using long-lived or permanent file links that keep working after access is revoked. - Having no written data map when the client's compliance team asks for one. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [Audit portal for an Australian accounting firm](/work/audit) - [Hire a full stack developer in Australia](/hire/full-stack-developer-australia) - [Production Node.js on AWS EC2 checklist](/blog/nodejs-aws-ec2-production) - [Building a self-hosted LAN file transfer app](/blog/lan-file-transfer) - [Next.js Core Web Vitals fixes that worked](/blog/nextjs-core-web-vitals) - [Zero-downtime deployment with PM2](/blog/zero-downtime-deployment-pm2) ## FAQ ### Which Azure region should I use for Australian data residency? Australia East (Sydney) is the most common primary region and has the widest service availability. Australia Southeast (Melbourne) is a typical pair for backups or disaster recovery when both copies must stay onshore. ### Does hosting on Azure in Australia make my app compliant? No. Hosting onshore helps with residency requirements and client expectations, but compliance also depends on access control, retention, audit trails and your contracts. Get legal advice for your specific obligations. ### Can I use Azure DevOps or GitHub Actions and still keep data in Australia? Yes, as long as CI/CD handles code and build artifacts, not production data. Keep database dumps, customer files and real records out of pipelines and logs. ### How do I share files securely from Azure Blob Storage? Keep containers private and generate short-lived SAS URLs on the server after checking the user's permission. The link expires quickly, so a forwarded URL stops working. ## Next step If you are building software for Australian accounting, legal or compliance teams and need data to stay onshore, I can design and build it end to end. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # Production Node.js on AWS EC2: A Checklist URL: https://webdevang.com/blog/nodejs-aws-ec2-production · Category: Mobile & DevOps · Updated: 2026-11-03 Most guides to "nodejs aws ec2 production" setups end once `node server.js` responds on port 80. That is the first ten percent. The rest is networking, identity, storage, email deliverability, monitoring and recovery, which is where production apps actually fail. I ran a B2B marketplace on AWS EC2 that I built solo, and I run Node services on GCP VMs for Antoc. This checklist is the EC2-specific version of what I set up before real users arrive. If you are on Google Cloud instead, my post on deploying Next.js on GCP covers the equivalent setup. ## TL;DR Launch a right-sized instance in the region nearest your users, attach an Elastic IP, lock security groups to 80/443 plus restricted SSH, use IAM roles instead of stored keys, put Nginx in front for TLS, run the app under PM2 or systemd, send email through SES, and turn on EBS snapshots and CloudWatch alarms. Add load balancers later, when you have a reason. ## Key takeaways - A single well-configured EC2 instance can run a Node.js product reliably for a long time if networking, IAM and backups are done properly. - Use an Elastic IP, tight security groups and IAM instance roles instead of public SSH and access keys stored on disk. - EBS snapshots, CloudWatch alarms and log rotation are the unglamorous parts that prevent most outages. - Move to load balancers and auto scaling only when traffic or uptime requirements justify the extra moving parts. ## The checklist at a glance | Area | Do this | Why | |---|---|---| | Instance | Start with t3/t4g, 2 vCPU, 2 to 4 GB; gp3 EBS 30 GB+ | Cheap, and gp3 lets you tune IOPS separately | | IP | Allocate and attach an Elastic IP | Public IP survives stop/start, DNS stays valid | | Security group | 80/443 open, 22 from your IP only, app port closed | Users go through Nginx, attackers see less | | Identity | IAM instance role with least privilege | No AWS keys in `.env` files | | Metadata | Require IMDSv2 | Blocks a class of SSRF credential theft | | TLS | Nginx + Certbot, auto-renew | Free certificates, HTTP/2, redirects | | Process | PM2 with startup script, or systemd | Restarts on crash and reboot | | Email | Amazon SES with SPF, DKIM, DMARC | Deliverability without running a mail server | | Backups | Scheduled EBS snapshots via Data Lifecycle Manager | Point-in-time recovery for the whole disk | | Monitoring | CloudWatch alarms, agent for memory and disk | Default metrics skip memory and disk usage | ## Networking and identity ### Elastic IP and DNS An instance's auto-assigned public IP changes when you stop and start it. Allocate an Elastic IP, associate it, and point your A records at it. Remember that an Elastic IP not attached to a running instance costs money, so release ones you stop using. ### Security groups Treat security groups as your first firewall: 1. Inbound 443 and 80 from `0.0.0.0/0` (80 only to redirect to HTTPS). 2. Inbound 22 from your office or home IP, or close it entirely and use Session Manager. 3. Database ports open only to the app server's security group, never to the internet. 4. Outbound left open unless you have a reason to restrict it. Reference security groups by ID instead of IP ranges where possible. When you add a second app server, it inherits access automatically. ### IAM roles, not keys If your app uploads to S3 or sends via SES, attach an IAM role to the instance. The AWS SDK picks up temporary credentials from the instance metadata service automatically. Long-lived access keys in an `.env` file are the thing you least want copied off a server. Enforce IMDSv2 so those credentials require a session token. AWS's [EC2 user guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) covers both. ## Running the Node process On the instance itself: - Install Node with nvm or NodeSource, pinned to the version CI uses. - Run the app as a non-root user. Bind to a high port (3000, 8000) and let Nginx listen on 80/443. - Use PM2 with `pm2 startup` and `pm2 save`, or a systemd unit with `Restart=always`. - Set `NODE_ENV=production`, which changes Express behavior and many libraries' defaults. - Handle `SIGTERM` gracefully: stop accepting connections, finish in-flight requests, close database pools, then exit. - Rotate logs with `pm2-logrotate` or logrotate, because a full EBS volume takes down everything. Nginx sits in front for TLS termination, gzip, upload size limits and WebSocket upgrades. Certbot with the Nginx plugin issues and renews certificates. ## Email, monitoring and recovery ### SES for transactional email New SES accounts start in a sandbox that can only send to verified addresses. Request production access early, because approval can take a day or more. Verify your domain, publish SPF, DKIM and DMARC records, and handle bounces and complaints, or SES may pause sending. ### What to monitor CloudWatch gives CPU and network by default but not memory or disk usage. Install the CloudWatch agent or use another monitor, then alarm on: - Disk above 80 percent. - Memory pressure or swap usage. - CPU credit balance near zero on burstable instances. - Failed health checks from an external uptime monitor. - Error rate spikes from your error tracker. ### Recovery Schedule daily EBS snapshots with Data Lifecycle Manager and keep a week or more. Snapshot before every risky change. Practice restoring: launch an instance from a snapshot in a test subnet and confirm the app boots. Databases deserve their own backup plan on top of disk snapshots. ## How I built this in practice On X4ET, a B2B tech marketplace I built solo, production ran on AWS EC2 with an Elastic IP, Nginx and SSL in front of a Next.js frontend and a FastAPI backend, with MongoDB for data. Four GitHub Actions runners handled deploys, Razorpay handled payments, AWS SES sent transactional email, and MSG91 delivered OTPs. On the [Antoc](/work/antoc) side, the same principles apply on GCP: VMs in asia-south1 running Node/Express and Next.js under PM2 behind Nginx, Sentry for errors, and a MongoDB database hardened with authentication and network restrictions as it grew past 300K leads. The cloud vendor changes the names (security groups versus firewall rules, Elastic IP versus static IP), not the checklist. Across AWS, GCP and Azure, the projects that stayed calm were the ones where these basics were done before launch, not after the first outage. ## Common mistakes - Storing AWS access keys in `.env` instead of using an instance role. - Leaving SSH open to the world with password login enabled. - Forgetting to request SES production access until launch day. - Running a sustained-load API on a burstable instance and getting throttled when credits run out. - Relying on default CloudWatch metrics and missing a disk filling up. - Never testing a snapshot restore. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [Antoc CRM infrastructure case study](/work/antoc) - [Hire a full stack developer in the USA](/hire/full-stack-developer-usa) - [Building a self-hosted LAN file transfer app](/blog/lan-file-transfer) - [Next.js Core Web Vitals fixes](/blog/nextjs-core-web-vitals) - [Zero-downtime deployment with PM2 and GitHub Actions](/blog/zero-downtime-deployment-pm2) - [When Docker is worth it for a Node.js SaaS](/blog/docker-nodejs-saas) ## FAQ ### Is EC2 a good choice for a Node.js production app? Yes, for many SaaS products and APIs. EC2 gives full control, predictable pricing and room for background workers. Managed options like App Runner or Elastic Beanstalk reduce ops work but limit flexibility. ### What EC2 instance type should I start with for Node.js? A burstable t3 or t4g instance with 2 vCPU and 2 to 4 GB RAM is a common starting point for small apps. Watch CPU credit balance, because a sustained-load app on a burstable instance can slow down when credits run out. ### Should I use PM2 or systemd for Node.js on EC2? Both work. PM2 adds clustering, zero-downtime reloads and log handling for Node specifically, while systemd is built in and fine for a single process. I usually use PM2 for apps and systemd for supporting services. ### How do I send email from a Node.js app on EC2? Use Amazon SES rather than running your own mail server. Verify your domain, set up SPF, DKIM and DMARC, request production access, and send through the SES API from the app using an IAM role. ## Next step If you are launching on AWS and want the production basics right the first time, or need an existing EC2 setup reviewed, I can help. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # Building a Self-Hosted LAN File Transfer Web App URL: https://webdevang.com/blog/lan-file-transfer · Category: Mobile & DevOps · Updated: 2026-11-03 Moving a 15 GB video from a phone to a laptop should not involve uploading it to the cloud and downloading it again. A LAN file transfer tool keeps the bytes on your own network, where they move as fast as your router allows. I built PocketBridge, an open-source, self-hosted web UI for exactly this. Run it on any machine, open the address from a phone browser, and send files up to 20 GB. This post covers the design decisions that make that work reliably: streaming to disk, honest progress and ETA, and enough security for a shared network. ## TL;DR Serve a small web app on a machine in your local network, accept uploads as streams written directly to disk, report progress from the browser's upload events, protect access with a PIN, and keep the process alive with PM2. No app install is needed on the sending device, and memory use stays flat even for very large files. ## Key takeaways - A browser-based LAN file transfer tool needs no app installs, so any phone, tablet or laptop on the same network can use it. - Large uploads must be streamed straight to disk, because buffering a multi-gigabyte file in memory will crash the server. - Progress and ETA come from the browser's upload events, and they matter more to users than raw speed. - Even on a home or office network, a simple PIN and binding to the local interface prevent casual access. ## Why a web UI beats the alternatives There are plenty of ways to move files locally. Each has a catch. | Method | Install needed | Large files | Cross-platform | Catch | |---|---|---|---|---| | Cloud drive | App or browser | Size limits, slow | Yes | Goes through the internet twice | | Bluetooth / nearby share | Built in | Very slow | Partly | Vendor ecosystems do not talk to each other | | SMB / network share | OS config | Good | Mostly | Setup friction on phones | | USB cable | Cable, drivers | Good | Mostly | Phone file access is often clumsy | | Local web app | Nothing on sender | Good if streamed | Any browser | Needs one machine running the server | A browser is the one client every device already has. That is the whole pitch: one server, zero installs everywhere else. ## Streaming uploads to disk, not RAM This is the core engineering problem. Many upload tutorials parse the whole request into memory, then save it. That works for a 2 MB photo and fails badly at 20 GB. ### The approach 1. The browser sends the file as the raw request body (or a multipart stream), with the file name and size in headers or the form. 2. The server opens a write stream to a temporary file in the target directory. 3. Incoming chunks are piped to the write stream. Node's `pipeline()` handles backpressure, so if the disk is slower than the network, reading pauses instead of buffering. 4. When the stream finishes and the byte count matches the declared size, the temp file is renamed to its final name. 5. If the client disconnects or sizes do not match, the temp file is deleted. In a Next.js route handler, the request body is a web `ReadableStream`. Convert it with `Readable.fromWeb()` and pipe it into `fs.createWriteStream()`. The [Next.js route handler docs](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) describe the request object you get. ### Details that matter at 20 GB - **Disable body parsing and size limits** for the upload route only, so the framework does not try to buffer or reject the body. - **Check free disk space** before accepting, using the declared size. Failing at 19 GB is far worse than failing at 0. - **Sanitize file names.** Strip path separators and `..` so a name cannot escape the upload directory. Handle duplicates by appending a counter. - **Raise proxy timeouts** if Nginx sits in front, and turn off request buffering for the route, or the proxy will spool the whole file first. - **Write temp files on the same filesystem** as the destination so the final rename is instant. ## Progress, ETA and the user experience Users judge a transfer tool by whether they trust it. A frozen screen during a 10-minute upload feels broken even when it is working. On the client, `XMLHttpRequest.upload.onprogress` reports bytes sent. From that: - **Percentage** is `loaded / total`. - **Speed** should be a moving average over the last few seconds, not the overall average, so it reacts when Wi-Fi changes. - **ETA** is remaining bytes divided by the smoothed speed. Round it to friendly units and avoid updating the text more than once a second. Other touches that help: - Queue multiple files and show per-file and total progress. - Keep the screen awake during transfers on mobile where the browser allows it. - Show the server's LAN address and a QR code on the host machine, so phones can connect without typing an IP. - Provide a clear success state with the saved file name and size. ## Security on a local network "It is only my Wi-Fi" is not a security model, especially on office or shared networks. 1. **PIN protection.** Require a PIN before uploads or downloads, and set a session cookie after it is entered. Rate-limit wrong attempts. 2. **Bind to the LAN.** Listen on the local interface, and never port-forward the app to the internet. 3. **Restrict the directory.** Only read and write inside one configured folder. 4. **No directory traversal.** Validate every path parameter on downloads as strictly as uploads. 5. **Log transfers** with time, client IP, file name and size. If you ever need remote access, put it behind a VPN rather than exposing the app directly. ## How I built this in practice [PocketBridge](/work/pocketbridge) is open source and self-hosted. It is a Next.js app that runs under PM2, so it restarts if it crashes and comes back after a reboot. Uploads stream to disk rather than RAM, which is what makes files up to 20 GB practical on modest hardware. The UI shows progress and ETA, and a PIN gates access. The same streaming discipline shows up in client work. In the audit portal I built for an Australian accounting firm, documents go to Azure Blob Storage and are served through time-limited signed URLs rather than through the app server. In Client Mitra, files go to Cloudinary. The rule is consistent: never hold a whole file in application memory if you can stream it or hand it off. ## Common mistakes - Parsing uploads into memory with a default body parser and crashing on the first large file. - Leaving framework or proxy body size limits in place, causing silent failures near the end. - Trusting the client-provided file name and allowing path traversal. - Calculating ETA from the overall average speed, which makes it wildly wrong after a Wi-Fi dip. - Not cleaning up partial temp files after cancelled uploads, slowly filling the disk. - Port-forwarding a LAN tool to the internet for convenience. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [PocketBridge open-source LAN transfer project](/work/pocketbridge) - [Hire a full stack developer in India](/hire/full-stack-developer-india) - [Next.js Core Web Vitals fixes that worked](/blog/nextjs-core-web-vitals) - [Zero-downtime deployment with PM2](/blog/zero-downtime-deployment-pm2) - [Docker for Node.js SaaS](/blog/docker-nodejs-saas) - [Getting a Flutter WebView app through App Store review](/blog/flutter-webview-app-store-approval) ## FAQ ### What is the fastest way to transfer files over a LAN? For occasional transfers, a local web app or SMB share over Wi-Fi or Ethernet is fast and avoids cloud upload limits. Wired Ethernet is usually much faster and more consistent than Wi-Fi for multi-gigabyte files. ### Why not just use a cloud drive? Cloud drives upload over your internet connection and then download again, which is slow for large files and may have size limits. A LAN transfer stays on the local network, so speed is limited only by your router and devices. ### How do you upload a 20 GB file through a browser without crashing the server? Stream the request body directly to a file on disk instead of parsing it into memory. Node's streams with backpressure write chunks as they arrive, so memory use stays flat regardless of file size. ### Is a self-hosted file transfer app safe on my network? It can be if you keep it on the local network, avoid port forwarding, add a PIN or password, and sanitize file names. Do not expose it to the internet without proper authentication and TLS. ## Next step If your product needs large file uploads, self-hosted tooling or infrastructure that handles heavy data without falling over, I can build it. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # Next.js Core Web Vitals: Fixes That Moved the Needle URL: https://webdevang.com/blog/nextjs-core-web-vitals · Category: Mobile & DevOps · Updated: 2026-11-03 Teams searching for "nextjs core web vitals" fixes usually start by chasing a Lighthouse number on their own laptop. That number is not what Google uses, and it is not what your users feel. The real score comes from field data on mid-range phones and patchy mobile networks. This post lists the Next.js changes that reliably improve Largest Contentful Paint, Interaction to Next Paint and Cumulative Layout Shift, roughly in order of impact. It draws on building Client Mitra, a data-heavy App Router SaaS that also runs inside Android and iOS apps, where slow pages are impossible to hide. ## TL;DR Measure field data first. Fix LCP with a properly prioritized hero image, self-hosted fonts and faster server responses. Fix INP by moving work into server components, shrinking client bundles and breaking up long tasks. Fix CLS by reserving space for images, fonts and late content. Then defer every third-party script you can. ## Key takeaways - Measure field data first, because lab scores from one fast laptop rarely match what real users on mid-range phones experience. - LCP usually improves most from fixing the hero image, fonts and server response time, not from micro-optimizing JavaScript. - INP problems come from heavy client components and long tasks, so moving work to server components and splitting bundles matters. - CLS is almost always caused by images without dimensions, late-loading fonts and content injected above existing content. ## Measure before you change anything Google's thresholds for good are LCP under 2.5 s, INP under 200 ms and CLS under 0.1, at the 75th percentile of visits. The [web.dev Core Web Vitals guide](https://web.dev/articles/vitals) explains each metric in depth. Where to get real data: 1. **Search Console's Core Web Vitals report** for public pages, grouped by URL pattern. 2. **PageSpeed Insights** for a URL's field data (from the Chrome UX Report) alongside a lab run. 3. **Your own RUM** using Next.js's `useReportWebVitals` hook, sending metrics to analytics with the route name attached. Your own collection is the most useful, because it covers logged-in pages and tells you which route is slow, not just that the site is. ## Fixes that move LCP LCP is the time until the largest visible element, usually a hero image or a heading, is painted. | Cause | Fix in Next.js | |---|---| | Hero image discovered late | Use `next/image` with `priority` on the LCP image only | | Oversized images | Set `sizes` correctly so phones do not download desktop widths | | Web fonts blocking text | Use `next/font` to self-host with `display: swap` and preloading | | Slow server response (TTFB) | Cache data fetches, avoid waterfalls, colocate server and database | | Client-side data fetching for above-the-fold content | Fetch in a server component so HTML arrives with content | | Huge CSS | Tailwind's purge plus avoiding global CSS imports from many libraries | Two notes from experience. First, `priority` on every image defeats its purpose, so pick the one LCP element per page. Second, server response time is often the biggest hidden factor. A server in a different region from the database adds latency to every request before the browser sees a byte. ## Fixes that move INP INP measures how long the page takes to respond visually after a tap, click or keypress. It replaced First Input Delay and is harder to pass, especially on dashboards. - **Ship less JavaScript.** Default to server components. Add `"use client"` only to the interactive leaf, not to the whole page. - **Split heavy components.** Charts, rich text editors, PDF previews and date pickers belong behind `next/dynamic` so they load when needed. - **Avoid giant re-renders.** A filter change that re-renders a 500-row table on the main thread will fail INP. Virtualize long lists and memoize row components. - **Yield during heavy work.** Break long loops into chunks, or move parsing and calculations to a web worker. - **Give instant feedback.** Use `useTransition` for state updates that trigger expensive renders, so the button press paints immediately. - **Audit libraries.** Check bundle composition with `@next/bundle-analyzer`. A single date or icon library imported wholesale can dominate the bundle. ## Fixes that move CLS CLS measures unexpected layout movement. It is usually the easiest to fix. 1. Always give images and videos dimensions, or use `next/image`, which reserves space automatically. 2. Use `next/font` so fallback and web font metrics are matched and text does not jump on swap. 3. Reserve space for banners, cookie notices and ads, or render them as overlays. 4. Render skeletons with the same height as the real content for data that loads after the first paint. 5. Never insert content above what the user is reading, except in response to their action. ### Third-party scripts Analytics, chat widgets, heatmaps and ad pixels quietly hurt all three metrics. Load them with `next/script` using `afterInteractive` or `lazyOnload`, remove the ones nobody looks at, and test with them disabled to see their real cost. ## How I built this in practice [Client Mitra](/work/clientmitra) is a multi-tenant CRM for Indian photography studios that I built solo on the Next.js App Router with Tailwind, a Node/Express API and MongoDB. It has around 30 app pages covering enquiries, bookings, a crew calendar for multi-day weddings, GST invoices and reports. The same web app ships as native Android and iOS apps through a Flutter wrapper, so studio owners on mid-range phones are the real audience for performance. A few choices did the heavy lifting. TanStack Query with a persisted cache means returning users see their last data instantly while fresh data loads in the background, which helps perceived speed on every revisit. Uploaded images such as business logos live on Cloudinary, which can deliver resized versions instead of full originals. Heavy pieces like reports and calendars load only on the pages that need them, and client components stay at the leaves. I did not chase a perfect lab score. I watched how screens behaved on real phones inside the app wrapper and fixed the interactions that felt slow, which is what INP is trying to measure anyway. ## Common mistakes - Optimizing for a desktop Lighthouse run instead of mobile field data. - Adding `priority` to every image, which makes none of them a priority. - Marking entire pages as client components because one button needs state. - Fetching above-the-fold data on the client and showing spinners where HTML could have arrived ready. - Loading chat widgets and pixels synchronously in the root layout. - Ignoring logged-in pages, where users spend most of their time. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [Client Mitra case study: Next.js SaaS for studios](/work/clientmitra) - [Hire a full stack developer in the UK](/hire/full-stack-developer-uk) - [Zero-downtime deployment with PM2 and GitHub Actions](/blog/zero-downtime-deployment-pm2) - [Docker for Node.js SaaS: when it is worth it](/blog/docker-nodejs-saas) - [Flutter WebView apps and App Store approval](/blog/flutter-webview-app-store-approval) - [How much Flutter app development costs](/blog/flutter-app-development-cost) ## FAQ ### What are good Core Web Vitals scores for a Next.js site? Google's thresholds for good are LCP under 2.5 seconds, INP under 200 milliseconds and CLS under 0.1, measured at the 75th percentile of real user visits. Those thresholds are the same for Next.js as for any other site. ### Does the App Router improve Core Web Vitals? It can, because server components send less JavaScript to the browser and streaming shows content sooner. But a page full of client components and heavy libraries will still be slow, so the router alone is not a fix. ### Why is my Lighthouse score good but Search Console says pages are poor? Lighthouse is a lab test on one device and network. Search Console uses field data from real users, often on slower phones and connections, so it exposes problems a fast development machine hides. ### Do third-party scripts hurt Next.js performance? Yes, often more than your own code. Load analytics, chat widgets and pixels with next/script using the afterInteractive or lazyOnload strategies, and remove any you are not actively using. ### Should I fix Core Web Vitals on dashboard pages behind login? Search ranking only uses public pages, but logged-in users feel the same slowness. Prioritize public pages for SEO and fix dashboard INP for retention. ## Next step If your Next.js product feels slow or Search Console is flagging poor pages, I can profile it and fix what matters. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # Zero-Downtime Deployment With PM2 and GitHub Actions URL: https://webdevang.com/blog/zero-downtime-deployment-pm2 · Category: Mobile & DevOps · Updated: 2026-11-03 A zero-downtime deployment (PM2 plus GitHub Actions) is the cheapest reliability upgrade a VM-hosted product can make. Without it, every deploy means a few seconds of 502 errors, failed form submissions and dropped realtime connections. Teams start deploying late at night to hide it, and then they stop deploying often. PM2 can swap versions without dropping requests, but only if the app and the pipeline cooperate. This post covers the pieces that make it actually work: cluster mode, ready signals, graceful shutdown, release folders, migration discipline and rollback. ## TL;DR Run the app in PM2 cluster mode with at least two instances. Signal readiness explicitly and shut down gracefully on SIGINT. Build each release into its own folder, switch a `current` symlink, then `pm2 reload`. Keep migrations backward compatible, health-check after the reload, and keep previous releases for instant rollback. Trigger it all from a GitHub Actions job. ## Key takeaways - pm2 reload only gives zero downtime when the app runs in cluster mode with at least two instances and shuts down gracefully. - Building Next.js in place overwrites files the running server needs, so build into a fresh release folder and switch a symlink. - Database migrations must be backward compatible for one release, because old and new code run side by side during a reload. - Every deploy needs a health check and a one-command rollback, or zero downtime only holds until the first bad release. ## How pm2 reload works, and when it does not In cluster mode, PM2 runs several instances of your app behind Node's cluster module, sharing one port. On `pm2 reload`, it starts a new instance, waits until it is ready, then stops one old instance, and repeats until all are replaced. | Setup | `pm2 restart` | `pm2 reload` | |---|---|---| | Fork mode, 1 instance | Downtime | Same as restart, downtime | | Cluster mode, 1 instance | Downtime | Short gap possible | | Cluster mode, 2+ instances | Downtime | Zero downtime if app is ready-aware | | Cron or queue worker | Fine, use fork mode | Not needed | The [PM2 cluster mode documentation](https://pm2.keymetrics.io/docs/usage/cluster-mode/) explains the mechanics. The catch is the word "ready". By default PM2 considers an instance ready when it starts listening, which may be before database connections and caches are warm. ## Make the app reload-friendly ### Signal readiness explicitly Set `wait_ready: true` and a `listen_timeout` in the ecosystem file. In the app, call `process.send('ready')` only after the server is listening and the database is connected: ```js await mongoose.connect(process.env.MONGO_URI); server.listen(PORT, () => process.send && process.send('ready')); ``` ### Shut down gracefully PM2 sends SIGINT to the old instance, then kills it after `kill_timeout` (default 1600 ms). Handle the signal: 1. Stop accepting new connections with `server.close()`. 2. Let in-flight requests finish. 3. Close database pools and flush logs. 4. Exit with code 0. Raise `kill_timeout` to cover your slowest normal request, such as a report export. If it is too short, PM2 cuts requests off mid-response. ### Keep workers out of the cluster Cron jobs and queue consumers should run as separate fork-mode apps with one instance. Two copies of a reminder cron sends every customer two reminders. ## Build into release folders Running `git pull && npm run build` in the live directory is the most common reason "zero downtime" deploys still break. Next.js rewrites the `.next` folder during the build, so the running server can fail to find chunks, and users on open tabs get errors when they navigate. A release-folder layout fixes this: ``` /srv/app/ releases/2026-11-03-1402-a1b2c3/ releases/2026-11-02-1730-d4e5f6/ shared/.env current -> releases/2026-11-03-1402-a1b2c3 ``` Each deploy: 1. Creates a new folder under `releases/` named with time and commit SHA. 2. Checks out the commit, links `shared/.env`, runs `npm ci` and `npm run build` there. 3. Runs pending migrations. 4. Atomically switches `current` with `ln -sfn`. 5. Runs `pm2 reload ecosystem.config.js --update-env`, with the ecosystem `cwd` pointing at `current`. 6. Hits a `/health` endpoint, and rolls back if it fails. 7. Deletes all but the last five releases. Because the build happens away from the running code, a failed build never touches production. ## Migrations and realtime connections ### Backward-compatible migrations During a reload, old and new instances serve traffic at the same time for a few seconds. A migration that renames a column or field breaks the old instances immediately. Use expand and contract: - **Release 1:** add the new field, write to both, read the old. - **Release 2:** backfill, then read the new field. - **Release 3:** stop writing the old field and remove it. It feels slower, but each release is safe to roll back. ### Socket.IO in cluster mode WebSocket clients are attached to a specific instance. When that instance reloads, they disconnect. Plan for it: - Use sticky sessions or force the WebSocket transport so polling requests do not bounce between instances. - Add an adapter (Redis is common) so an event emitted on one instance reaches clients on others. - Make the frontend reconnect automatically and refetch state after reconnecting. ## The GitHub Actions job The workflow is short. Run tests on a hosted runner, then deploy either by SSHing into the VM with a restricted deploy key or by running the job on a self-hosted runner on the server itself. Add `concurrency: production-deploy` so two pushes cannot run overlapping deploys, and use a GitHub environment with required reviewers if production deploys need approval. The deploy step calls one script on the server that does the seven steps above, so the same script works when run by hand in an emergency. ## How I built this in practice On [Antoc](/work/antoc), the real-estate CRM I work on at Passdn Technologies, the Next.js client and Node/Express API run on GCP VMs in asia-south1 under PM2 with Nginx in front. With 100+ real estate firms using the product during the working day, there is no quiet window where an outage goes unnoticed, so deploys have to be invisible. That shapes the architecture. Socket.IO powers realtime updates, so clients must handle reconnects cleanly. WhatsApp nurture drips and reminders run as scheduled jobs, which stay single-instance so a reload never duplicates messages. Webhook receivers for Meta lead ads and Google Ads must keep answering during a deploy, or leads are missed. Sentry on both client and server makes a bad release visible within minutes, which is when a fast rollback matters. GitHub Actions with self-hosted runners is a pattern I use across these GCP setups. ## Common mistakes - Using `pm2 restart` in the deploy script, which kills every instance at once. - Running a single cluster instance and expecting reload to keep the site up. - Building Next.js in the live folder while the server is serving it. - Leaving `kill_timeout` at the default and cutting off slow requests. - Shipping a field rename in one release while old instances still read the old name. - Having no health check, so a broken release is discovered by customers. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [Antoc CRM case study](/work/antoc) - [Hire a full stack developer in Australia](/hire/full-stack-developer-australia) - [Docker for Node.js SaaS: when it is worth it](/blog/docker-nodejs-saas) - [Flutter WebView apps and App Store approval](/blog/flutter-webview-app-store-approval) - [Flutter app development cost breakdown](/blog/flutter-app-development-cost) - [In-app purchase server-side verification](/blog/in-app-purchase-server-verification) ## FAQ ### Does pm2 reload really give zero downtime? Yes, for cluster-mode apps with two or more instances. PM2 restarts instances one at a time and waits for each new one to be ready before stopping the next old one, so there is always a process serving traffic. ### What is the difference between pm2 restart and pm2 reload? restart kills and restarts all instances at once, causing a brief outage. reload replaces instances one by one in cluster mode, keeping the app available throughout. ### Can I do zero-downtime deploys with Socket.IO and PM2? Yes, but cluster mode needs sticky sessions or the WebSocket transport only, plus an adapter such as Redis so events reach clients connected to other instances. Clients will reconnect during a reload, so handle reconnection on the frontend. ### How do I roll back a bad deploy on PM2? Keep the last few release folders on the server. Rolling back is pointing the current symlink at the previous release and running pm2 reload, which takes seconds. ## Next step If deploys at your company still mean a maintenance window or a nervous evening, I can set up a pipeline that makes them routine. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact). --- # Docker for Node.js SaaS: When It Is Worth It URL: https://webdevang.com/blog/docker-nodejs-saas · Category: Mobile & DevOps · Updated: 2026-11-03 Founders often ask whether their "docker nodejs saas" setup is a requirement or a fashion. The honest answer is that containers are a tool with clear costs and clear benefits, and plenty of profitable products run without them. I have shipped Node.js and Next.js products both ways: on plain VMs with PM2 and Nginx, and on a container-based platform. This post is the decision framework I use, plus the patterns that make containers pleasant when they are the right call. ## TL;DR Use Docker when you run several services, need identical environments across developers, CI and production, or deploy to a platform built around containers. Skip it for a single app on a single VM, where PM2 is simpler. If you want containers without maintaining Dockerfiles, a platform like Coolify with Nixpacks is a good middle path. ## Key takeaways - Docker pays off when you need identical environments across machines, many services on one host, or a platform that deploys containers for you. - A single Node.js app on one VM with PM2 is often simpler to run, debug and deploy than the same app in containers. - Platforms like Coolify with Nixpacks give you container benefits without writing or maintaining Dockerfiles. - If you do containerize, use multi-stage builds, a non-root user, a slim base image and secrets injected at runtime. ## What Docker actually buys you Containers package your app with its runtime and system dependencies, so it runs the same on a laptop, a CI runner and a server. That solves real problems: - **"Works on my machine" bugs** from different Node versions or native libraries. - **Dependency conflicts** when several apps on one host need different runtimes. - **Reproducible CI**, where tests run in the same image that ships. - **Portability** between providers, since any host that runs containers can run your app. - **Onboarding**, where a new developer runs `docker compose up` instead of following a setup document. It also adds costs: slower builds if layers are not cached well, images to store and scan, another layer of networking and volumes to debug, and a learning curve for the team. ## When it is worth it, and when it is not | Situation | Recommendation | Reason | |---|---|---| | One Node.js app, one VM, small team | PM2 + Nginx, no Docker | Fewer moving parts, easy debugging | | App + API + workers + headless browser on one host | Docker Compose | Isolates runtimes and system deps | | Multiple environments that drift (staging, prod, preview) | Docker | Same image everywhere | | Deploying to a container platform (Cloud Run, Coolify, ECS) | Docker or buildpacks | The platform expects images | | Native dependencies (image processing, PDF, browsers) | Docker | Pins system libraries | | Rapid prototype or MVP | Skip for now | Ship first, containerize when pain appears | | Team frequently onboarding developers | Docker Compose for local dev | Faster setup, fewer local bugs | My rule of thumb: containerize when you feel the pain of environment drift or dependency conflicts, not because a tutorial said so. ## A lean Dockerfile pattern for Node.js If you do write Dockerfiles, these habits keep images small and safe. Docker's [multi-stage build documentation](https://docs.docker.com/build/building/multi-stage/) is the reference. 1. **Multi-stage builds.** Install dev dependencies and build in one stage, then copy only the output and production dependencies into a slim runtime stage. 2. **Slim, pinned base images.** Use `node:-slim` or Alpine with an exact major version, and update deliberately. 3. **Cache-friendly order.** Copy `package.json` and the lockfile first, run `npm ci`, then copy source, so dependency layers are reused. 4. **Non-root user.** Switch to the built-in `node` user before `CMD`. 5. **One process per container.** Let the platform restart and scale; skip PM2 inside the image. 6. **Handle signals.** Make sure `SIGTERM` reaches Node (use `node` directly as `CMD`, not `npm start`) and shut down gracefully. 7. **Secrets at runtime.** Pass environment variables from the platform. Never bake `.env` files into images. 8. **A `.dockerignore`.** Exclude `node_modules`, `.git`, `.next/cache` and local env files. 9. **Next.js standalone output.** Set `output: 'standalone'` so the runtime image only contains what the server needs. ## The middle path: platforms that build containers for you Writing and maintaining Dockerfiles is a skill some teams do not want to invest in. Self-hosted platforms like Coolify, using Nixpacks, detect the framework, build an image and deploy it with environment variables, domains, TLS and logs handled in a UI. You get most of the container benefits (reproducible builds, isolated services, easy rollbacks to a previous image) on your own server, without a hand-written Dockerfile. The trade-off is less control over the image, which rarely matters for a standard Next.js or Node app. ### What still matters with containers Containers do not fix weak release practices. You still need: - **Versioned database migrations** applied in order and tested in CI. - **End-to-end tests** that exercise the real flows before production. - **Health checks** so the platform knows when a new container is ready. - **Persistent data outside containers**, in a managed database or mounted volumes. ## How I built this in practice [HNEFA](/work/hnefa) is a gaming cafe POS and ERP I contributed to with the Exlaso team. It runs a live machine floor with realtime timed sessions, touch POS billing, prepaid wallets, FIFO inventory and around 15 reports. The stack is Next.js and TypeScript on Supabase, and it deploys with Coolify using Nixpacks, so the app ships as a container without anyone maintaining a Dockerfile. What made that deployment trustworthy was the discipline around it. The database is defined by 47 versioned SQL migrations that are validated in CI, Playwright end-to-end tests cover key flows, and multi-tenant isolation is enforced with Postgres row-level security. The container is just the delivery mechanism. Contrast that with [Antoc](/work/antoc), where Next.js, a Node/Express API, Socket.IO and scheduled jobs run directly on GCP VMs under PM2 and Nginx. For that setup, PM2's cluster reloads and a clear process list are simpler than containers. Both approaches are right for their context. ## Common mistakes - Containerizing an MVP before it has users, then spending days on Docker networking instead of features. - Baking secrets or `.env` files into images that end up in a registry. - Running PM2 inside a container and fighting the orchestrator over restarts. - Using `npm start` as `CMD`, so `SIGTERM` never reaches Node and shutdowns are not graceful. - Storing uploads or database files inside the container filesystem, where they vanish on redeploy. - Huge images from skipping multi-stage builds and shipping dev dependencies. ## Internal links - [Cloud and DevOps services](/services/cloud-devops) - [HNEFA gaming cafe POS case study](/work/hnefa) - [Hire a full stack developer in Dubai](/hire/full-stack-developer-dubai) - [Flutter WebView apps and App Store approval](/blog/flutter-webview-app-store-approval) - [Flutter app development cost](/blog/flutter-app-development-cost) - [Server-side verification for in-app purchases](/blog/in-app-purchase-server-verification) - [FCM push notifications setup guide](/blog/fcm-push-notifications) ## FAQ ### Do I need Docker for a Node.js SaaS? No. Many successful SaaS products run on a VM with PM2 and Nginx. Docker becomes worth it when you have several services, multiple environments to keep identical, a team onboarding often, or a platform that expects containers. ### Is Docker slower than running Node.js directly? On Linux, the runtime overhead of a container is small for typical web workloads. The real costs are build time, image size and the extra layer to debug when something goes wrong. ### Should I use Docker with PM2 inside the container? Usually not. Let the container runtime or orchestrator handle restarts and scaling, and run one Node process per container. PM2 inside Docker mostly duplicates what the platform already does. ### What is Nixpacks and how does it relate to Docker? Nixpacks detects your app's language and framework and builds a container image without a hand-written Dockerfile. Platforms like Coolify use it so you get containers while keeping build configuration minimal. ## Next step If you are deciding how to package and deploy your SaaS, or want an existing setup simplified, I can recommend the right approach and build it. See my [cloud and DevOps services](/services/cloud-devops) and [get in touch](/#contact).