<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Gaurav Bansal</title>
    <description>The latest articles on DEV Community by Gaurav Bansal (@gaurav_bansal_2e1ca573623).</description>
    <link>https://dev.to/gaurav_bansal_2e1ca573623</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2872330%2F299b5089-749d-4f7f-b67f-86895537391b.JPG</url>
      <title>DEV Community: Gaurav Bansal</title>
      <link>https://dev.to/gaurav_bansal_2e1ca573623</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/gaurav_bansal_2e1ca573623"/>
    <language>en</language>
    <item>
      <title>Messaging Queues in Distributed Systems: Design, Challenges, and Innovations</title>
      <dc:creator>Gaurav Bansal</dc:creator>
      <pubDate>Wed, 11 Jun 2025 21:31:00 +0000</pubDate>
      <link>https://dev.to/gaurav_bansal_2e1ca573623/messaging-queues-in-distributed-systems-design-challenges-and-innovations-2i58</link>
      <guid>https://dev.to/gaurav_bansal_2e1ca573623/messaging-queues-in-distributed-systems-design-challenges-and-innovations-2i58</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In modern distributed architectures, services often need to communicate asynchronously to ensure decoupling, scalability, and fault tolerance. A distributed messaging queue system enables reliable communication between producers and consumers without requiring direct synchronous interaction. This document explores key components, architecture, design considerations, and future trends of distributed messaging queues.&lt;/p&gt;

&lt;h2&gt;
  
  
  System Overview
&lt;/h2&gt;

&lt;p&gt;A messaging queue system[1][3] enables asynchronous communication between a producer, which sends messages, and a consumer, which processes them. Instead of directly calling the consumer, the producer sends messages to a queue, ensuring reliability and scalability. This system supports two primary message delivery models:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Queue Model&lt;/strong&gt;: A message is delivered to only one consumer.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Topic Model&lt;/strong&gt;: A message is delivered to multiple subscribers.
The system must be designed to handle high availability, fault tolerance, scalability, and performance optimizations while ensuring data durability and integrity.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  System Architecture
&lt;/h2&gt;

&lt;p&gt;The system architecture of a distributed messaging queue must ensure reliability, scalability, and fault tolerance. To achieve this, several key components work together seamlessly. A Load Balancer (LB) distributes incoming requests across multiple frontend nodes, ensuring even distribution and redundancy. The Frontend Web Service handles request validation, authentication, caching, and rate limiting before passing requests to the backend. The Queue Metadata Manager stores queue-related information, such as queue names, creation timestamps, and ownership details. Meanwhile, the Backend Message Store is responsible for persisting messages reliably and enabling efficient retrieval. To ensure data durability, a Replication Mechanism distributes messages across multiple storage nodes. Additionally, Failure Detection and Recovery continuously monitor system health and automatically recover from failures, maintaining high availability. To support large-scale distributed messaging, the system comprises several key components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Load Balancer (LB)&lt;/strong&gt;: Distributes incoming requests across multiple frontend nodes to ensure even load distribution and redundancy.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Frontend Web Service:&lt;/strong&gt; Handles request validation, authentication, caching, and rate limiting before forwarding requests to the backend.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Metadata Manager:&lt;/strong&gt; Stores queue-related information, including queue names, creation timestamps, and ownership details.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Backend Message Store:&lt;/strong&gt; Persists messages reliably and ensures efficient retrieval.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Replication Mechanism:&lt;/strong&gt; Ensures message durability by replicating data across multiple storage nodes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Failure Detection and Recovery:&lt;/strong&gt; Monitors system health and automatically recovers from failures to maintain high availability.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Approaches to Message Delivery
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Approach 1: Synchronous Communication (Direct API Calls)
&lt;/h3&gt;

&lt;p&gt;In synchronous communication, the producer directly calls the consumer and waits for a response. This approach is simple and offers low latency since there is no intermediary component. However, it has significant downsides, including difficulties in handling failures, the risk of overwhelming the consumer, and poor scalability. If the consumer service becomes slow or unavailable, the producer may experience delays or failures.&lt;/p&gt;

&lt;h3&gt;
  
  
  Approach 2: Asynchronous Communication (Message Queue)
&lt;/h3&gt;

&lt;p&gt;With an asynchronous message queue, the producer sends messages to a queue, and a consumer retrieves them at a later time. This approach improves fault tolerance, scalability, and load handling, making it suitable for high-traffic environments. However, it introduces additional complexity, as it requires infrastructure to manage the queue, ensure message persistence, and handle delayed processing.&lt;/p&gt;

&lt;h3&gt;
  
  
  Approach 3: Hybrid Approach
&lt;/h3&gt;

&lt;p&gt;A hybrid approach combines synchronous and asynchronous messaging, allowing producers to send messages directly when real-time responses are needed while leveraging a queue for background tasks. This approach balances performance, reliability, and cost-effectiveness. However, it requires careful coordination to determine when to use each method and ensure seamless integration.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F07ghq9toxmna25fwcv03.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F07ghq9toxmna25fwcv03.png" alt="Image description" width="800" height="295"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Detailed Design
&lt;/h2&gt;

&lt;p&gt;The Load Balancer is responsible for routing client requests to available frontend nodes, ensuring even distribution of traffic. It supports failover by using primary and secondary nodes to maintain high availability. Additionally, VIP partitioning is used to scale the system by mapping multiple DNS records to different load balancers.&lt;br&gt;
The Frontend Web Service plays a critical role in handling client requests. It ensures request validation, checking that necessary parameters like queue names and message size limits are met. The service also manages authentication and authorization, verifying the sender’s identity and permissions. Caching is implemented to store frequently accessed metadata, improving response times. To prevent overload, the service employs rate limiting, which restricts excessive requests. Additionally, request deduplication is used to maintain exact-once message processing, ensuring reliability.&lt;br&gt;
The Queue Metadata Manager is designed to store queue configurations and maintain a consistent mapping of queues to backend nodes. It optimizes performance through caching strategies and ensures efficient lookups with consistent hashing, reducing data retrieval overhead.&lt;br&gt;
The Backend Message Store serves as a durable, fault-tolerant storage system for messages. It supports data replication to maintain high availability and is optimized for high-throughput writes, ensuring efficient message retrieval. This component guarantees that messages are stored reliably and can be processed with minimal latency.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling Failures and Scalability
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz3ac8i1ouwd8n6jdyvvc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz3ac8i1ouwd8n6jdyvvc.png" alt="Image description" width="800" height="348"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Future Trends and Innovations
&lt;/h2&gt;

&lt;p&gt;The evolution of distributed messaging queues continues to be driven by advancements in cloud computing, AI-driven optimizations, and edge technologies. Below are some key trends that will shape the future of messaging systems:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Serverless Messaging Queues: Cloud providers offer serverless messaging solutions like AWS SQS[1] and Google Pub/Sub[2], reducing operational overhead while improving scalability and reliability. These managed solutions eliminate the need for infrastructure management, allowing developers to focus on application logic.&lt;/li&gt;
&lt;li&gt;AI and Predictive Analytics: Machine learning models are being increasingly used to analyze messaging patterns, predict peak loads, and optimize message routing dynamically. AI-driven insights[5] can help scale resources efficiently, reducing latency and improving system performance.&lt;/li&gt;
&lt;li&gt;Multi-Cloud and Hybrid Deployments: Organizations are increasingly adopting multi-cloud strategies, where messaging queues span multiple cloud providers. This approach enhances redundancy, prevents vendor lock-in, and optimizes cost efficiency[4].&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;A distributed messaging queue system is a fundamental building block of modern scalable architectures. By implementing a well-structured queueing mechanism, organizations can ensure fault tolerance, scalability, durability, and performance. Future advancements in AI-driven traffic management, serverless architecture, and event-driven messaging will further enhance the capabilities of distributed message queue systems.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;AWS Blogs.&lt;/strong&gt; (2023). AWS Simple Queue Service (SQS) Documentation &lt;a href="https://docs.aws.amazon.com/sqs/" rel="noopener noreferrer"&gt;https://docs.aws.amazon.com/sqs/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Google Cloud.&lt;/strong&gt; (2023). Pub/Sub Overview &lt;a href="https://cloud.google.com/pubsub" rel="noopener noreferrer"&gt;https://cloud.google.com/pubsub&lt;/a&gt;
3.** Microsoft Azure.** (2023).  Service Bus Messaging &lt;a href="https://learn.microsoft.com/en-us/azure/service-bus-messaging/" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/azure/service-bus-messaging/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;IBM Topics.&lt;/strong&gt; (2023). Multi-Cloud Strategies for Enterprise &lt;a href="https://www.ibm.com/think/topics/multicloud" rel="noopener noreferrer"&gt;https://www.ibm.com/think/topics/multicloud&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Medium&lt;/strong&gt; (2025). AI-Driven Infrastructure Scaling &lt;a href="https://medium.com/doctor-ai/scaling-ai-infrastructure-lessons-from-building-high-performance-systems-65e9c062bac9" rel="noopener noreferrer"&gt;https://medium.com/doctor-ai/scaling-ai-infrastructure-lessons-from-building-high-performance-systems-65e9c062bac9&lt;/a&gt; &lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  About me
&lt;/h2&gt;

&lt;p&gt;I am a Senior Staff Software Engineer at Uber with over a decade of experience in scalable, high-performance distributed systems. I have worked on cloud-native architectures, database optimization, and building large-scale distributed systems&lt;br&gt;
Connect with me at &lt;a href="https://www.linkedin.com/in/gaurav-bansal-8465363a/" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Monitoring What Matters: Practical Alerting for Scalable Systems</title>
      <dc:creator>Gaurav Bansal</dc:creator>
      <pubDate>Fri, 04 Apr 2025 20:57:03 +0000</pubDate>
      <link>https://dev.to/gaurav_bansal_2e1ca573623/alert-strategy-best-practices-1b79</link>
      <guid>https://dev.to/gaurav_bansal_2e1ca573623/alert-strategy-best-practices-1b79</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In modern distributed systems, performance isn't just about speed—it's about balancing latency, availability, and resource efficiency at scale. Effective alerting is essential for maintaining this balance. Without it, teams may miss real failures, overreact to false positives, or remain blind to slow degradation. This guide lays out a practical approach to designing alerts that matter—so you can catch what’s broken, ignore what’s not, and scale confidently. [1][2]&lt;/p&gt;

&lt;p&gt;Alerts depend on the type of service being monitored. Customer-facing services need different alerts than backend systems or batch jobs. But no matter the service, you should at least set alerts for these key areas.&lt;/p&gt;

&lt;h3&gt;
  
  
  Availability
&lt;/h3&gt;

&lt;p&gt;Availability just means that the system is ready to do its job. For services that take requests, it means the service is running and can handle any incoming requests. For backend processes, it means the system is either working right now or ready to start when there are tasks to handle.&lt;/p&gt;

&lt;h3&gt;
  
  
  Latency
&lt;/h3&gt;

&lt;p&gt;Latency is how long it takes for your system to do something. For a service, it’s the time it takes from when a request comes in to when the response is sent out. This is the total time for the request to travel to the service and the response to go back. However, we can only measure latency from the service’s side, so things like network delays or other issues outside the service aren’t counted.&lt;/p&gt;

&lt;p&gt;For backend processes, latency is how long it takes to finish a task—like processing a message from a queue, completing a step in a workflow, or finishing a batch job.&lt;/p&gt;

&lt;h3&gt;
  
  
  Compute metrics
&lt;/h3&gt;

&lt;p&gt;Compute metrics track things like CPU usage, memory usage, disk space, etc. These alerts help make sure individual servers aren’t causing problems that might get hidden in overall system metrics.&lt;/p&gt;

&lt;h3&gt;
  
  
  Call volume
&lt;/h3&gt;

&lt;p&gt;They help protect your service from hitting its limits and let you know if you need to scale up. These alerts should track the total number of requests your service can handle at its current size, including limits on your servers and any dependencies.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deciding Severity
&lt;/h2&gt;

&lt;p&gt;Severity should reflect how critical the system is and how urgent the issue is to fix. If you create a high severity alert, it's a good idea to also create a low severity alert at a more sensitive level. This acts as an early alert to catch issues before they escalate.&lt;/p&gt;

&lt;p&gt;For some services, only low severity alerts may work well in case of very low customer impact.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting thresholds
&lt;/h2&gt;

&lt;p&gt;Threshold setting depends on the SLA of the services. If the service impacts a large customer base then the thresholds can be sensitive. &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fof6f1nspqvj8xdldy98b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fof6f1nspqvj8xdldy98b.png" alt="Image description" width="800" height="415"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Availability
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvj303qetxvx4406p2p2h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvj303qetxvx4406p2p2h.png" alt="Image description" width="800" height="372"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Latency
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh3fu61kc0pnjklgr5hjh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh3fu61kc0pnjklgr5hjh.png" alt="Image description" width="798" height="269"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;P50 (50th percentile) is the median latency, meaning half of the requests are processed faster, and half take longer.&lt;/p&gt;

&lt;p&gt;P90 (90th percentile) is the latency where 90% of the requests are faster, and 10% take longer.&lt;/p&gt;

&lt;p&gt;P99 (99th percentile) is the latency where 99% of the requests are faster, and only 1% take longer.&lt;/p&gt;

&lt;p&gt;P99.9 (99.9th percentile) is the latency where 99.9% of the requests are faster, and only 0.1% take longer.&lt;/p&gt;

&lt;p&gt;Threshold values should be set based on your SLA and the past performance of your application. The highest threshold should match your SLA or your client’s expectations. If your service is causing latency, it’s important that your system alerts you before your clients notice.&lt;/p&gt;

&lt;p&gt;To set the maximum threshold, check with your clients to understand their SLAs.&lt;/p&gt;

&lt;p&gt;For the minimum threshold, review your service’s performance over at least the last 45 days. Consider any recent or upcoming changes, like increased traffic, a new API, new dependencies.&lt;/p&gt;

&lt;h3&gt;
  
  
  Compute metrics
&lt;/h3&gt;

&lt;p&gt;Compute metrics should be set on CPU usage e.g. alert when CPU usage is higher than 80%. Similarly for memory usage, disk space, etc&lt;/p&gt;

&lt;h3&gt;
  
  
  Call volume
&lt;/h3&gt;

&lt;p&gt;The call volume threshold should be set just below the point where the service starts to break or fail.&lt;/p&gt;

&lt;h2&gt;
  
  
  Notification channels
&lt;/h2&gt;

&lt;p&gt;In order to alert the on-call to notify for the alert to take immediate actions, there can be various notification channels integrated with the alert framework.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwgl0fu2w819ne4i8yxr0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwgl0fu2w819ne4i8yxr0.png" alt="Image description" width="800" height="430"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Good alerts help teams catch problems early and fix them before they impact users. It’s important to set alerts for key areas like availability, latency, compute usage, and call volume. Each service is different, so alerts should match the type of service and how critical it is.&lt;/p&gt;

&lt;p&gt;Setting the right severity and thresholds helps reduce noise and focus attention on real issues. Using the right notification channels makes sure the right people get alerted in time. With clear alerts and smart settings, teams can keep systems healthy and reliable.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Datadoghq Blogs.&lt;/strong&gt; (2015). &lt;em&gt;Monitoring 101: Alerting on what matters&lt;/em&gt; &lt;br&gt;
&lt;a href="https://www.datadoghq.com/blog/monitoring-101-alerting" rel="noopener noreferrer"&gt;https://www.datadoghq.com/blog/monitoring-101-alerting&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Microsoft Blogs&lt;/strong&gt;. (2014). &lt;em&gt;Recommendations for designing a reliable monitoring and alerting strategy&lt;/em&gt; &lt;a href="https://learn.microsoft.com/en-us/azure/well-architected/reliability/monitoring-alerting-strategy" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/azure/well-architected/reliability/monitoring-alerting-strategy&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Medium&lt;/strong&gt;. (2024). &lt;em&gt;Managing Critical Alerts through PagerDuty’s Event Rules&lt;/em&gt; &lt;a href="https://medium.com/@davidcesc/managing-critical-alerts-through-pagerdutys-event-rules-2c7014eded3d" rel="noopener noreferrer"&gt;https://medium.com/@davidcesc/managing-critical-alerts-through-pagerdutys-event-rules-2c7014eded3d&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  About me
&lt;/h2&gt;

&lt;p&gt;I am a Senior Staff Software Engineer at Uber with over a decade of experience in scalable, high-performance distributed systems. I have worked on cloud-native architectures, database optimization, and building large-scale distributed systems&lt;br&gt;
Connect with me at &lt;a href="https://www.linkedin.com/in/gaurav-bansal-8465363a/" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>alerts</category>
      <category>operations</category>
    </item>
    <item>
      <title>Designing a Scalable and Real-Time Messaging System</title>
      <dc:creator>Gaurav Bansal</dc:creator>
      <pubDate>Sun, 02 Mar 2025 20:25:34 +0000</pubDate>
      <link>https://dev.to/gaurav_bansal_2e1ca573623/designing-a-scalable-and-real-time-messaging-system-4664</link>
      <guid>https://dev.to/gaurav_bansal_2e1ca573623/designing-a-scalable-and-real-time-messaging-system-4664</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this article, we will explore building a highly scale distributed[1] messaging system like whatsapp. &lt;/p&gt;

&lt;h2&gt;
  
  
  Requirements
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Functional Requirements&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;1:1 chat&lt;/li&gt;
&lt;li&gt;Send Text/Images&lt;/li&gt;
&lt;li&gt;Last seen&lt;/li&gt;
&lt;li&gt;Notify user about the new messages while he was offline, when he comes back online&lt;/li&gt;
&lt;li&gt;Read receipt (single double and blue tick)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Non-functional requirements&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Low latency - people should receive msg immediately&lt;/li&gt;
&lt;li&gt;High availability - should not go down&lt;/li&gt;
&lt;li&gt;No lag - real time system&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;API&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;POST /api/v1/chat/{conversationId}  Body - {Message text}&lt;/li&gt;
&lt;li&gt;GET /api/v1/chat/{conversationId} Returns {List}&lt;/li&gt;
&lt;li&gt;GET /api/v1/chat/status/{userId}&lt;/li&gt;
&lt;li&gt;GET /api/v1/lastseen/{userId}&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s look at the overall architecture of the whole system. First we will discuss the chatting solution and then we’ll discuss other pieces that surround it.&lt;/p&gt;

&lt;h2&gt;
  
  
  High Level Design
&lt;/h2&gt;

&lt;p&gt;Chat server, clients and db. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Deep Dive&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;System needs to receive incoming message, deliver outgoing messages.&lt;/li&gt;
&lt;li&gt;Store and retrieve message from db&lt;/li&gt;
&lt;li&gt;Store user’s last seen record&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Message Delivery Models
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Pull Model:&lt;/strong&gt;&lt;/em&gt; In this approach, clients periodically check the server for new messages. The server stores undelivered messages and provides them when the recipient requests updates. To minimize latency, clients must poll frequently, often receiving empty responses when no messages are pending. This method can be inefficient as it consumes unnecessary resources.&lt;br&gt;
&lt;em&gt;&lt;strong&gt;Push Model:&lt;/strong&gt;&lt;/em&gt; Active users maintain an open connection with the server, allowing instant message delivery as soon as they arrive. This eliminates the need for tracking pending messages and ensures low-latency communication. WebSockets[3] are commonly used to implement this model.&lt;br&gt;
[2]&lt;/p&gt;

&lt;h2&gt;
  
  
  WebSocket Handling
&lt;/h2&gt;

&lt;p&gt;A WebSocket handler (WSH) on the backend maintains open connections with all active users who have an internet connection. These connections enable real-time message transmission across various platforms, including mobile apps, web browsers, and smartwatches.&lt;/p&gt;

&lt;p&gt;Websocket connections are bi-directional, any party (client/server) can send messages to the other one.&lt;/p&gt;

&lt;h2&gt;
  
  
  WebSocket and Message Management
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;WebSocket Manager (WSM)&lt;/strong&gt;&lt;/em&gt;: WSM tracks which devices are connected to which users. It operates on a database, storing connection details between users and WebSockets. If a connection drops, the user reconnects to a different WebSocket server, and WSM updates this information in the database.&lt;br&gt;
&lt;em&gt;&lt;strong&gt;Message Service (MS)&lt;/strong&gt;&lt;/em&gt;: This component stores all system messages and retrieves unread messages for users. It also runs on a database to ensure reliability.&lt;br&gt;
&lt;em&gt;Facebook:&lt;/em&gt; Stores all messages permanently in its database.&lt;br&gt;
&lt;em&gt;WhatsApp:&lt;/em&gt; Stores messages temporarily—once a message is delivered and acknowledged, it is deleted from the system.&lt;/p&gt;

&lt;h2&gt;
  
  
  Use cases
&lt;/h2&gt;

&lt;p&gt;Assumptions:&lt;br&gt;
User U1 is connected to WSH1 and wants to send message M1 to  user U2.&lt;br&gt;
WSM returns WSH2 which is connected to U2&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Case 1: Both U1 and U2 are online and sending message to each other&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzgx5775rql0ljopulumm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzgx5775rql0ljopulumm.png" alt="Image description" width="800" height="251"&gt;&lt;/a&gt;&lt;br&gt;
There are multiple calls going  to WSM  -&amp;gt; We can keep a cache in front of WSM for optimization which will contain all users (online/offline)&lt;br&gt;
2.1 and 2.2 will happen in parallel. &lt;br&gt;
U2 is using the app and reads the delivered message, so U2 sends “Received and Read” status.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Case 2 - U1 sends a msg and U2 is offline&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdimzokpol6n1wtfkowp0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdimzokpol6n1wtfkowp0.png" alt="Image description" width="800" height="510"&gt;&lt;/a&gt;&lt;br&gt;
If U2 is offline, the message is saved in db via MS and WSH1 sends Sent status to U1.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Case 3 - U2 comes online&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F691w4gh048cjhb57v43f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F691w4gh048cjhb57v43f.png" alt="Image description" width="800" height="270"&gt;&lt;/a&gt;U2 requests for all messages which are not received or not read.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Case 4 - U1 is offline and sends a msg&lt;/strong&gt;&lt;/em&gt;&lt;br&gt;
Messages will be stored locally on the phone db. Whenever device comes online, it will push the message from the db to websocket handler&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Send File&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;U1 -&amp;gt; U2&lt;br&gt;
In the approach below the image will be sent instead of text so as a result for each connection more network bandwidth would be required as it sends image over the wire&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4pdanexjq6uyiw5rsace.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4pdanexjq6uyiw5rsace.png" alt="Image description" width="800" height="505"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Optimized&lt;/p&gt;

&lt;p&gt;WSH1 will get the URL from the Image server and give it to U1. U1 directly uploads the image on the given URL and sends a message to WSH1. Then the URL is sent to U2 as a text message. Once U2 receives the URL it will also directly download the image from the image server.&lt;br&gt;
Here the device can compress the image before uploading in the image server.&lt;/p&gt;

&lt;h2&gt;
  
  
  DB Schema
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;WSM DB&lt;/strong&gt;&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Schema&lt;/em&gt; -&amp;gt; UserId, WSH id, timestamp (last seen)&lt;br&gt;
&lt;em&gt;Queries&lt;/em&gt; -&amp;gt; GetWSH(userId)&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Messaging Service DB&lt;/strong&gt;&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Schema&lt;/em&gt; -&amp;gt; conversationId, userTo, userFrom, timestamp, status, fileUrl, type (type of file image, video, text)&lt;br&gt;
Partition key -&amp;gt; conversationId, sortKey -&amp;gt; timestamp_uuid&lt;br&gt;
&lt;em&gt;Queries&lt;/em&gt;&lt;br&gt;
getMessageGreaterThanTimestamp(conversationId, timestamp, maxCount) -&amp;gt; will paginate results if the result is greater than maxCount &lt;br&gt;
getMessageInfo(conversationId, timestamp)&lt;br&gt;
Puts&lt;br&gt;
putMessage(conversationId, userFrom, userTo, timestamp...)&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Conversation DB&lt;/strong&gt;&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Schema&lt;/em&gt; -&amp;gt; UserId1,UserId2,ConversationId; PK or ParKey- User1_User2&lt;br&gt;
&lt;em&gt;Queries&lt;/em&gt; &lt;br&gt;
getConvers(U1, U2);&lt;br&gt;
getConversation(U1) - Secondary Index - on both U1 and U2&lt;br&gt;
We can use No SQL databases[4] like AWS DynamoDB&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;A messaging system should be fast, reliable, and scalable. The push model with WebSockets enables real-time communication, while efficient WebSocket management ensures smooth interactions. Whether storing messages permanently or temporarily, the goal remains the same—delivering messages instantly while keeping the system efficient.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Splunk. 2024.&lt;/strong&gt; &lt;em&gt;Distributed System&lt;/em&gt; &lt;a href="https://www.splunk.com/en_us/blog/learn/distributed-systems.html" rel="noopener noreferrer"&gt;https://www.splunk.com/en_us/blog/learn/distributed-systems.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Medium. 2018.&lt;/strong&gt; &lt;em&gt;Push Vs Pull model&lt;/em&gt; &lt;a href="https://medium.com/@_JeffPoole/thoughts-on-push-vs-pull-architectures-666f1eab20c2" rel="noopener noreferrer"&gt;https://medium.com/@_JeffPoole/thoughts-on-push-vs-pull-architectures-666f1eab20c2&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;GeeksForGeeks. 2024.&lt;/strong&gt; &lt;em&gt;What is web socket.&lt;/em&gt; &lt;a href="https://www.geeksforgeeks.org/what-is-web-socket-and-how-it-is-different-from-the-http/" rel="noopener noreferrer"&gt;https://www.geeksforgeeks.org/what-is-web-socket-and-how-it-is-different-from-the-http/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mongodb Blog. 2023.&lt;/strong&gt; &lt;em&gt;No SQL Data base&lt;/em&gt; &lt;a href="https://www.mongodb.com/resources/basics/databases/nosql-explained" rel="noopener noreferrer"&gt;https://www.mongodb.com/resources/basics/databases/nosql-explained&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  About me
&lt;/h2&gt;

&lt;p&gt;I am a Sr Staff Software Engineer with over a decade of experience in scalable, high-performance distributed systems. I have worked on cloud-native architectures, database optimization, and large-scale distributed systems&lt;br&gt;
Connect with me at &lt;a href="https://www.linkedin.com/in/gaurav-bansal-8465363a/" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>websocket</category>
      <category>design</category>
    </item>
  </channel>
</rss>
