# Mimo **Repository Path**: 44346460/Mimo ## Basic Information - **Project Name**: Mimo - **Description**: 这是一套企业级即时通讯(IM)系统,采用微服务架构设计,支持多端接入、实时消息推送、群组聊天、企业组织架构同步等核心功能。即可用于B端场景,也可以用于高并发下的C端场景,如直播场景。 - **Primary Language**: Java - **License**: GPL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 12 - **Forks**: 5 - **Created**: 2020-06-20 - **Last Updated**: 2026-10-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: IM, 微服务, Grpc, 直播, 企业级通讯 ## README # MIMO - Enterprise Instant Messaging System ## Project Overview This project is an **enterprise-grade Instant Messaging (IM) system** built on a microservices architecture. It supports multi-terminal access, real-time message push, group chat, enterprise organizational structure synchronization, and other core features. ### Project Background The company's previous live streaming platform relied on a third-party IM service. As the business grew rapidly, user volume and message traffic surged dramatically. **The annual third-party service fee for IM alone reached millions of RMB.** Additionally, during marketing campaigns on the live streaming platform, core metrics such as message distribution volume, concurrent online users, API call frequency, and maximum members per room would spike significantly. However, the third-party service's rules and cost control policies imposed notable constraints on the client, including rate limiting and call frequency restrictions, which directly hindered normal business operations and expansion. Moreover, the platform primarily targeted the **overseas Southeast Asian market**, where local network infrastructure was unstable, posing continuous challenges to business stability. When relying on third-party services, quality-of-service response and issue resolution were noticeably delayed, leaving the platform in a passive position with limited ability to autonomously control service levels and disaster recovery timelines. To address these pain points, the team decided to **build an enterprise-grade IM system in-house**. Through service decomposition, multi-level load balancing, multi-tier data storage architecture, and a comprehensive monitoring system, the goals are: - **Cost Controllability**: Eliminate high third-party service fees and reduce long-term operating costs - **Elastic Scalability**: Autonomously control service capacity and flexibly handle traffic peaks from marketing campaigns - **Quality Assurance**: Optimize long-connection stability for overseas network environments and shorten fault response and recovery times - **Business Decoupling**: Break free from third-party service rule constraints and customize message strategies and feature iterations on demand The system supports massive concurrent long connections and complex live streaming interaction scenarios through microservices design, while integrating with enterprise-level systems and retaining the ability to integrate with third-party systems, balancing openness and autonomy. ## Connection Stress Test Results On an Alibaba Cloud ECS instance (4C 32G), a single machine stably supported **600,000 connections**, consuming **80%+ memory** and **50%+ CPU**. --- ## System Architecture ### Overall Architecture Diagram System Architecture ### Architecture Layer Description #### 1. Client Access Layer - **Multi-terminal Coverage**: Supports Android, iOS, and Web access - **Dual Protocol Access**: - **TCP Long Connection**: Accesses backend Comet services through LVS load balancing to maintain real-time online status and message push - **HTTP Short Connection**: Handles management operations and third-party business calls through Spring Gateway #### 2. Gateway and Traffic Scheduling Layer | Component | Responsibility | |-----------|----------------| | **Spring Gateway** | HTTP entry gateway, handling request routing, authentication, rate limiting, etc. | | **LVS** | Layer-4 load balancing, responsible for TCP long connection traffic distribution | | **3rd Business Server** | Third-party business server HTTP access, supporting integration with existing enterprise systems | #### 3. Service Registration and Configuration Center - **Eureka Cluster**: Service registration and discovery; all microservices auto-register for inter-service calls - **Configuration Center**: Centralized management of service configurations, supporting dynamic configuration distribution #### 4. Core Business Service Cluster Services communicate internally via **gRPC** for high-performance communication: | Service | Responsibility | |---------|----------------| | **Comet** | Long-connection gateway (currently primarily uses WebSocket; in fact, it can be extended to support any protocol). Maintains massive client TCP connections and handles message sending/receiving.
(1) Manages physical connections, including read, write, idle, etc.
(2) Maintains session uniqueness for the same account under multiple connections in a cluster environment
(3) Transparent transmission of all upstream commands to Logic service | | **Logic** | Business logic processing center, handling message routing, user status, and business rules.
(1) Stateless processing of all contexts
(2) User validity authentication and processing of client SDK collected information
(3) Introduces logical sessions for connection sessions and uniformly manages them based on logical session activity
(4) Maintains room functionality and room member functionality
(5) Maintains message receiving and distribution, including P2P messages and room messages
(6) Maintains message receiving confirmation mechanism and offline message consumption mechanism
(7) Maintains user access permission functionality, including room-level mute and ban, platform-level global mute and ban, user-level private message sending, and interaction frequency limits based on user and room dimensions
(8) Provides HTTP interface services for external business systems; provides system-level metric information across different date dimensions, such as P2P upstream message count, P2P downstream message count, room upstream message count, room downstream message count, room creation count, new user count, login user count, active user count, etc. | | **Push** | Push service, responsible for offline push and message delivery | | **System** | Provides attachment/backpack functionality and other weakly business-related feature sets | | **Chat** | Upper-layer application business integration, such as single chat, group chat, application-level authentication, user roles, message and attachment features, enterprise OA integration (user organizational structure), and other specific businesses | | **Admin** | Management backend service, providing access terminal information query and multi-dimensional metric query interfaces | #### 5. Data Storage and Message Middleware | Component | Purpose | |-----------|---------| | **Redis** | Data caching + message broadcasting based on Pub/Sub (message diffusion between Comet nodes) | | **MongoDB** | Primary persistent storage for document-type data such as chat records and user profiles | | **Kafka** | Message queue for message storage and relay, achieving peak shaving and valley filling, asynchronous processing | | **Elasticsearch** | Full-text search and message cloud storage, supporting historical message search | | **OSS** | Object storage for attached text files, images, multimedia files, etc. | #### 6. Unified Logging and Operations Monitoring - **ELK Stack (LogStash + Elasticsearch + Kibana)** - Service logs aggregated to LogStash - Elasticsearch stores logs; Kibana provides visual query and monitoring - Achieves full-link log tracing and troubleshooting --- ## Business Functions The system supports the following core business capabilities: - **Friend Functionality** - **Enterprise Organizational Structure Synchronization** - **Group Functionality** - **File Upload Functionality** - **Chat History Functionality** - **Information Retrieval Functionality** - **Group Bot Functionality** --- ## Technology Stack | Layer | Technology Selection | |-------|----------------------| | Access Gateway | Spring Gateway, LVS | | Service Registration | Eureka | | Configuration Center | Spring Cloud Config | | Service Communication | gRPC + protobuf | | Data Caching | Redis | | Persistent Storage | MongoDB | | Message Queue | Kafka | | Full-text Search | Elasticsearch | | Logging & Monitoring | ELK (LogStash + Elasticsearch + Kibana) | | Client | Android, iOS, Web | --- ## Project Structure ``` mimo/ ├── mimo-comet/ # Long-connection gateway service ├── mimo-logic/ # Business logic processing service ├── mimo-system/ # Backpack/attachment service and weakly business-related features ├── mimo-push/ # Push service ├── mimo-chat/ # Chat business service ├── mimo-admin/ # Management backend service ├── mimo-gateway/ # Spring Gateway ├── mimo-discovery/ # Service registration center ├── mimo-config/ # Configuration center ├── mimo-common/ # Common components, tools, and proto definitions ├── docs/ # Documentation and architecture diagrams └── README.md ``` --- ## Client Screenshots ### Web-PC Client > > > 2 > > 3 > > 4 > > 5 > > 6 > > 7 ### Native Client > native --- ## Project Implementation Difficulty Analysis > **(This chapter will be continuously updated based on the author's mood and energy — treat it as a blog if you like)** > > - Maintenance and heartbeat management of massive long connections > - Message reliable delivery mechanism (at-least-once / exactly-once) > - Message ordering guarantee and out-of-order handling > - Group chat message diffusion and fan-out optimization > - Historical message pagination loading and search performance > - Multi-terminal message synchronization strategy > - Service high availability and failover design > - Communication layer protocol design --- # Application Protocol Design ## Authentication and Authorization - Login message - Logout message ## Room Operation Set - Create, Join, Leave, Destroy, List all joined rooms based on user ## Upstream Commands - P2P (Peer-to-Peer) message - Room message - Heartbeat message - Query pending confirmation messages ## Downstream Response Commands (corresponding to upstream commands) - Receive confirmation message (sender needs this to confirm whether the server has received the message) - Login success message - User's joined room list message - Pending confirmation list message - Command error response message (returned by server when upstream command is erroneous or restricted) ## Downstream Distribution Messages - Business messages distributed to the client for reception; generally, the client will receive P2P messages and room distribution messages. --- # Server Response Code Definitions | Group | Response Code | Message Description | Remarks | |-------|---------------|---------------------|---------| | System | 0 | Normal business response | | | System | -1 | Unknown error | Such as NPE, network exception, data exception, etc. | | User Module | 1000 | Login authorization failed | Possibly wrong account/password or non-existent account | | User Module | 1001 | User is banned | | | User Module | 1002 | Target user does not exist in P2P message | | | User Module | 1003 | Current user logged in on another mobile device, this device is kicked offline | Same account logged in multiple places causing the previously logged-in user to be forced offline | | User Module | 1004 | Current user is offline | Generally during inter-service write-back when user is unreachable | | Chat Room | 2000 | Chat room does not exist | When joining a chat room or sending messages to it | | Chat Room | 2001 | Chat room member limit exceeded when joining | Chat rooms have member limits, configured by server | | Chat Room | 2002 | Current user is muted in the chat room | Muted within chat room | | Chat Room | 2003 | Current user has been kicked and banned from the chat room | Ban duration depends on time parameter passed when server calls kick interface | | Chat Room | 2004 | Not yet joined the chat room | Generally when user sends messages to a chat room without having joined it | | Internal Service | 3000 | User locate not on this machine | Generally refers to user not being on this machine during Comet communication; currently used for inter-service call judgment | | Message | 4000 | Private message rejected | Generally, the other party has added the user to blacklist during P2P messaging | | Message | 4001 | User-dimension upstream command too frequent | Generally won't happen for normal users; mainly to prevent malicious message spamming (P2P and room messages) | | Message | 4002 | Room-dimension upstream command too frequent | Generally, too many upstream messages in chat room; also mainly to prevent malicious message spamming (room messages) | --- # Protocol Class Diagrams - Upstream Command Class Diagram Upstream Command Class Diagram - Downstream Echo Command Class Diagram Downstream Response Class Diagram - Downstream Distribution Message Class Diagram Downstream Distribution Class Diagram --- # Network Communication Protocol - Currently uses WebSocket for clients, mainly to accommodate H5 and native applications - Inter-service communication uses gRPC, both to improve communication efficiency and reduce internal bandwidth pressure during communication. For more information on gRPC and protobuf, please learn from the official website. - The IM system provides HTTP interfaces for external business systems --- # Implementation Solution Selection and Considerations ## Connection Routing Industry practices generally fall into two categories: 1. There is a "routing" service (module) in the business layer. This "routing" can effectively perceive the specific connection management services at the backend (such as ServerA, ServerB). When a new client connects, it first goes through "routing" and is guided to connect to ServerA or ServerB according to business or resource rules. - **Pros**: Strong controllability, entirely determined by business code. - **Cons**: On one hand, it requires additional functional design costs; on the other hand, the client first connects to "routing" and then to the corresponding Server, effectively connecting twice. - Diagram: System Architecture 2. The entire access layer consists of CometA, CometB, etc. The front end of this layer depends on LVS (for more information on LVS, please check the Alibaba Cloud official website), a third-party component service. According to its relevant "routing rules," connections are distributed to backend CometA, CometB, etc. - **Pros**: The system itself doesn't need to consider routing distribution issues. For projects without high custom requirements, this can effectively reduce design complexity. - Diagram: System Architecture For the current project, the connection routing solution uses the latter. For specific implementation, please refer to the **Comet** service's ***WebSocketServer*** and the **Login** service's ***UserServiceImpl#login***. ## Connection Session Management Since all Comet instances are peer-to-peer, the business needs to ensure connection uniqueness for any user information. When any client connects to a Comet, the corresponding Comet instance relies on Redis's pub/sub mechanism to broadcast to other Comets in the cluster. **Diagram:** Connection Session Uniqueness For each Comet instance, to distinguish itself, it generates a unique identifier in UUID format upon startup. This allows each instance to determine whether the "login event" broadcast indicates that the client is connected to the current instance. If not, each instance traverses locally to find the client's connection information; if it exists, it disconnects and clears it. Configuration information is roughly as follows: ```java @Validated @ConfigurationProperties(prefix = "mimo.comet.server") public class LocalCometServerConfig { /** * Each application instance ID must remain unique */ private String applicationId = RandomStringUtils.uniqueRandom(); /** * Redis pub/sub listens for new local session connections */ @NotEmpty private String clusterChannel; /** * Redis pub/sub listens for forced disconnect information when logic session expires */ @NotEmpty private String logicExpiredChannel; /** * Used to obtain local machine configuration information */ @NotNull @Valid private ZoneDTO zone; private com.mimo.common.rpc.proto.UserProto.ZoneDTO protoZone; ``` ## Message Acknowledgment For most IM applications, the message acknowledgment mechanism ensures the reachability of information between the "sender-receiver" pair. Therefore, for messages distributed to the client, the client is often required to explicitly Ack (acknowledge) the delivered message. Only then will the server delete the corresponding message. - **P2P Message** - That is, User A sends to User B. For such messages, the system explicitly requires User B to "ACK" the message. Otherwise, upon reconnection or when the client actively queries, the message will be pushed again. - **Group Message** - That is, User A broadcasts a message in a group. Other members in the group need to acknowledge the message; otherwise, it will continue to be pushed after they come online. - **Room Distribution Message** - For live streaming scenarios, especially within live rooms, message distribution is a high-frequency behavior. Particularly during various ranking-type marketing campaigns, the server pushes a large volume of IM messages (marketing, calibration, etc.) to the live room. If the client had to respond to each message individually in this scenario, the consumption of upstream bandwidth and mobile processing would be very high while downstream bandwidth is already occupied. Therefore, for message distribution within live rooms, the server currently does **not** require any "ack," and the client does **not** need to send "ACK" for such messages. ## Read Diffusion vs. Write Diffusion Based on our own business, the system currently limits the maximum number of members in a room to 10,000 (configurable; refer to RoomDefinitionInfo). Therefore, we simply adopt: **Write Diffusion**. After all, for most small and medium-sized projects, it's rare to have live rooms with member counts far exceeding 10,000. Of course, for many top-tier projects where hundreds of thousands or even millions of users crowd into the same live room, most adopt a combination of Read Diffusion + Write Diffusion, along with many bucket-based delivery methods. This will be elaborated on in the future when there's an opportunity.