Experience seamless messaging with enterprise-grade architecture, real-time communication, and beautiful UI
π― chatty-microservices.vercel.app
- Features
- Architecture
- Technology Stack
- Apache Kafka Integration
- Nginx Configuration
- Server-Sent Events (SSE)
- Redis Integration
- Microservices
- Getting Started
- API Documentation
- Real-time Features
- Security
- Contributing
- License
- JWT-based authentication with secure token validation
- User registration and login with password hashing
- Protected routes and API endpoints
- Session management with refresh tokens
- Instant message delivery with WebSocket connections
- One-to-one private conversations
- File sharing and media support
- Message status indicators (sent, delivered, read)
- Typing indicators and online presence
- Add contacts by email or username
- Contact request system with accept/reject functionality
- Real-time contact list updates
- Search and discover users
- Beautiful, responsive design with Tailwind CSS
- Dark/Light mode toggle
- Smooth animations with Framer Motion
- Mobile-first responsive layout
- Paper-inspired design system
- Microservices architecture with Spring Boot
- Service discovery with Eureka
- API Gateway for centralized routing
- gRPC for efficient inter-service communication
- Real-time updates with WebSocket and STOMP
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β React + TypeScript + Redux + WebSocket + SSE + Tailwind CSS β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ
β REVERSE PROXY β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Nginx (Port 80/443) β
β β’ SSL termination & Load balancing β
β β’ Static file serving & Compression β
β β’ Request routing & Security headers β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ
β API GATEWAY β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Spring Cloud Gateway (Port 8081) β
β β’ Request routing & Load balancing β
β β’ CORS handling & Rate limiting β
β β’ SSE endpoint management β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ
β MICROSERVICES LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ β
β β AuthService β β UserService β β ChatService β β
β β (Port 8082) β β (Port 8084) β β (Port 8085) β β
β β gRPC: 9092 β β gRPC: 9094 β β SSE Support β β
β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ β
β β
β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ β
β βNotificationSvc β β PaymentService β β EurekaServer β β
β β (Port 8086) β β (Port 8087) β β (Port 8761) β β
β β gRPC: 9096 β β β β β β
β β SSE Support β β β β β β
β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ
β MESSAGE STREAMING β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Apache Kafka (Port 9092) β
β β’ Event streaming & Message queuing β
β β’ Real-time data processing β
β β’ Microservice communication β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ
β DATA LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β PostgreSQL Database (Port 5432) Redis Cache (Port 6379) β
β β’ User data & authentication β’ Session management β
β β’ Chat messages & conversations β’ Real-time caching β
β β’ Contact relationships β’ Pub/sub messaging β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- React 18.3.1 - Modern UI library with hooks and context
- TypeScript 5.8.3 - Type-safe JavaScript development
- Redux Toolkit - State management with RTK Query
- Tailwind CSS - Utility-first CSS framework
- Framer Motion - Animation library for React
- WebSocket + STOMP - Real-time bi-directional communication
- Server-Sent Events (SSE) - Real-time server-to-client streaming
- Vite - Fast build tool and development server
- Spring Boot 3.5.0 - Java-based microservices framework
- Spring Cloud Gateway - API Gateway and routing
- Spring Security - Authentication and authorization
- Spring Data JPA - Database abstraction layer
- gRPC - High-performance RPC framework
- WebSocket + STOMP - Real-time messaging
- Server-Sent Events (SSE) - Real-time event streaming
- Eureka - Service discovery and registration
- Apache Kafka - Distributed event streaming platform
- Kafka Connect - Data integration framework
- Kafka Streams - Stream processing library
- Schema Registry - Schema management and evolution
- Nginx - Reverse proxy and load balancer
- Docker - Containerization
- Docker Compose - Multi-container orchestration
- Maven - Build automation and dependency management
- Vercel - Frontend deployment
- CI/CD - Automated testing and deployment
- PostgreSQL - Primary relational database
- Redis - Session storage, caching, and pub/sub messaging
- File Storage - Media and file uploads
Redis serves as a critical component in the Chatty platform, providing high-performance caching and session management capabilities:
- Session Management: User authentication sessions and JWT token storage
- Caching Layer: User profiles, chat metadata, and frequently accessed data
- Real-time Features: WebSocket session management and user presence tracking
- Message Queuing: Temporary storage for offline message delivery
- UserService: User session persistence and profile caching
- AllServices: Centralized Redis configuration and shared caching
# Redis Configuration
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=0
spring.redis.timeout=2000ms
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0- Performance: Sub-millisecond response times for cached data
- Scalability: Distributed caching across multiple service instances
- Reliability: Session persistence across service restarts
- Real-time: Fast pub/sub messaging for live features
Apache Kafka serves as the backbone for event-driven architecture and real-time data streaming in the Chatty platform:
- Event Streaming: Real-time message delivery and event propagation
- Microservice Communication: Asynchronous service-to-service messaging
- Data Processing: Stream processing for analytics and monitoring
- Event Sourcing: Audit trails and event history tracking
- chat-messages: Real-time chat message streaming
- user-events: User activity and presence updates
- notifications: Push notification delivery
- system-events: System-wide event logging and monitoring
- ChatService: Publishes chat messages and conversation events
- UserService: Publishes user activity and profile updates
- NotificationService: Publishes notification events
- AuthService: Publishes authentication and security events
- NotificationService: Consumes events to trigger notifications
- ChatService: Consumes events for message ordering and delivery
- Analytics Service: Consumes events for real-time analytics
- Audit Service: Consumes events for compliance and logging
# Kafka Configuration
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=chatty-service-group
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer- Scalability: Horizontal scaling with partitioned topics
- Reliability: Message durability and fault tolerance
- Performance: High-throughput, low-latency message processing
- Decoupling: Loose coupling between microservices
Nginx acts as a reverse proxy, load balancer, and SSL terminator for the Chatty platform:
- SSL Termination: HTTPS encryption and certificate management
- Load Balancing: Traffic distribution across multiple service instances
- Static File Serving: Efficient serving of frontend assets
- Request Routing: Path-based routing to appropriate services
- Security Headers: Implementation of security best practices
- Gzip Compression: Reduces bandwidth usage and improves performance
- Rate Limiting: Prevents abuse and ensures fair resource usage
- Caching: Static content caching for improved response times
- WebSocket Proxying: Support for real-time WebSocket connections
- SSE Support: Server-Sent Events proxying for real-time updates
server {
listen 80;
listen 443 ssl http2;
server_name api.chatty.com;
# SSL Configuration
ssl_certificate /etc/nginx/ssl/chatty.crt;
ssl_certificate_key /etc/nginx/ssl/chatty.key;
# Gzip Configuration
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain application/json application/javascript text/css;
# API Gateway Proxy
location /api/ {
proxy_pass http://api-gateway:8081/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# WebSocket Proxy
location /ws/ {
proxy_pass http://api-gateway:8081/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
# SSE Proxy
location /sse/ {
proxy_pass http://api-gateway:8081/sse/;
proxy_set_header Cache-Control no-cache;
proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
}
}- Performance: Efficient static file serving and caching
- Security: SSL termination and security header management
- Scalability: Load balancing and connection pooling
- Reliability: Health checks and failover support
Server-Sent Events provide real-time, unidirectional communication from server to client:
- Live Notifications: Real-time push notifications without polling
- Chat Updates: Live message delivery and typing indicators
- User Presence: Real-time online/offline status updates
- System Alerts: Server-side event notifications to clients
- Spring Boot SSE: Built-in SSE support with SseEmitter
- Event Streaming: Continuous event stream to connected clients
- Auto-Reconnection: Client-side automatic reconnection handling
- Event Filtering: Selective event delivery based on user context
@RestController
public class SSEController {
@GetMapping(value = "/sse/notifications", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter subscribeToNotifications(@RequestParam String userId) {
SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
// Register emitter for user
sseService.addEmitter(userId, emitter);
// Handle connection cleanup
emitter.onCompletion(() -> sseService.removeEmitter(userId, emitter));
emitter.onTimeout(() -> sseService.removeEmitter(userId, emitter));
return emitter;
}
@Service
public class SSEService {
private final Map<String, List<SseEmitter>> userEmitters = new ConcurrentHashMap<>();
public void sendNotification(String userId, Object data) {
List<SseEmitter> emitters = userEmitters.get(userId);
if (emitters != null) {
emitters.forEach(emitter -> {
try {
emitter.send(SseEmitter.event()
.name("notification")
.data(data)
.id(UUID.randomUUID().toString()));
} catch (Exception e) {
emitter.completeWithError(e);
}
});
}
}
}
}// SSE Client Service
export class SSEService {
private eventSource: EventSource | null = null;
connect(userId: string) {
this.eventSource = new EventSource(`/sse/notifications?userId=${userId}`);
this.eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
this.handleNotification(data);
};
this.eventSource.onerror = (error) => {
console.error('SSE connection error:', error);
this.reconnect(userId);
};
}
private reconnect(userId: string) {
setTimeout(() => {
this.connect(userId);
}, 5000);
}
private handleNotification(data: any) {
// Dispatch to Redux store or handle notification
store.dispatch(addNotification(data));
}
}- Real-time: Instant server-to-client communication
- Efficiency: Lower overhead compared to polling
- Simplicity: Built-in browser support and automatic reconnection
- Scalability: Efficient handling of many concurrent connections
- User authentication and authorization
- JWT token generation and validation
- Password hashing and security
- Session management
- User profile management
- User search and discovery
- Profile picture and settings
- User data persistence
- Message handling and storage
- Real-time message delivery
- File upload and sharing
- Message history and pagination
- Contact request management
- Real-time notifications
- Push notification system
- Notification preferences
- Payment processing
- Transaction history
- Billing and subscriptions
- Payment gateway integration
- Request routing and load balancing
- CORS and security headers
- Rate limiting and throttling
- Request/response transformation
- Service discovery and registration
- Health monitoring
- Load balancing configuration
- Service mesh coordination
- Java 21 or later
- Node.js 18 or later
- PostgreSQL 14 or later
- Redis 6.0 or later
- Maven 3.8 or later
- Git
-
Clone the repository
git clone https://github.com/your-username/chatty-microservices.git cd chatty-microservices -
Setup PostgreSQL Database
CREATE DATABASE chatty_microservices; CREATE USER chatty_user WITH ENCRYPTED PASSWORD 'your_password'; GRANT ALL PRIVILEGES ON DATABASE chatty_microservices TO chatty_user;
-
Setup Redis
# Install Redis (Ubuntu/Debian) sudo apt update sudo apt install redis-server # Start Redis server sudo systemctl start redis-server sudo systemctl enable redis-server # Verify Redis is running redis-cli ping # Should return: PONG
-
Configure Application Properties
# Update database and Redis credentials in each service's application.properties cd server/AuthService/src/main/resources # Edit application.properties with your database and Redis credentials
-
Build and Start Services
# Build proto definitions first cd server/chattyprotos mvn clean install # Start Eureka Server cd ../EurekaServer mvn spring-boot:run # Start services in this order: cd ../AuthService && mvn spring-boot:run & cd ../UserService && mvn spring-boot:run & cd ../NotificationService && mvn spring-boot:run & cd ../ChatService && mvn spring-boot:run & cd ../PaymentService && mvn spring-boot:run & cd ../Api_Gateway && mvn spring-boot:run &
-
Install Dependencies
cd client npm install -
Configure Environment
# Create .env file cp .env.example .env # Edit .env with your API endpoints
-
Start Development Server
npm run dev
-
Build for Production
npm run build
# Build and run all services with full stack
docker-compose up -d
# Or build specific services
docker-compose up -d postgres redis kafka zookeeper nginx eureka-server api-gateway
# Check service status
docker-compose ps
# View logs for specific service
docker-compose logs -f kafka
docker-compose logs -f nginxDocker Compose Services:
- Nginx (Port 80/443) - Reverse proxy and load balancer
- PostgreSQL (Port 5432) - Primary database
- Redis (Port 6379) - Caching and session management
- Apache Kafka (Port 9092) - Event streaming platform
- Zookeeper (Port 2181) - Kafka coordination service
- Eureka Server (Port 8761) - Service discovery
- API Gateway (Port 8081) - Request routing and management
- All microservices - Each with their respective ports
# Create Kafka topics
docker-compose exec kafka kafka-topics --create --topic chat-messages --bootstrap-server localhost:9092 --partitions 3 --replication-factor 1
docker-compose exec kafka kafka-topics --create --topic user-events --bootstrap-server localhost:9092 --partitions 3 --replication-factor 1
docker-compose exec kafka kafka-topics --create --topic notifications --bootstrap-server localhost:9092 --partitions 3 --replication-factor 1
# List all topics
docker-compose exec kafka kafka-topics --list --bootstrap-server localhost:9092
# Monitor topic messages
docker-compose exec kafka kafka-console-consumer --topic chat-messages --bootstrap-server localhost:9092# Reload Nginx configuration
docker-compose exec nginx nginx -s reload
# Test Nginx configuration
docker-compose exec nginx nginx -t
# View Nginx access logs
docker-compose logs -f nginxPOST /auth/login
POST /auth/register
POST /auth/validate
GET /auth/pingGET /user/profile
PUT /user/profile
GET /user/search?q={query}
POST /user/upload-avatarGET /chat/allChats
POST /chat/send
GET /chat/messages/{chatId}
POST /files/uploadGET /contacts
POST /contacts/request
PUT /contacts/accept/{id}
DELETE /contacts/reject/{id}service AuthService {
rpc ValidateToken (TokenRequest) returns (TokenResponse);
}service UserService {
rpc GetUserByEmail (GetUserByEmailRequest) returns (UserResponse);
rpc GetAllUser (Empty) returns (AllUserResponse);
}service ContactService {
rpc GetUserContacts (GetUserContactsRequest) returns (GetUserContactsResponse);
}- Chat Messages:
/user/queue/messages - Notifications:
/user/queue/notifications - Presence Updates:
/topic/presence - Typing Indicators:
/topic/typing
- Live Notifications:
/sse/notifications - System Alerts:
/sse/system-events - User Presence:
/sse/presence - Chat Updates:
/sse/chat-updates
- Message Events: Real-time message delivery via Kafka streams
- User Activity: Activity tracking and presence updates
- System Events: Distributed event processing
- Analytics: Real-time analytics and monitoring
// Send private message
stompClient.send("/app/private-message", {}, JSON.stringify({
to: "user@example.com",
content: "Hello!",
type: "text"
}));
// Subscribe to notifications
stompClient.subscribe("/user/queue/notifications", (message) => {
const notification = JSON.parse(message.body);
// Handle notification
});// Connect to SSE endpoint
const eventSource = new EventSource('/sse/notifications');
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
dispatch(addNotification(data));
};
eventSource.addEventListener('user-presence', (event) => {
const presence = JSON.parse(event.data);
dispatch(updateUserPresence(presence));
});// Kafka producer example
@Component
public class MessageProducer {
@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;
public void sendMessage(String topic, Object message) {
kafkaTemplate.send(topic, message);
}
}
// Kafka consumer example
@KafkaListener(topics = "chat-messages")
public void handleChatMessage(String message) {
// Process incoming chat message
ChatMessage chatMessage = objectMapper.readValue(message, ChatMessage.class);
messageService.processMessage(chatMessage);
}- Real-time state updates via WebSocket and SSE
- Optimistic UI updates with rollback support
- Persistent state management with Redux Toolkit
- Offline support with queue synchronization
- JWT tokens with RS256 signing
- Refresh token rotation
- Session invalidation
- Password strength validation
- Role-based access control
- API endpoint protection
- Resource-level permissions
- Cross-service authorization
- HTTPS/TLS encryption
- gRPC with TLS
- WebSocket Secure (WSS)
- Request signing
- SQL injection prevention
- XSS protection
- CORS configuration
- Rate limiting
- Paper-inspired material design
- Consistent color palette
- Typography hierarchy
- Responsive grid system
- Smooth page transitions
- Loading states
- Hover effects
- Micro-interactions
- ARIA labels and roles
- Keyboard navigation
- Screen reader support
- Color contrast compliance
- Code splitting and lazy loading
- Image optimization
- Bundle size optimization
- Service worker caching
- Database query optimization
- Connection pooling
- Caching with Redis
- Load balancing
- Application metrics
- Error tracking
- Performance monitoring
- Health checks
# Run unit tests
npm test
# Run E2E tests
npm run test:e2e
# Run coverage report
npm run test:coverage# Run unit tests
mvn test
# Run integration tests
mvn verify
# Run service tests
mvn spring-boot:run -Dspring-boot.run.profiles=test# Deploy to Vercel
vercel --prod
# Or use GitHub integration
# Connect repository to Vercel dashboard# Build images
docker-compose build
# Deploy to production
docker-compose -f docker-compose.prod.yml up -d# Frontend (.env)
VITE_API_URL=https://api.chatty.com
VITE_WS_URL=wss://ws.chatty.com
# Backend (application.properties)
spring.datasource.url=jdbc:postgresql://localhost:5432/chatty
jwt.secret=your-secret-key
spring.profiles.active=productionWe welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch
git checkout -b feature/amazing-feature
- Commit your changes
git commit -m 'Add amazing feature' - Push to the branch
git push origin feature/amazing-feature
- Open a Pull Request
- Follow conventional commits
- Add tests for new features
- Update documentation
- Ensure code quality with ESLint/Checkstyle
This project is licensed under the MIT License - see the LICENSE file for details.
- Spring Boot Team for the excellent framework
- React Team for the amazing UI library
- Tailwind CSS for the utility-first approach
- gRPC Team for high-performance RPC
- Open Source Community for inspiration and support
- Developer: Dev-Rishav
- Email: dev.rishav@example.com
- LinkedIn: Connect with me
Made with β€οΈ by Dev-Rishav
β Star this repository if you found it helpful!