Skip to content

Latest commit

ย 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Mini-Chat

A realtime chat backend application built with Spring Boot, supporting:

  • JWT Authentication (register, login, logout)
  • Public and room-based chat via WebSocket/STOMP
  • Online/offline presence tracking with heartbeat mechanism
  • Multi-source data storage: MySQL (auth), MongoDB (chat rooms/messages), Redis (presence cache)
  • Fast deployment with Docker Compose

1) Technology Stack

Backend & Framework

  • โ˜• Java 21 โ€” Latest JDK with virtual threads, records, pattern matching
  • ๐ŸŒฑ Spring Boot 3.2.x โ€” Standard web framework, auto-config, embedded server
  • ๐Ÿ” Spring Security + JWT โ€” Authentication, authorization, token-based auth (stateless)
  • ๐Ÿ”Œ Spring WebSocket (STOMP + SockJS) โ€” Realtime 2-way communication with fallback for older browsers

Data Layer

  • ๐Ÿ—„๏ธ Spring Data JPA + Hibernate โ€” ORM, manage MySQL entities (User, Auth)
  • ๐Ÿƒ Spring Data MongoDB โ€” NoSQL, store documents (Chat messages + Rooms)
  • ๐Ÿ”ด Spring Data Redis โ€” In-memory cache, fast presence tracking
  • ๐Ÿฌ MySQL 8.4 โ€” Relational DB, auth + user data
  • ๐Ÿ€ MongoDB 7 โ€” Document DB, chat history + room metadata
  • โšก Redis 7 โ€” Cache + pub/sub, user online status

DevOps & Container

  • ๐ŸŽญ Docker Compose โ€” Run infra services for local app development (MySQL, MongoDB, Redis)
  • ๐Ÿ“ฆ Maven 3.9 โ€” Build tool, dependency management

Libraries & Tooling

  • ๐Ÿชถ Lombok โ€” Reduce boilerplate (auto-generate getters, setters, constructors)
  • ๐Ÿ”‘ JJWT 0.12.6 โ€” JWT library for signing/verifying tokens
  • ๐Ÿงช JUnit 5 + Spring Boot Test โ€” Unit & integration testing

2) Architecture Overview

com.minichat/
โ”œโ”€โ”€ auth/                    ๐Ÿ” Authentication & Authorization
โ”‚   โ”œโ”€โ”€ controller/          REST: /api/auth/register, login, logout
โ”‚   โ”œโ”€โ”€ dto/                 Request/Response payloads
โ”‚   โ”œโ”€โ”€ model/               AppUser, Role entities
โ”‚   โ”œโ”€โ”€ repository/          JPA repository for users
โ”‚   โ”œโ”€โ”€ security/            JWT filter, service, custom UserDetailsService
โ”‚   โ””โ”€โ”€ service/             Auth business logic
โ”‚
โ”œโ”€โ”€ chat/                    ๐Ÿ’ฌ Chat & Presence
โ”‚   โ”œโ”€โ”€ controller/          REST: /api/rooms, WebSocket: /app/...
โ”‚   โ”œโ”€โ”€ dto/                 CreateRoomRequest, JoinRoomRequest, etc
โ”‚   โ”œโ”€โ”€ event/               UserPresenceEvent (publish/subscribe)
โ”‚   โ”œโ”€โ”€ listener/            Event listeners, WebSocket listeners
โ”‚   โ”œโ”€โ”€ model/               ChatMessage, ChatRoom, UserPresence, BaseEntity
โ”‚   โ”œโ”€โ”€ repository/          MongoDB, MySQL, Redis repositories
โ”‚   โ””โ”€โ”€ service/             ChatService, RoomService, PresenceService
โ”‚
โ”œโ”€โ”€ config/                  โš™๏ธ Configuration
โ”‚   โ”œโ”€โ”€ auth/                SecurityConfig (JWT filter chain)
โ”‚   โ””โ”€โ”€ websocket/           WebSocketConfig (STOMP endpoint, broker)
โ”‚
โ””โ”€โ”€ shared/                  ๐Ÿ”ง Shared Utilities
    โ”œโ”€โ”€ error/               Exception handler, custom exceptions
    โ””โ”€โ”€ response/            BaseResponse, ResponseFactory

3) Core Features

๐Ÿ” JWT Authentication

  • POST /api/auth/register โ€” Create new account, hash password, save to MySQL
  • POST /api/auth/login โ€” Authenticate user, issue JWT token (24h TTL)
  • POST /api/auth/logout โ€” Mark user offline, clear presence cache

๐Ÿ  Room Management

  • POST /api/rooms โ€” Create chat room, persist metadata to MongoDB
  • POST /api/rooms/{roomId}/join โ€” User joins room, add to membership
  • GET /api/rooms โ€” List all rooms
  • GET /api/rooms/{roomId} โ€” Get room details (name, members, created_at)

๐Ÿ’ฌ Public Chat (Broadcast)

  • WebSocket endpoint: /ws (STOMP over SockJS)
  • Send message: POST /app/chat.sendMessage โ†’ broadcast to /topic/public
  • Join announcement: POST /app/chat.addUser โ†’ announce join to /topic/public
  • All connected users receive messages instantly

๐ŸŽฏ Room Chat (Scoped)

  • Send to room: POST /app/room/{roomId}/send โ†’ broadcast to /topic/rooms/{roomId}
  • Join room: POST /app/room/{roomId}/join โ†’ announce join within room topic
  • Messages persist in MongoDB
  • Only users in the room receive messages (not global broadcast)

๐Ÿ‘ฅ Presence & Heartbeat

  • User online tracking: Store presence record (username, timestamp) in Redis
  • Heartbeat: Client sends POST /app/presence.heartbeat periodically (every 30s)
  • Auto offline: If no heartbeat for >30s โ†’ mark offline, trigger event
  • Event listener: Spring event listener publishes UserPresenceEvent, notifies web clients

4) Run Locally Without Docker

โœ… Requirements

  • โ˜• Java 21 JDK
  • ๐Ÿ“ฆ Maven 3.9+
  • ๐Ÿฌ MySQL 8.x running locally
  • ๐Ÿ€ MongoDB 7.x running locally
  • โšก Redis 7.x running locally

โš™๏ธ Configuration

Default settings in src/main/resources/application.yml:

spring:
     datasource:
          url: jdbc:mysql://localhost:3306/mini_chat_auth
          username: root
          password: root
     data:
          mongodb:
               uri: mongodb://localhost:27017/mini_chat
          redis:
               host: localhost
               port: 6379

๐Ÿš€ Run

mvn clean spring-boot:run

App runs by default at: http://localhost:8080

5) Run with Docker Compose

๐Ÿณ Start Infra Services

docker compose up -d

๐Ÿ“Œ Service Endpoints

Service Port Note
MySQL 3306:3306 Auth database
MongoDB 27017:27017 Document DB
Redis 6379:6379 Cache + Presence

๐Ÿ“Š View Logs

# View infra logs
docker compose logs -f

โ–ถ๏ธ Run App Locally

mvn clean spring-boot:run

App endpoint: http://localhost:8080

๐Ÿ›‘ Stop Services

# Stop all services
docker compose down

# Stop & remove volumes
docker compose down -v

6) Test Realtime Chat & WebSocket

๐Ÿ”— WebSocket Connection

  • Endpoint: ws://localhost:8080/ws (STOMP over SockJS)
  • Tools: Postman, Socket.io Client, web browser + stomp.js library

๐Ÿ“ฎ Common Message Flows

1๏ธโƒฃ Public Chat

CLIENT SUBSCRIBE: /topic/public

CLIENT SEND:
  destination: /app/chat.sendMessage
  body: {
    "sender": "alice",
    "content": "Hello everyone!"
  }

SERVER BROADCAST: /topic/public
  {
    "sender": "alice",
    "content": "Hello everyone!",
    "timestamp": "2025-03-17T10:30:00Z"
  }

2๏ธโƒฃ Room Chat

CLIENT SUBSCRIBE: /topic/rooms/room-123

CLIENT SEND:
  destination: /app/room/room-123/send
  body: {
    "sender": "bob",
    "content": "Room message"
  }

SERVER BROADCAST: /topic/rooms/room-123
  {
    "sender": "bob",
    "roomId": "room-123",
    "content": "Room message",
    "timestamp": "2025-03-17T10:31:00Z"
  }

3๏ธโƒฃ Presence Heartbeat

CLIENT SEND (every 30s):
  destination: /app/presence.heartbeat
  body: { "username": "alice" }

SERVER:
  - Update Redis presence: alice โ†’ timestamp
  - Trigger UserPresenceEvent
  - Auto clear offline after 30s timeout

7) Directory Structure

๐Ÿ“ mini-chat
โ”œโ”€โ”€ ๐Ÿ“„ pom.xml                    Maven build configuration
โ”œโ”€โ”€ ๐Ÿ“„ docker-compose.yml         Orchestrate infra services (MySQL, MongoDB, Redis)
โ”œโ”€โ”€ ๐Ÿ“„ README.md                  This file
โ”œโ”€โ”€ ๐Ÿ“„ .gitignore                 Ignore build, IDE, env files
โ”‚
โ””โ”€โ”€ ๐Ÿ“ src/main/java/com/minichat
    โ”œโ”€โ”€ ๐Ÿ“„ MiniChatApplication.java    Spring Boot entry point
    โ”‚
    โ”œโ”€โ”€ ๐Ÿ“ auth/                  ๐Ÿ” Authentication
    โ”‚   โ”œโ”€โ”€ controller/
    โ”‚   โ”œโ”€โ”€ dto/
    โ”‚   โ”œโ”€โ”€ model/
    โ”‚   โ”œโ”€โ”€ repository/
    โ”‚   โ”œโ”€โ”€ security/
    โ”‚   โ””โ”€โ”€ service/
    โ”‚
    โ”œโ”€โ”€ ๐Ÿ“ chat/                  ๐Ÿ’ฌ Chat & Presence
    โ”‚   โ”œโ”€โ”€ controller/
    โ”‚   โ”œโ”€โ”€ dto/
    โ”‚   โ”œโ”€โ”€ event/
    โ”‚   โ”œโ”€โ”€ listener/
    โ”‚   โ”œโ”€โ”€ model/
    โ”‚   โ”œโ”€โ”€ repository/
    โ”‚   โ””โ”€โ”€ service/
    โ”‚
    โ”œโ”€โ”€ ๐Ÿ“ config/                โš™๏ธ Configuration
    โ”‚   โ”œโ”€โ”€ auth/
    โ”‚   โ””โ”€โ”€ websocket/
    โ”‚
    โ””โ”€โ”€ ๐Ÿ“ shared/                ๐Ÿ”ง Shared Utils
        โ”œโ”€โ”€ error/
        โ””โ”€โ”€ response/

8) ๐Ÿ”’ Security Notes

โš ๏ธ WARNING:

  • โŒ Never hardcode JWT secret, DB password in application.yml
  • โœ… Use environment variables for production:
    export APP_JWT_SECRET=your-long-secret-key
    export SPRING_DATASOURCE_PASSWORD=your-db-password
    export SPRING_DATA_REDIS_PASSWORD=your-redis-password
  • โŒ Never commit .env file (add to .gitignore)
  • โœ… Use Docker secrets or Kubernetes ConfigMap for production deployments

JWT Token Configuration

app:
     jwt:
          secret: 12345678901234567890123456789012 # Min 32 chars
          expiration-ms: 86400000 # 24 hours

9) ๐Ÿš€ Future Enhancements (Roadmap)

๐Ÿ’พ Data & History

  • Persistent chat history + pagination (MongoDB query with limits)
  • Search messages by keyword/date range
  • Archive old messages

๐Ÿ“ฌ Advanced Chat Features

  • Direct messaging (1-on-1 private chat)
  • Group chat (multiple members per room)
  • Message edit/delete (soft delete + version tracking)
  • Read receipts (message seen status per user)
  • Typing indicators (broadcast when user is typing)

๐Ÿ‘ค Presence & User Status

  • User custom status (away, do not disturb, online)
  • Per-room presence (detailed tracking of who's in which room)
  • Last seen timestamp (when user last logged in)

๐Ÿ”” Notifications & Alerts

  • Push notifications (Firebase Cloud Messaging)
  • Email alerts for missed messages
  • In-app notification center

๐ŸŽฏ Moderation & Control

  • Rate limiting (max messages per user per minute)
  • Mute/block users
  • Room admin controls (ban, kick, permission management)
  • Message audit log (track edit/delete history)

๐Ÿ“Š Analytics & Monitoring

  • User activity statistics
  • Message volume metrics
  • Performance monitoring (WebSocket connection count)
  • Error tracking integration (Sentry/DataDog)

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages