The Wayback Machine - https://web.archive.org/web/20241117170442/https://www.geeksforgeeks.org/what-is-pub-sub/
Open In App

What is Pub/Sub Architecture?

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Consider a scenario of synchronous message passing. You have two components in your system that communicate with each other. Let’s call the sender and receiver. The receiver asks for a service from the sender and the sender serves the request and waits for an acknowledgment from the receiver.

  • There is another receiver that requests a service from the sender. The sender is blocked since it hasn’t yet received any acknowledgment from the first receiver.
  • The sender isn’t able to serve the second receiver which can create problems. To solve this drawback, the Pub-Sub model was introduced.

what-is-pub-sub-architecture-banner

What is Pub/Sub Architecture?

The Pub/Sub (Publisher/Subscriber) model is a messaging pattern used in software architecture to facilitate asynchronous communication between different components or systems. In this model, publishers produce messages that are then consumed by subscribers. Key points of the Pub/Sub model include:

  • Publishers: Entities that generate and send messages.
  • Subscribers: Entities that receive and consume messages.
  • Topics: Channels or categories to which messages are published.
  • Message Brokers: Intermediaries that manage the routing of messages between publishers and subscribers.

What-is-Pub-Sub-Architecture

Components of Pub/Sub Architecture?

In the Pub/Sub (Publish/Subscribe) model, there are several key components that work together to enable communication between publishers and subscribers. These components include:

  • Publisher
    • The Publisher is responsible for creating and sending messages to the Pub/Sub system.
    • Publishers categorize messages into topics or channels based on their content. They do not need to know the identity of the subscribers.
  • Subscriber
    • The Subscriber is a recipient of messages in the Pub/Sub system. Subscribers express interest in receiving messages from specific topics.
    • They do not need to know the identity of the publishers. Subscribers receive messages from topics to which they are subscribed.
  • Topic
    • A Topic is a named channel or category to which messages are published. Publishers send messages to specific topics, and subscribers can subscribe to one or more topics to receive messages of interest.
    • Topics help categorize messages and enable targeted message delivery to interested subscribers.
  • Message Broker
    • The Message Broker is an intermediary component that manages the routing of messages between publishers and subscribers.
    • It receives messages from publishers and forwards them to subscribers based on their subscriptions.
    • The Message Broker ensures that messages are delivered to the correct subscribers and can provide additional features such as message persistence, scalability, and reliability.
  • Message
    • A Message is the unit of data exchanged between publishers and subscribers in the Pub/Sub system.
    • Messages can contain any type of data, such as text, JSON, or binary data. Publishers create messages and send them to the Pub/Sub system, and subscribers receive and process these messages.
  • Subscription
    • A Subscription represents a connection between a subscriber and a topic. Subscriptions define which messages a subscriber will receive based on the topics to which it is subscribed.
    • Subscriptions can have different configurations, such as message delivery guarantees (e.g., at-most-once, at-least-once) and acknowledgment mechanisms.

How does Pub/Sub Architecture work?

Below is how the Pub/Sub architecture works:

  • Step 1: Publishers create messages and send them to the Pub/Sub system. They sort these messages into topics or channels based on what the messages are about.
  • Step 2: Subscribers let the system know which topics they’re interested in. They’ll get messages only from those topics.
  • Step 3: Topics are basically channels for messages. Publishers send their messages to specific topics, and subscribers can choose one or more topics to follow.
  • Step 4: Message brokers act as go-betweens, managing how messages get from publishers to subscribers. They take messages from publishers and send them to the subscribers who are interested.
  • Step 5: When a publisher sends a message to a topic, the message broker grabs it and sends it out to all the subscribers who have signed up for that topic.
  • Step 6: The Pub/Sub system allows for asynchronous communication. This means publishers can send messages without waiting for subscribers to be ready, and subscribers can pick up messages whenever it suits them, without needing the publisher to be around

Real-World Example of Pub/Sub Architecture

A real-life example of Pub/Sub architecture can be seen in the operation of a social media platform like Twitter.

  • Publishers: Users post tweets, which are published to the Twitter platform.
  • Subscribers: Followers of a user subscribe to their tweets to receive updates.
  • Topics: Each user’s tweets can be considered a topic, and subscribers receive updates for the topics they are interested in.
  • Message Broker: Twitter’s backend infrastructure acts as the message broker, routing tweets from publishers to subscribers.
  • Message: Each tweet is a message that is published by the user and received by their followers.

In this example, the Pub/Sub architecture allows for scalable and efficient distribution of tweets to followers. Publishers (users) can publish tweets without knowing who will receive them, and subscribers (followers) receive updates in real-time without the need for direct communication with the publishers.

Use-cases of Pub/Sub Architecture

The Pub/Sub (Publisher/Subscriber) architecture is widely used in various scenarios where asynchronous and scalable communication between components is required. Some common use cases of Pub/Sub architecture include:

  • Real-time Data Streaming: It’s often used in applications that deal with real-time data, like IoT devices and sensor networks, allowing multiple subscribers to get data streams right away.
  • Event-driven Architectures: This setup works well for systems that react to events instead of constantly checking for updates, making applications more responsive.
  • Message Queues: Pub/Sub can act as a message queue, temporarily holding messages until subscribers can process them, which helps manage how messages are delivered.
  • Notifications and Alerts: It’s used for sending notifications and alerts, letting publishers send important updates that subscribers can receive instantly.
  • Scalable Web Applications: In web apps, Pub/Sub supports features like real-time updates and chat, so many users can receive information at the same time without overloading the server.
  • Microservices Communication: Finally, it helps microservices talk to each other, allowing them to communicate without being tightly connected, which improves scalability and reliability.

Types of Pub/Sub Services

Below are the two types of Pub/Sub Services:

1. Pub/Sub Service

This is the main messaging service that most users and applications choose. It provides:

  • High Reliability: Ensures that messages are delivered consistently.
  • Integrations: Supports a wide range of integrations with other services.
  • Automatic Capacity Management: Handles scaling automatically based on demand.
  • Data Replication: Synchronously replicates all data to at least two zones and offers best-effort replication to a third zone for added reliability.

2. Pub/Sub Lite Service

This is a separate messaging service designed to be more cost-effective but comes with some trade-offs:

  • Lower Reliability: Offers less reliability compared to the standard Pub/Sub service.
  • Zonal or Regional Storage: Zonal Lite topics are stored in one zone, while Regional Lite topics replicate data to a second zone asynchronously.
  • Pre-provisioning Required: You need to manage and provision your own storage and throughput capacity.
  • Cost-Effective: Consider this option if keeping costs low is essential, and you can accept the lower reliability and some extra management tasks.

Comparing Pub/Sub to other Messaging Technologies

Below is the comparison of Pub/Sub to other messaging Technologies:

  • Pub/Sub vs. Message Queues
    • Message Queues (e.g., RabbitMQ): Focus on delivering messages to one consumer at a time, ensuring delivery and often preserving order. Best for point-to-point communication.
    • Pub/Sub: Broadcasts messages to multiple subscribers simultaneously, making it ideal for event-driven systems where many services need to react to the same event.
  • Pub/Sub vs. Streaming Platforms
    • Streaming Platforms (e.g., Kafka): Designed for processing continuous streams of data and can retain messages for longer periods. More complex but great for analytics.
    • Pub/Sub: Simpler and geared towards real-time delivery of messages without extensive setup.
  • Pub/Sub vs. WebSockets
    • WebSockets: Enable real-time, bidirectional communication between clients and servers. Best for applications like chat.
    • Pub/Sub: Decouples publishers and subscribers, allowing for multiple subscribers to receive the same message without needing direct connections.
  • Pub/Sub vs. HTTP APIs
    • HTTP APIs: Follow a synchronous request-response model where clients wait for replies. Good for direct interactions.
    • Pub/Sub: Allows asynchronous communication, letting publishers send messages without waiting for subscribers to respond

When and When not to Use Pub/Sub Architecture

1. When to Use the Pub/Sub Architecture

Use Pub/Sub Architecture when:

  • Subscribers don’t need to know about each other, making the system more flexible and easier to scale.
  • Pub/Sub helps you build systems that can grow easily. You can add more publishers or subscribers without disrupting the existing setup.
  • If you want parts of your system to communicate without waiting for each other, Pub/Sub is a great option. Publishers can send messages without needing to wait for subscribers.
  • This approach is perfect for event-driven systems. Publishers can send out events, and subscribers can respond to those events without being tightly linked together.
  • With Pub/Sub, subscribers can change their interests at runtime. They can subscribe to different topics or types of messages, adding more flexibility to the system.

2. When Not to Use the Pub/Sub Architecture

Donot use Pub/Sub Architecture when:

  • If you need very quick communication between parts of your system, Pub/Sub might not be the best option. The process of routing messages and managing subscriptions can slow things down.
  • Using Pub/Sub can make your system more complicated, especially when it comes to routing messages and handling subscriptions.
  • Pub/Sub doesn’t guarantee that messages will be delivered in the order they were sent. If your application needs messages to arrive in a specific sequence, Pub/Sub may not work for you.
  • For smaller applications where a few components communicate directly, using Pub/Sub could add unnecessary complexity that isn’t needed.

How Scalable and Secure is Pub/Sub Architecture?

The scalability and security of the Pub/Sub model depend on the implementation and the specific requirements of the system. However, in general, the Pub/Sub model can be both scalable and secure if implemented correctly.

  • Scalability:
    • Horizontal Scalability: Pub/Sub systems can be designed to scale horizontally by adding more publishers, subscribers, or message brokers. This allows the system to handle a large number of messages and subscribers without a significant decrease in performance.
    • Load Balancing: Pub/Sub systems can use load balancing techniques to distribute messages evenly across multiple message brokers or nodes, ensuring efficient use of resources and handling of high message volumes.
  • Security:
    • Access Control: Pub/Sub systems can implement access control mechanisms to ensure that only authorized publishers and subscribers can send or receive messages. This helps protect against unauthorized access and data breaches.
    • Encryption: Messages exchanged in a Pub/Sub system can be encrypted to protect them from eavesdropping and ensure data confidentiality. Transport Layer Security (TLS) can be used to secure message transmission over the network.
    • Authentication and Authorization: Pub/Sub systems can use authentication and authorization mechanisms to verify the identity of publishers and subscribers and ensure that they have the necessary permissions to send or receive messages.
  • Challenges:
    • Message Ordering: Ensuring strict message ordering can be challenging in a distributed Pub/Sub system, especially when messages are processed by multiple subscribers concurrently.
    • Message Delivery Guarantees: Pub/Sub systems typically provide at-least-once or at-most-once message delivery guarantees, which may not be suitable for all applications requiring exactly-once semantics.

Benefits and Challenges of Pub/Sub Architecture

1. Benefits of Pub/Sub Architecture

Below are the benefits of Pub/Sub Architecture:

  • Scalability: Pub/Sub systems can easily expand to accommodate numerous publishers, subscribers, and messages. This flexibility comes from the separation of publishers and subscribers, along with the use of message brokers to manage how messages are sent out.
  • Decoupling: In a Pub/Sub setup, publishers and subscribers are kept separate, allowing them to function independently. This separation simplifies the design and maintenance of the system, making it easy to add or remove components as needed.
  • Asynchronous Communication: Pub/Sub enables asynchronous communication between components, enhancing the responsiveness and efficiency of the system. Publishers can send messages without having to wait for subscribers, who can take their time processing the messages.
  • Reliability: Pub/Sub systems are designed to be dependable, incorporating features that ensure messages are successfully delivered. This includes things like message acknowledgments, retries, and strategies to deal with faults.

2. Challenges of Pub/Sub Architecture

Below are the challenges of Pub/Sub Architecture:

  • Message Ordering: Pub/Sub systems usually don’t guarantee the order in which messages reach subscribers. This can create problems for applications that need messages to arrive in a specific sequence, as subscribers might get them out of order.
  • Exactly-once Message Delivery: Achieving exactly-once message delivery can be tricky in Pub/Sub systems, especially when there are failures or network problems. Creating methods to ensure messages are delivered once without duplicates can be complicated.
  • Latency: Pub/Sub systems can introduce delays because of how messages are routed and delivered. Balancing low latency with scalability and reliability is especially challenging for real-time applications where speed is crucial.
  • Complexity: Setting up a Pub/Sub architecture can add complexity, particularly in large-scale environments. Managing subscriptions, routing messages, and keeping everything consistent across distributed components requires careful planning and oversight.

Pub/Sub Vs. Point to Point Messaging

Below are the differences between Pub/Sub and Point to Point Messaging:

Aspect Pub/Sub Messaging Point-to-Point Messaging
Message Delivery Messages are broadcast to multiple subscribers Messages are delivered to a single receiver
Subscriber Knowledge Publishers do not need to know about subscribers Sender needs to know the receiver
Scalability Scalable, as new subscribers can be added without affecting publishers Less scalable, as each message is sent directly to a specific receiver
Coupling Loosely coupled, as publishers and subscribers are decoupled Tightly coupled, as sender and receiver are directly connected
Use Case Suitable for broadcasting messages to multiple recipients Suitable for one-to-one communication
Example Technology Google Cloud Pub/Sub, Amazon SNS/SQS, Kafka JMS, AMQP, RabbitMQ



Previous Article
Next Article

Similar Reads

Difference between System Architecture and Software Architecture
1. System Architecture : System architecture is a conceptual model that describes the structure and behavior of multiple components and subsystems like multiple software applications, network devices, hardware, and even other machinery of a system. It is Architecture Description Language (ADL) which helps to describe the entire system architecture.
3 min read
MVC Architecture vs. Microservices Architecture
In the world of system design, choosing the right architecture for your project is crucial. Two prominent contenders are Microservices and Model-View-Controller (MVC). While both offer distinct advantages, understanding their core differences is essential for making an informed decision. Important Topics for MVC vs. Microservices Architecture Micro
3 min read
Lambda Architecture vs. Kappa Architecture in System Design
Lambda and Kappa Architectures are popular data processing models used in big data systems to handle real-time and batch processing. While Lambda Architecture separates batch and real-time processing for fault tolerance and scalability, Kappa Architecture simplifies the process by focusing solely on stream processing for real-time analytics. This a
6 min read
Event-Driven Architecture vs Data-Driven Architecture
In System Design, architecture plays a crucial role in determining how systems handle and process information. Two prominent architectural paradigms are Event-Driven Architecture (EDA) and Data-Driven Architecture (DDA). Both approaches offer distinct methods for managing data and interactions within systems, and understanding their differences can
4 min read
Event-Driven Architecture vs. Microservices Architecture
In system design, choosing the right architecture is crucial for building scalable and efficient systems. Two popular approaches, Event-Driven Architecture (EDA) and Microservices Architecture, each offer unique benefits. This article explores their definitions, differences, use cases, and more. Table of Content What is Event-Driven Architecture?Wh
4 min read
Message-Driven Architecture vs. Event-Driven Architecture
Message-driven and event-driven architectures are both communication patterns used to build scalable, decoupled systems. They focus on how components communicate asynchronously. In this article, we will see the differences between message-driven and event-driven architecture: Table of Content What is Message-Driven Architecture?What is Event-Driven
4 min read
Android System Architecture
The Android software stack generally consists of a Linux kernel and a collection of C/C++ libraries that are exposed through an application framework that provides services, and management of the applications and run time. Linux KernelAndroid was created on the open-source kernel of Linux. One main reason for choosing this kernel was that it provid
3 min read
Biometric System Architecture
Biometrics are computerized methods of identifying a person based on physiological and observable qualities. The use of biometric systems has impacted the way we identify and authenticate ourselves around the world. By utilizing this technology, not only has the identification of people changed, but also the time it takes to identify and verify peo
3 min read
Architecture of an Embedded System | Set-3
Typical embedded system mainly has two parts i.e., embedded hardware and embedded software. Embedded hardwares are based around microprocessors and microcontrollers, also include memory, bus, Input/Output, Controller, where as embedded software includes embedded operating systems, different applications and device drivers. Basically these two types
2 min read
Fundamentals of Software Architecture
In the world of technology, starting from small children to young people and starting from young to old people everyone using their Smartphones, Laptops, Computers, PDAs etc to solve any simpler or complex task online by using some software programs, there everything looks very simple to user. Also that's the purpose of a good software to provide g
4 min read
SQA system and architecture
Software Quality Assurance (SQA) is a set of exercises for ensuring quality in software measures. It ensures that created programming meets and follows the characterized or normalized quality determinations. SQA is a progressing cycle inside the Software Development Life Cycle (SDLC) that regularly checks the created software to ensure it meets the
4 min read
Solving Non-Determinism with Blackboard Architecture
The Blackboard Architecture is particularly well-suited for addressing non-deterministic problems by leveraging the collective knowledge and expertise of multiple knowledge sources. But the question now arises How does the Blackboard Pattern actually solve the problem of Non-Determinism? In this post, we will deep dive into the problem of non-deter
9 min read
Architecture of a System
Architecture is a critical aspect of designing a system, as it sets the foundation for how the system will function and be built. It is the process of making high-level decisions about the organization of a system, including the selection of hardware and software components, the design of interfaces, and the overall system structure. Components con
4 min read
Blackboard Architecture
Blackboard architecture, also known as the blackboard system, is a problem-solving approach that utilizes a modular and decentralized framework. It effectively solves complex problems that lack a well-defined algorithm or a pre-determined architecture. Blackboard architecture is inspired by human experts collaborating and solving difficult problems
2 min read
E-commerce Architecture | System Design for E-commerce Website
To sell and buy the goods and services we have to develop a system that helps the seller to connect with customers or customers can connect with multiple sellers. For this, we developed different E-Commerce architectures that we see in this article, components of E-Commerce architecture, and advantages of E-Commerce all these topics will be covered
7 min read
3 Essentials for E-commerce Architecture
Building a top-notch e-commerce store requires speed optimization, having the best Content Delivery Network (CDN), the best databases and servers according to requirements, etc. These factors should be the priority in an online e-commerce business but they may not result in the growth of the online e-commerce store in the long run. So a solid e-com
4 min read
Hexagonal Architecture in Java
As per the software development design principle, the software which requires the minimum effort of maintenance is considered as good design. That is, maintenance should be the key point which an architect must consider. In this article, one such architecture, known as Hexagonal Architecture which makes the software easy to maintain, manage, test,
6 min read
What is Microservice Architecture and Why to Use Them?
Building an application is all about making it efficient and effective. There are various ways to make an application run smoothly. The major reason which makes an application function properly is the invention of microservice architecture. Microservice architecture helps you to break large components into sub-components thus making debugging easie
8 min read
Difference between System Design and System Architecture
When it comes to software development and engineering there can be some confusion, between the two terms "System Design" and "System Architecture." Although they are related they actually refer to stages and responsibilities in creating scalable and efficient systems. It is important to grasp the differences, between System Design and System Archit
3 min read
Architecture for Mobile Development | Design Patterns
Hey there, tech enthusiasts! Ever wonder what makes your favorite mobile apps so smooth and user-friendly? Well, the secret lies in their architecture – the behind-the-scenes structure that turns code into the awesome apps we can't live without. Important Topics for Mobile Development Architecture Classic MVC or MVC (Model-View-Controller) Architec
9 min read
What is Lambda architecture | System Design
This Architecture is widely used in many big tech companies as it takes advantage of both real-time data processing as well as batch processing i.e. one can query both fresh data by real-time data processing technique and historical data using batch processing data technique. Important Topics for Lambda Architecture What is Lambda Architecture? Dif
5 min read
What are the Components of Mach Architecture?
The components of MACH Architecture include Microservices, API-First Design, Cloud-Native Architecture, and Headless Architecture. Below is the explanation of each component: MicroservicesMicroservices are small, independent services that each handle a specific business function or capability. Each microservice typically runs in its process and com
2 min read
Containerization Architecture in System Design
In system design, containerization architecture describes the process of encapsulating an application and its dependencies into a portable, lightweight container that is easily deployable in a variety of computing environments. Because it makes the process of developing, deploying, and scaling applications more efficient, this approach has become i
10 min read
Monolithic Architecture - System Design
Monolithic architecture, a traditional approach in system design, actually contains all components of an application into a single codebase. This unified structure simplifies development and deployment processes, offering ease of management and tight integration. However, its rigidity poses scalability and maintenance challenges, hindering adaptabi
10 min read
Importance of Stateless Architecture in Authorization Systems
Stateless architecture plays a pivotal role in modern authorization systems, offering a streamlined approach to managing user access securely and efficiently. By eliminating the need for server-side session storage, stateless architecture simplifies scalability, enhances reliability, and provides security. In stateless authorization systems, each r
10 min read
Steps to Migrate From Monolithic to Microservices Architecture
Moving from one big block of software to many smaller blocks might seem hard, but it's worth it. In this article, we'll show you how to do it step by step. We'll break down the big blocks into smaller ones, making your software more flexible and strong. It's like upgrading from a bulky car to a sleek, faster one. So, let's get started on making you
5 min read
How to Build a Fault Tolerant Architecture with Bulkhead Pattern?
Building fault-tolerant architectures has become essential for ensuring continuous operation and minimizing the impact of failures. One effective approach to achieving fault tolerance is through the use of the Bulkhead Pattern, inspired by the watertight compartments of ships that prevent flooding from spreading and sinking the entire vessel. By im
10 min read
Microservices Architecture for Enterprise Large-Scaled Application
In digital systems, large-scale applications are the backbone of many businesses. However, maintaining and scaling these monolithic systems can be a difficult task. The microservices architecture is a revolutionary approach to software development that breaks down these complex applications into smaller, more manageable pieces. Let's say While buil
9 min read
Active Active vs. Active Passive Architecture
In system design, the debate between Active-Active and Active-Passive configurations sparks intense discussion. Active-Active employs parallel processing, allowing simultaneous use of multiple resources for enhanced performance and resilience. Conversely, Active-Passive relies on a standby system that activates only when the primary system fails, e
6 min read
Architecture Patterns for Resilient Systems
Resilient architecture patterns help our systems stay strong even when facing challenges. In this article, we will see some resilience architecture patterns. We'll explore how these patterns work by looking at real-life examples. By the end of this article, you'll have a clear picture of how these patterns work and how to use them to make your syst
6 min read
three90RightbarBannerImg