Messaging and Notifications Architecture¶
Overview¶
This document describes how FarmCove's messaging system, abuse prevention mechanisms, and notification infrastructure work together to provide a secure, scalable, and user-friendly communication platform. The system enables bidirectional conversations across multiple channels (WhatsApp, SMS, web, in-app) while preventing abuse and maintaining conversation context.
Table of Contents¶
- System Components
- Architecture Overview
- Data Flow and Integration
- Storage Strategy
- Abuse Prevention Integration
- Real-time Capabilities
- Key Design Decisions
System Components¶
Core Tables¶
- Notifications System
notification- Stores all system notificationsnotification_template- Reusable notification templatesnotification_delivery- Tracks delivery status per channel-
notification_preference- User communication preferences -
Messaging System
conversation- Permanent container for user interactionsconversation_instance- Time-based message groupings (8-hour windows)message- Individual messages within instancesmessage_attachment- Media/file attachments-
conversation_summary- AI-generated summaries of closed instances -
Abuse Prevention
rate_limit_config- Configurable rate limits per channelabuse_pattern- Detected abuse patterns and actionsabuse_action_history- History of penalties applied
Architecture Overview¶
Bidirectional Communication Flow¶
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ │ │ │ │ │
│ Notification │────▶│ Messaging │◀────│ Abuse │
│ System │ │ System │ │ Prevention │
│ │◀────│ │────▶│ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
└───────────────────────┴─────────────────────────┘
│
┌──────▼──────┐
│ Supabase │
│ (Storage) │
└─────────────┘
Key Integration Points¶
- Notification → Conversation: Notifications can initiate conversations
- Message → Notification: Important messages can trigger in-app alerts
- Abuse Prevention: Monitors all messaging activity in real-time
- Shared Context: All systems reference the same user records
Data Flow and Integration¶
Scenario 1: Notification-Initiated Conversation¶
When a notification needs user response (e.g., transaction alert):
- Create Notification
- System creates notification in
notificationtable - Marks WhatsApp channel for delivery
-
Creates delivery record in
notification_delivery -
Start Conversation
- Sana (WhatsApp bot) sends notification
- System calls
get_or_create_conversation_instance() - Creates/reuses conversation in
conversationtable -
Links notification via
conversation_instance_id -
Track Message
- Creates outbound message in
messagetable - Links to notification via
notification_id -
Updates delivery status
-
Handle Response
- User reply creates inbound message
- Abuse prevention checks rate limits
- Conversation continues in same instance
Scenario 2: User-Initiated Conversation¶
When user starts conversation directly:
- Receive Message
- WhatsApp webhook receives message
- System checks rate limits via
check_rate_limits_and_abuse() -
If allowed, creates conversation structure
-
Optional Alert
- Can create in-app notification for visibility
- Notification links to conversation instance
-
User sees activity across all channels
-
Continue Dialog
- Messages stay in same instance for 8 hours
- After timeout, new instance created
- Old instance summarized by AI
Storage Strategy¶
Database Tables¶
All data is stored in Supabase (PostgreSQL) with Row-Level Security:
- conversation: Stores channel type, user association, status
- conversation_instance: Groups messages in 8-hour windows
- message: Stores content, direction, sender, timestamps
- notification: Stores templates, content, delivery preferences
- rate_limit_config: Defines limits per channel/user type
- abuse_pattern: Logs detected patterns with confidence scores
Time-Based Instance Management¶
Conversation (permanent)
└── Instance 1 (8 hours)
│ ├── Message 1
│ ├── Message 2
│ └── ... up to 500 messages
│
└── Instance 2 (new 8-hour window)
├── Message 501
└── ...
Benefits:
- Prevents unbounded growth
- Enables efficient AI summarization
- Maintains conversation context
- Supports quick message retrieval
Abuse Prevention Integration¶
Real-Time Protection¶
- Rate Limiting (Before Message Creation)
Per-Minute: 5 messages
Per-Hour: 60 messages
Per-Day: 200 messages
Per-Instance: 500 messages
- Pattern Detection (Every 5th Message)
- Spam: Identical repeated messages
- Flooding: <2 seconds between messages
-
Gibberish: Short meaningless content
-
Progressive Penalties
- 1st offense: Warning
- 2nd offense: 15-minute throttle
- 3rd offense: 1-hour throttle
- 4th offense: 24-hour suspension
- 5th+ offense: 7-day block
Storage in conversation Table¶
Rate limit data stored as JSONB in conversation:
{
"daily_message_count": 45,
"daily_reset_at": "2024-01-09T00:00:00Z",
"hourly_message_count": 12,
"hourly_reset_at": "2024-01-08T15:00:00Z",
"is_throttled": false,
"throttled_until": null
}
Real-time Capabilities¶
Enabled Tables¶
conversation- Live conversation updatesconversation_instance- Instance status changesmessage- Real-time message deliverynotification- Instant notification alerts
Use Cases¶
- Live chat in web interface
- Message status updates (sent → delivered → read)
- Instant abuse detection alerts
- Real-time conversation handoff
Key Design Decisions¶
1. Unified User Context¶
- Single user table referenced by all systems
- Consistent preferences across channels
- Unified permission and RLS policies
2. Channel-Agnostic Design¶
- Generic fields support any channel
- Easy to add new channels (Telegram, Email)
- Channel-specific data in JSONB metadata
3. Notification-Conversation Bridge¶
- Notifications can start conversations seamlessly
- Messages can trigger follow-up notifications
- Bidirectional flow with clear ownership
4. Time-Windowed Instances¶
- 8-hour windows balance context and performance
- Automatic summarization preserves history
- Prevents infinite conversation growth
5. Proactive Abuse Prevention¶
- Checks happen before resource consumption
- Progressive penalties educate users
- Configurable per channel and user type
6. AI-Ready Architecture¶
- Summaries provide historical context
- Pattern detection improves over time
- Ready for future AI enhancements
Benefits¶
- Seamless Integration: Notifications and messages work together naturally
- Scalable Design: Time-based instances prevent performance degradation
- User Protection: Robust abuse prevention maintains platform quality
- Multi-Channel: Single architecture supports all communication channels
- Complete Audit Trail: Every interaction is logged and traceable
- Real-Time Experience: Instant updates across all interfaces
- Flexible Configuration: Rate limits and rules can be adjusted per channel
Future Enhancements¶
- Cross-Channel Continuity: Start on WhatsApp, continue in-app
- Smart Routing: AI decides best channel for each notification
- Behavioral Learning: Personalized rate limits based on user history
- Rich Media: Enhanced support for videos, documents, voice notes
- Conversation Intelligence: AI-powered insights and suggestions