Skip to content

Repository files navigation

⚠️ PROTECTED CODE - DO NOT COPY ⚠️

This is a personal project by Meet Jain. This repository is publicly visible for demonstration purposes only.

Author: Meet Jain

  • This project is protected. Do not copy, fork, or reuse without permission.
  • Unauthorized use is strictly prohibited. Only the official deployment is allowed to run.

Legal Protection

This project is protected by copyright law and includes proprietary security measures. Unauthorized use or attempts to circumvent security measures may result in legal consequences.

Contact

For any inquiries about this project please contact: meetofficialhere@gmail.com

Branch Message Hub

Branch Message Hub is a demonstration-grade customer support messaging platform that models how agents triage, investigate, and respond to inbound customer issues in real time.

Table of Contents

Project Overview

Branch Message Hub centralizes inbound customer messages, enriches them with contextual profile metadata, classifies urgency, and streams updates to connected support agents in real time.

It solves a common operations problem: fragmented support workflows where ticket intake, prioritization, and response history are spread across disconnected systems.

The project is relevant to teams building fintech, e-commerce, and SaaS support operations where response speed, triage quality, and shared visibility directly affect customer trust.

Objectives

This project demonstrates:

  • Event-driven system design with REST for commands and WebSockets for state propagation
  • Real-time multi-agent collaboration patterns
  • Pragmatic data modeling in MongoDB for conversational records
  • Scalable separation of concerns between client, API, and persistence layers
  • Practical engineering trade-offs for a demo system that still reflects production thinking

Use Cases

Real-world scenarios:

  • Support agents handling loan disbursement and account-access issues with urgency awareness
  • Team leads monitoring queue pressure and response quality across agents
  • Product and operations teams validating support tooling workflows before larger platform investment

Example user flows:

  1. Customer issue arrives through /api/incoming
  2. Backend classifies urgency and enriches profile context
  3. New message is stored and broadcast to all live agent sessions
  4. Agent opens thread, uses canned response or custom reply
  5. Reply is persisted and propagated in real time to all viewers

Core Features

Message Intake and Triage

  • Structured inbound message ingestion via API
  • Rule-based urgency classification for fast prioritization
  • Search across customer identity and message content

Agent Workspace

  • Shared inbox with near-instant updates
  • Detail view with conversation history and profile context
  • Quick-reply templates for consistent handling

Data Enrichment

  • Customer profile metadata attached to messages at ingestion
  • Conversation thread persistence with timestamped agent replies

Data Operations

  • CSV import utility for bootstrapping realistic historical data
  • Support for multiple CSV schema variants in importer logic

System Architecture

High-level components:

  • Client (React + Vite): Agent-facing single-page application for queue management and responses
  • Server (Node.js + Express + Socket.io): API, triage logic, enrichment, and event broadcasting
  • Database (MongoDB + Mongoose): Persistent store for messages, replies, and profile metadata
  • External/Supporting Inputs: CSV ingestion pipeline for historical sample data

Communication patterns:

  • REST for retrieval and command operations
  • Socket.io channels for live event fan-out (new_message, message_updated)

Architecture Diagram

┌─────────────────┐         ┌─────────────────┐
│  React Client   │◄───────►│  Express Server │
│   (Vite SPA)    │  HTTP   │   + Socket.io   │
└────────┬────────┘  REST   └────────┬────────┘
         │                            │
         │ Socket.io                  │ Mongoose
         │ WebSocket                  │ ODM
         │                            │
         └────────────────────────────┼─────────┐
                                      │         │
                              ┌───────▼──────┐  │
                              │   MongoDB    │  │
                              │   Database   │  │
                              └──────────────┘  │
                                                │
                                    ┌───────────▼──────────┐
                                    │  CSV Import Script   │
                                    └──────────────────────┘

This architecture keeps user interaction latency low by combining durable writes in MongoDB with immediate state distribution through WebSockets.

Data Flow / Request Lifecycle

Incoming Message Lifecycle

  1. Client or integration posts payload to POST /api/incoming
  2. Server validates required fields
  3. Urgency detection executes against message text
  4. Profile enrichment data is generated and attached
  5. Document is persisted to MongoDB
  6. new_message event is emitted to connected clients
  7. UI prepends the message in each active inbox

Reply Lifecycle

  1. Agent submits reply via POST /api/messages/:id/reply
  2. Server validates actor and content
  3. Target message is loaded and updated with reply entry
  4. Updated document is persisted
  5. message_updated event is broadcast
  6. All clients reconcile updated thread state

Project Structure

BranchMessageHub/
├── client/
│   ├── src/
│   │   ├── App.jsx
│   │   ├── main.jsx
│   │   └── styles.css
│   ├── package.json
│   └── vite.config.js
├── server/
│   ├── models/
│   │   └── message.js
│   ├── index.js
│   ├── import_csv.js
│   ├── canned.json
│   └── package.json
├── branch_customer_messages.csv
├── Branch_Messaging_API.postman_collection.json
├── ARCHITECTURE.md
└── README.md

Why this structure:

  • Clear client/server boundary enables independent scaling and deployment
  • Server modules isolate transport logic, schema definitions, and data tooling
  • Artifacts like Postman collection and architecture docs accelerate demonstration and evaluation

Tech Stack & Justification

  • React 18: Mature component model for responsive support console interactions
  • Vite 5: Fast build/dev feedback loop for UI iteration
  • Node.js + Express 4: Lightweight API runtime with minimal ceremony
  • Socket.io 4: Robust real-time abstraction over WebSockets with fallback capabilities
  • MongoDB 6 + Mongoose 7: Flexible schema evolution for message metadata and threaded replies
  • csv-parser: Efficient stream-based ingestion for historical dataset import

Key Design Decisions

  • Single message aggregate: Replies embedded inside the message document simplify retrieval for thread rendering
  • Hybrid transport model: REST handles deterministic commands; Socket.io handles asynchronous state updates
  • Server-side urgency classification: Centralized triage logic avoids inconsistent priority interpretation across clients
  • Profile enrichment at write-time: Improves agent context availability without extra read hops

Trade-offs

  • Rule-based urgency vs ML model: Faster to implement and explain, but less adaptive to language nuance
  • Embedded replies vs separate collection: Better read performance for thread views, weaker flexibility for very large threads
  • Broadcast-to-all updates vs room-based targeting: Simpler event topology, potentially higher unnecessary fan-out at scale
  • Minimal auth model in demo: Keeps focus on messaging architecture but does not represent production identity controls

API Design

Key endpoints:

  • GET /api/messages?q=<term>: Returns up to 200 most recent messages, optionally filtered
  • POST /api/incoming: Ingests a customer message and triggers triage + broadcast
  • POST /api/messages/:id/reply: Appends an agent reply and emits update events
  • GET /api/canned: Returns predefined response templates

Sample request:

POST /api/incoming
Content-Type: application/json

{
  "customerName": "Asha Patel",
  "customerEmail": "asha@example.com",
  "message": "My loan was approved but funds are not disbursed"
}

Sample response:

{
  "_id": "665f4a1f9c1f1e6c4d13a1d5",
  "customerName": "Asha Patel",
  "customerEmail": "asha@example.com",
  "message": "My loan was approved but funds are not disbursed",
  "urgency": "high",
  "customerProfile": {
    "accountAge": "2 years",
    "loanStatus": "Approved",
    "totalLoans": 3,
    "creditScore": 701,
    "lastActivity": "2026-04-20T11:24:58.000Z"
  },
  "replies": [],
  "createdAt": "2026-04-23T15:00:10.120Z",
  "updatedAt": "2026-04-23T15:00:10.120Z"
}

API philosophy:

  • Keep endpoints task-oriented and operationally clear
  • Return full updated entities after mutations to simplify UI reconciliation
  • Favor predictable contract shape over aggressive micro-optimization

Data Modeling

Primary entity: Message

  • Identity: _id
  • Customer fields: customerName, customerEmail
  • Content fields: message, urgency
  • Temporal fields: createdAt, updatedAt
  • Enrichment: customerProfile object
  • Conversation history: replies[] subdocuments (agentName, reply, createdAt)

Relationship model:

  • One message has many reply entries
  • Reply entries are stored as embedded documents to optimize thread reads

Security Considerations

Current implementation demonstrates baseline controls:

  • Input presence validation on write endpoints
  • CORS enabled for cross-origin client access
  • Basic error handling to prevent process crashes on malformed requests

Production hardening priorities:

  • AuthN/AuthZ for agent identity and endpoint protection
  • Request schema validation with explicit allowlists
  • Rate limiting and abuse protection on inbound endpoints
  • WebSocket origin restrictions and token-based session validation
  • Secrets management for database credentials and environment isolation

Performance Considerations

  • Message listing constrained with descending index-like query pattern and result limit
  • Single-document thread reads reduce query fan-out
  • Real-time incremental updates avoid expensive full-list polling loops
  • Stream-based CSV parsing prevents loading entire raw file into memory at once

Scalability Approach

Current path:

  • Stateless API instances behind a load balancer
  • Shared MongoDB backing store
  • Socket.io horizontal scale via adapter/backplane (e.g., Redis) when moving beyond single node

Scale evolution strategy:

  • Separate ingestion and processing pipelines for heavy triage/enrichment workloads
  • Introduce message partitioning and archival policies for long-term retention
  • Move from in-memory heuristics to externalized classification service if throughput increases

Observability & Monitoring

Recommended instrumentation model:

  • Structured logs for endpoint latency, validation failures, and broadcast events
  • Metrics for queue depth, reply latency, and urgency distribution
  • Error tracking for API exceptions and client-side action failures
  • Availability probes for API and database health

Current code includes console logging hooks suitable as initial insertion points for structured telemetry.

Testing Strategy

Current repository has no formal automated test suite. A production-ready strategy would include:

  • Unit tests: urgency classifier, validation paths, enrichment behavior
  • Integration tests: API contract tests against ephemeral MongoDB
  • Realtime tests: event emission and client reconciliation scenarios
  • Data tests: CSV import compatibility across schema variants

The existing Postman collection can serve as an initial contract verification artifact.

Failure Handling

Current behavior:

  • API returns 400 for missing required fields and 404 for missing message IDs
  • Server returns 500 on unhandled exceptions
  • Client surfaces send-reply failures to users and preserves current state

Recommended fallbacks:

  • Retry-safe idempotency strategy for ingestion
  • Dead-letter workflow for malformed imports
  • Circuit-breaker style handling around downstream dependencies

Constraints & Assumptions

  • Demonstration-scale usage with moderate concurrent agents
  • Message retrieval capped to recent subset (200 records per query)
  • Near-real-time delivery expected, not strict guaranteed ordering across distributed nodes
  • Customer profile enrichment is synthetic and intended for UX realism, not regulatory decisioning

Deployment Approach

A practical deployment model:

  • Containerized server and database in isolated environments
  • Static client assets served through CDN or edge hosting
  • Environment-based configuration for API base URL and Mongo connection
  • CI pipeline for build validation, image publication, and staged rollout

Limitations

  • No enterprise identity, role model, or audit-grade authorization
  • Rule-based urgency logic can misclassify ambiguous language
  • No pagination strategy beyond fixed message limit
  • No persistence or analytics model for agent-level productivity insights
  • Limited built-in observability and no distributed tracing

Future Improvements

  • Replace keyword triage with an ML/NLP classifier and confidence scoring
  • Add pagination, cursor-based querying, and archival storage
  • Introduce role-based access control and authenticated WebSocket channels
  • Implement SLA dashboards and operational analytics
  • Add automated test coverage and CI quality gates
  • Extend API to support assignment workflows and escalation routing

Learnings

  • Real-time systems benefit from explicit separation between state mutation and event distribution
  • Early schema decisions materially affect UX responsiveness and query cost
  • Even demo systems are stronger when trade-offs are stated and intentional
  • Operational concerns (observability, failure modes, scale path) should be documented from the start

Author

  • Name: Meet Jain

Contact

Connect with me through the following platforms:

LinkedIn Twitter

Social Media and Platforms

Discord Instagram Stack Overflow Medium Hashnode

Support Me

If you like my work, you can support me by buying me a coffee Thanks!

Buy Me A Coffee

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages