← Back to case studies

In production at spelltalk.com.br

Case Study — Spell

Version: 3.0

Status: Approved

Last updated: 2026-07-06

Type: Prior production system (narrative documentation, source not in this repository)


Overview

Spell is a multi-tenant SaaS platform that automates customer service on WhatsApp and Instagram using RAG-grounded AI, visual conversation flows, human handoff, scheduling, and integrated billing. It is in production at spelltalk.com.br.

Role: Lead engineer — architecture, backend, integrations, and deployment.

Scale: Multi-tenant production deployment with white-label instances.


Business Problem

Brazilian businesses depend on WhatsApp and Instagram for customer service, but manual responses do not scale: queues grow, off-hours go uncovered, and inconsistent answers hurt conversion. Generic chatbots frequently invent information or ignore the business knowledge base. The market needed an automated attendant on Meta's official APIs with reliable human handoff when automation is insufficient.


Requirements

CategoryRequirement
FunctionalMulti-tenant SaaS with per-tenant KB, agents, and billing
ChannelsWhatsApp Cloud API and Instagram Messaging API
AIRAG responses grounded in uploaded documents — no hallucinated pricing
HandoffHuman agent takeover with Meta template compliance
AutomationVisual flow builder for non-Q&A journeys (scheduling, data collection)
BillingStripe, Mercado Pago, PIX with package entitlements
OperationsAdmin panel, conversation history, operational metrics

Architecture

Spell adopted a three-service monorepo with shared PostgreSQL (pgvector) and internal communication between the bot engine and management API.

ServiceResponsibility
spell-serverMeta webhooks, RAG/visual bot engine, handoff relay, background worker
panel-apiAuth, tenant admin, KB, agents, billing, integrations, public API
spell-panelReact SPA for tenant and platform administration

System Diagram


Technology Stack

LayerTechnology
BackendNode.js 20, TypeScript, Fastify 4, Prisma 6
FrontendReact 18, Vite 5, React Router, @xyflow/react
DatabasePostgreSQL 16 with pgvector extension
AIOpenAI gpt-4o-mini, text-embedding-3-small
ChannelsWhatsApp Cloud API, Instagram Messaging API
PaymentsStripe, Mercado Pago, manual PIX
CalendarGoogle Calendar OAuth, Calendly
DeployDocker, CapRover

Key Features

  1. RAG knowledge base — PDF, DOCX, XLSX chunked and embedded; cosine similarity retrieval with response verifier
  2. Visual flows — Node-based builder for messages, options, data collection, timers, scheduling
  3. Human handoff — State machine: BOT_ACTIVEHANDOFF_PENDINGHUMAN_ACTIVECLOSED
  4. Multi-channel — Same tenant logic across WhatsApp and Instagram
  5. Package entitlements — Agent limits, conversation quotas, KB entries, flow node caps
  6. White-label deploy — Separate CapRover apps per branded instance

Engineering Challenges

RAG alignment

Generic LLMs invent prices and policies. The product requires retrieval with minimum similarity thresholds and a verification loop before sending any response.

WhatsApp 24-hour window

Human relay outside the messaging window requires Meta-approved templates, provisioned per tenant automatically.

Meta platform constraints

Instagram permissions, app review cycles, and comment reply limits directly impact feature availability and roadmap.

Multi-tenant billing

Entitlements must enforce limits in real time across server and panel-api via shared package-entitlements module.


Trade-offs

DecisionChosenAlternativeRationale
Bot runtimeDedicated spell-serverSingle APIWebhook latency isolation from admin CRUD
ORMPrismaRaw SQLType safety and migration velocity for small team
AI modelgpt-4o-miniLarger modelsCost control at scale; RAG quality matters more than model size
Monorepo3 services, 1 DBMicroservices per tenantOperational simplicity for current scale
HandoffFan-out to all agentsRound-robin queueFaster first response in WhatsApp context

Security

ControlImplementation
Tenant isolationphoneNumberId resolves tenant on every webhook
Webhook verificationMeta signature validation on inbound events
API authJWT for panel-api; API keys for public integrations
KB accessDocuments scoped per tenant; embeddings never cross tenant boundary
PaymentsStripe/Mercado Pago webhooks with signature verification
SecretsEnvironment variables per CapRover app; no keys in repository

Performance

AreaApproach
Embedding searchpgvector index on KnowledgeChunk.embedding; top-k with score threshold
Webhook responseAsync worker for heavy processing; immediate 200 to Meta
CachingSession state in PostgreSQL; hot tenant config cached in memory
Background jobsWorker for handoff retries, inactive session cleanup, template provisioning

Operational metrics (conversations/day, customers served) available in production admin panel.


Scalability

DimensionStrategy
TenantsShared infrastructure; tenant ID on all rows
MessagesHorizontal scale of spell-server behind load balancer; stateless webhook handlers
KB sizeChunked documents; embedding batch jobs off peak
AgentsPer-package agent limits enforced at connection time

Deployment

EnvironmentURLNotes
Panelpanel.spelltalk.com.brReact SPA via CapRover
APIapi.spelltalk.com.brpanel-api
Serverserver.spelltalk.com.brWebhook + worker
White-labelspellserver.projetovendermais.com.brSeparate CapRover branch deploy

Three captain-definition files — one per deployable unit with independent Git branches.


Lessons Learned

  1. RAG with verifier is the differentiator — Grounded answers beat a larger model without guardrails.
  2. Handoff is a feature, not a fallback — Templates, relay, and worker logic are as critical as the bot.
  3. Meta sets the rules — Permissions, 24h windows, and app review directly shape the roadmap.
  4. Visual flows complement KB — Not all support is Q&A; scheduling and data collection need structured automation.
  5. Three-service split — Separating bot engine from admin API enables independent deploy and scale.

Screenshots

Production URLs (access requires tenant credentials):

ScreenURLDescription
Tenant dashboardpanel.spelltalk.com.brKB management, flow builder, conversation inbox
Flow builderpanel → FlowsVisual node editor (@xyflow/react)
Conversation viewpanel → ConversationsHandoff state, message history
Admin metricspanel → AnalyticsConversations/day, active customers

_Screenshots available on request during technical interviews._


Roadmap (at handoff)

PhaseItemStatus
v1.0WhatsApp RAG + handoffShipped
v1.1Visual flows + schedulingShipped
v1.2Instagram DM + comment triggersShipped
v2.0Advanced analytics dashboardPlanned
v2.1Voice channel integrationEvaluating

Relation to NovaDesk

Concepts from Spell that inform NovaDesk:

  • Multi-tenancy with tenant isolation (Auth Service, HelpDesk)
  • Async workers and queues (Notification Service, BullMQ)
  • RAG as extensibility pattern (future HelpDesk AI module)
  • Package entitlements model for SaaS billing
  • Webhook and API key integration patterns