The Fundamental Architecture Shift
Traditional chatbots operate on a simple loop:- User asks question
- LLM generates answer
- Wait for next question
- What the user is doing right now
- What inventory just changed
- Which delivery slots opened
- When payment providers are struggling
- What other users are experiencing
Reactive Model
User initiates → AI responds → Wait for next question
Event-Driven Model
Continuous event streams → AI evaluates context → Proactive action
The Core Components
Here’s the high-level architecture:Part 1: The Three Event Types
Your AI assistant needs to consume events from three distinct sources to build complete situational awareness.1. User Events (Browser-Generated)
These are captured in real-time as users interact with your site: Behavioral signals:- Page views and routing changes
- Scroll depth and dwell time
- Mouse movement patterns
- Form input changes
- Idle detection
- Product views
- Basket state changes
- Checkout step progression
- Error banner displays
- Feature interactions
2. System Events (Commerce Platform)
These come from your backend services and inventory systems: Inventory signals:- Stock level changes
- Variants becoming unavailable
- Reservation failures
- Restock notifications
- Slot capacity changes
- New slots released
- ETA updates
- Fulfillment center congestion
- Price drops
- Discount eligibility
- Promotion activation
- Payment service degradation
- API latency spikes
- Feature flag changes
3. External Integration Events
These arrive from third-party services and external systems: Logistics:- Courier delay estimates (DPD, UPS)
- Weather-based delivery impacts
- Same-day cutoff time changes
- Stripe/Adyen health status
- Payment method availability
- Fraud score changes
- CRM/CDP profile updates
- Loyalty tier changes
- Segmentation assignments
- Personalization engine outputs
Part 2: WebSocket Architecture
You need two separate WebSocket channels to avoid interference and simplify backpressure handling.Outbound Channel (Browser → Backend)
Purpose: Stream raw user events to the backend Endpoint:wss://events.example.com/client
Payload structure:
- Use Web Workers to keep event capture lightweight
- Implement debouncing to prevent event floods (e.g., mouse movement)
- Batch events if network is slow (max 100ms buffer)
- Heartbeat every 15-30 seconds to detect disconnection
Inbound Channel (Backend → Browser)
Purpose: Receive agent commands and execute actions Endpoint:wss://actions.example.com/client
Command types:
1. UI Suggestions
Using two separate channels prevents action commands from getting stuck behind high-volume user event streams, ensuring responsive UI updates even under load.
Part 3: The Signal Derivation Layer
Here’s where most implementations fail. If you push raw events directly to your LLM agent, you’ll create two critical problems:Problem 1: Event Floods
When 500 users are online and one delivery slot opens:- Backend generates 50 low-level updates as services reconcile
- Without filtering, 500 agent instances receive 50 events each
- Each agent tries to send a suggestion
- Users get spammed with outdated suggestions
- The slot is gone before anyone can claim it
Problem 2: Lack of Semantic Meaning
Raw events are noisy:The Solution: Signal Derivation Architecture
- Deduplication: Collapse identical events within a time window (e.g., 3 seconds)
- Aggregation: Combine related events into higher-order signals
- Threshold filtering: Only emit signals when thresholds are crossed
- Trend detection: Track changes over time (stock trending down, slot availability improving)
- Semantic enrichment: Add business context and meaning
Part 4: The Relevance Router
Now you have clean semantic signals, but you still need to decide which users should receive them. This is the hardest part of the system because it determines whether your AI feels helpful or annoying.The Routing Decision
For the delivery slot example above, you need to filter 500 active users down to maybe 6 who should be notified. Routing criteria: Geographic relevance:- User’s delivery postcode matches the slot’s zone
- User is currently on the checkout delivery step
- User has been dwelling on delivery options (indicating hesitation)
- User tried to select a slot but none were available
- User historically prefers evening slots
- User previously complained about delivery timing
- User has abandoned cart at delivery step before
- VIP customers get first access to scarce slots
- High cart value users get priority
- Users closest to conversion get priority
Priority Scoring Example
Handling Scarcity and Conflicts
When multiple users might want the same scarce resource: 1. Centralized locking- Offer to highest-priority user first
- If they ignore/decline, release lock
- Offer to next-highest priority user
- Repeat until claimed or expired
- If slot is taken, suggest similar alternatives
- Use knowledge graph to find comparable options
Part 5: The Knowledge Graph Layer
You don’t need a knowledge graph for everything, but it’s incredibly useful for relationship traversal and semantic reasoning.The Three-Layer Model
Layer 1: Domain Model (Knowledge Graph)- Purpose: Store static and slow-changing relationships
- Technology: Neo4j, Amazon Neptune, or even Postgres with recursive CTEs
- Contents:
- Products → Variants → Stock levels
- Postcodes → Delivery Zones → Slot Pools
- Users → Preferences → Historical choices
- Payment Methods → Risk Profiles
- Categories → Substitutes → Alternatives
- Purpose: Real-time, high-frequency event processing
- Technology: Kafka Streams, Flink, or Redis Streams
- DON’T use the KG for this: Graphs are too slow for high-throughput event processing
- Purpose: Combine KG relationships with real-time session data
- Pattern: Query KG for structural relationships, then filter by live session state
Example: Multi-Layer Decision
Scenario: Size M of a popular item drops to 3 units in stock Layer 1 (KG): Find related users- User currently viewing this product: Priority 1
- User has item in cart: Priority 2
- User viewed in last 10 min: Priority 3
Part 6: The LLM Agent Decision Layer
Now your agent receives clean, semantically meaningful signals matched to specific users. The final step is deciding how to act.What the Agent Sees
The LLM receives a rolling context window containing:The Agent’s Policy Evaluation
The agent must answer several questions: 1. Should I react to this signal?Example: Multi-Signal Inference
The power comes from combining multiple signals: Signal 1: User hovering on size M (behavior) Signal 2: Stock for size M drops to 3 units (inventory) Signal 3: User has this brand in wishlist (preference) Signal 4: Item is frequently out of stock (historical) Agent reasoning:Agent Prompt Template
Part 7: Real-World Use Cases
Let me show you how this plays out in practice for a platform like Rohlik.cz (grocery delivery).Use Case 1: Proactive Inventory Management
Scenario: User viewing organic milk, stock drops to 2 units Event stream:user.product_view- User lands on organic milk pageinventory.stock_update- Stock drops from 5 to 2user.dwell_increase- User spending time reading reviews
Use Case 2: Dynamic Delivery Optimization
Scenario: User stuck on delivery selection, new slot opens Event stream:user.checkout_step- User reaches delivery selectionuser.long_dwell- 45 seconds with no actiondelivery.slot_opened- 6-8pm slot becomes available- KG query shows user historically prefers evening slots
Use Case 3: Payment Error Prevention
Scenario: Payment provider degraded, user approaching checkout Event stream:user.checkout_step- User enters payment stepstripe.provider_degraded- Stripe reporting issuesuser.payment_method_selected- User selects card payment
Use Case 4: Personalized Recall
Scenario: User who frequently orders eggs isn’t adding them Event stream:user.session_start- Returning user logs in- KG query shows user orders eggs 85% of the time
user.approaching_checkout- Cart value > $50, no eggs- No eggs in current cart
Use Case 5: Dietary Preference Learning
Scenario: User browsing dairy-free products consistently Event stream:user.product_views- 8 dairy-free items viewed- Pattern detection: 0 dairy products viewed
user.category_switch- User switches to cheese category- Inference: User likely dairy-intolerant
Part 8: Implementation Patterns
Let’s get tactical about how to build this.Browser Event Capture
Use Web Workers to avoid blocking the main thread:Event Bus Selection
For MVP, you can start simple: Option 1: Postgres LISTEN/NOTIFY (MVP)Signal Derivation Implementation
Agent Runtime Implementation
Part 9: Design Considerations
User Experience Principles
1. Frequency throttling is critical
2. Priority-based interruption
Only interrupt the user when:
- High priority: Scarcity alerts, payment errors, time-sensitive opportunities
- Medium priority: Delivery optimizations, personalized suggestions
- Low priority: Preference learning, non-urgent reminders
- Dismiss button on suggestions
- “Don’t show suggestions like this” option
- Settings panel for notification preferences
- Complete opt-out capability
Performance Optimization
Use Server-Sent Events (SSE) for lower complexity:- Simpler than WebSocket for one-way communication
- Automatic reconnection
- Works with HTTP/2 multiplexing
- Better for low-frequency updates
Privacy & Security
Event data minimization:Part 10: The Maturity Spectrum
Organizations evolve through predictable stages when building event-driven AI:Level 0: Traditional Reactive Chatbot
Characteristics:- User asks question → Bot responds
- No awareness of context
- No proactive assistance
- Generic, one-size-fits-all responses
Level 1: Event-Aware Chatbot
Characteristics:- Bot knows what page user is on
- Can see cart contents
- Context-aware responses
- Still waits for user to ask
- Basic browser event capture
- Simple context passing to LLM
- No signal derivation
Level 2: Proactive Assistant
Characteristics:- Anticipates needs based on behavior
- Sends helpful suggestions unprompted
- Aware of inventory and system state
- Basic relevance filtering
- Full event streaming architecture
- Signal derivation layer
- Simple relevance routing
- LLM agent decision layer
Level 3: Coordinated Intelligence
Characteristics:- Server-wide optimization
- Multi-user coordination
- Scarcity handling with centralized locking
- Knowledge graph integration
- Sophisticated priority routing
- Everything from Level 2
- Knowledge graph layer
- Advanced relevance scoring
- Conflict resolution
- Cross-session learning
Getting Started: Your MVP
Don’t try to build everything at once. Here’s a practical 4-week MVP plan:Week 1: Event Capture
Goal: Start streaming browser events Tasks:- Implement Web Worker event capture
- Set up basic WebSocket outbound channel
- Capture 3-5 key events (page view, cart update, checkout step)
- Log events to database
Week 2: Signal Derivation
Goal: Turn raw events into semantic signals Tasks:- Build simple signal deriver for 1-2 event types
- Implement deduplication (3 second window)
- Create “user stuck” detection (dwell time > 30s)
- Emit structured signals
Week 3: Agent Decision Layer
Goal: LLM evaluates signals and decides actions Tasks:- Set up Claude API integration
- Build agent prompt template
- Implement frequency throttling (max 2 per session)
- Create decision logging
Week 4: Action Execution
Goal: Close the loop - send actions to browser Tasks:- Implement WebSocket inbound channel
- Build browser action executor
- Create UI for displaying suggestions
- Add user controls (dismiss, preferences)
Measuring Success
Track these metrics before and after launch:Conclusion
The difference between a reactive chatbot and an always-on AI assistant isn’t just about technology—it’s about architecture. When your AI can:- See what users are doing in real-time
- Know what’s happening with inventory, delivery, and systems
- Anticipate needs before users get stuck
- Act proactively with perfect timing
Next in This Series
This article covered the comprehensive architecture. In future articles, I’ll go deeper on:- Building the Signal Derivation Layer - Code-level implementation patterns for real-time event processing
- Knowledge Graph Design for E-Commerce - Schema design, query patterns, and integration strategies
- LLM Agent Orchestration - Prompt engineering, context management, and decision quality optimization
- Production Operations - Monitoring, debugging, scaling, and cost optimization