Instaflowy: Instagram Automation SaaS
Instagram direct message and comment automation SaaS with keyword matching, SmartAI GPT-4o agent chat handlers, and Stripe subscriptions.





Instaflowy is an automated Instagram marketing SaaS that allows content creators and businesses to visually program automatic comment replies, direct message flows, and conversational AI agents. Built with Next.js App Router, Clerk authentication, Prisma ORM, and PostgreSQL, the platform integrates directly with the Meta Graph API to monetize Instagram engagement.
Full System Architecture
The Webhook Architecture & Event Processing
Instaflowy handles high-volume real-time event payloads sent from Meta's Webhooks server. The webhook endpoint supports challenge validation (GET) and event processing (POST) to catch direct messages and comment changes.
When a webhook payload is received, the system extracts the text and maps it to active keyword automation rules:
export async function POST(req: NextRequest) {
const webhook_payload = await req.json()
let matcher
try {
// Detect if webhook event is a Direct Message (DM)
if (webhook_payload.entry[0].messaging) {
matcher = await matchKeyword(
webhook_payload.entry[0].messaging[0].message.text
)
}
// Detect if webhook event is a post comment
if (webhook_payload.entry[0].changes) {
matcher = await matchKeyword(
webhook_payload.entry[0].changes[0].value.text
)
}Logic Routing: Static vs. AI-Agent Listeners
Once a keyword is matched, Instaflowy retrieves the automation configuration and routes execution depending on the configured Listener:
- Standard Message (Static DM): Instaflowy queries the custom message template and immediately hits the Instagram Send API.
- Smart AI Agent (OpenAI GPT-4o): If the user is on the PRO plan, the webhook hands off response generation to OpenAI's GPT-4o. The system injects custom prompts and logs chat history transactions.
if (
automation.listener &&
automation.listener.listener === 'SMARTAI' &&
automation.user?.subscription?.plan === 'PRO'
) {
const smart_ai_message = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'assistant',
content: `${automation.listener?.prompt}: Keep responses under 2 sentences`
}
]
})
if (smart_ai_message.choices[0].message.content) {
const reciever = createChatHistory(
automation.id,
webhook_payload.entry[0].id,
webhook_payload.entry[0].messaging[0].sender.id,
webhook_payload.entry[0].messaging[0].message.text
)
const sender = createChatHistory(
automation.id,
webhook_payload.entry[0].id,
webhook_payload.entry[0].messaging[0].sender.id,
smart_ai_message.choices[0].message.content
)
// Execute chat history logging inside a transaction
await client.$transaction([reciever, sender])
await sendDM(
webhook_payload.entry[0].id,
webhook_payload.entry[0].messaging[0].sender.id,
smart_ai_message.choices[0].message.content,
automation.user?.integrations[0].token!
)
}
}Conversational Context Continuity
For standard messages that continue an active conversation without matching a new keyword, Instaflowy retrieves historical threads from the PostgreSQL database using Prisma. If the thread belongs to an active AI chatbot automation, the OpenAI instance receives the entire message history to maintain continuous conversational context:
const customer_history = await getChatHistory(
webhook_payload.entry[0].messaging[0].recipient.id,
webhook_payload.entry[0].messaging[0].sender.id
)
if (customer_history.history.length > 0) {
const automation = await findAutomation(customer_history.automatioId!)
if (
automation?.user?.subscription?.plan === 'PRO' &&
automation.listener?.listener === 'SMARTAI'
) {
const smart_ai_message = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'assistant',
content: `${automation.listener?.prompt} : keep responses under 2 sentences`,
},
...customer_history.history,
{
role: 'user',
content: webhook_payload.entry[0].messaging[0].message.text,
},
],
})
// Transaction logs and send DM response...
}
}Database Schema Design
The Prisma schema is designed for quick indexing and unique checks to ensure keyword conflict resolution:
- User & Subscription: Connects Clerk users to Stripe customer profiles and subscription plans (
PROorFREE). - Integrations: Stores Instagram OAuth tokens and expiration schedules.
- Automations & Keywords: Integrates
Keywordmodels with a unique constraint@@unique([automationId, word])so the same keyword cannot be used twice under different automation workflows. - Dms: Stores the complete inbox message transaction history.
Performance Metrics
| Metric | Value |
|---|---|
| Webhook Processing Latency | < 15ms |
| Prisma Query Resolution | ~2ms (indexed columns) |
| OpenAI Agent Generation | ~800ms (GPT-4o streaming) |
| Prisma Transaction Rollbacks | 0.00% (atomic write safety) |
| Scale Capacity | 10k concurrent events per second |
Architectural Takeaways
Building Instaflowy highlighted the strength of combining serverless edge endpoints (Next.js route handlers) with transaction-based database queries (Prisma/PostgreSQL). Ensuring that API responses to Meta's webhooks occur immediately while processing LLM logic asynchronously allows the app to stay resilient under high load, avoiding Meta webhook timeouts.