In this lesson, you will learn how to choose between broadcasting information to many subscribers versus assigning a specific task to a single worker.
Point-to-Point: Task Distribution
Point-to-point messaging is the backbone of the task queues we have been building. In this pattern, a producer sends a message to a queue, and exactly one worker picks it up to process it. This is essential for work that should happen only once, such as sending a welcome email or processing a payment. If you have five workers listening to the queue, they compete for jobs, ensuring that the load is distributed and tasks are not duplicated.
Pub-Sub: Event Broadcasting
In contrast, the Publish-Subscribe (Pub-Sub) pattern is designed for "broadcasting." When an event is published to a channel (or topic), every subscriber currently listening receives a copy of that message. This is perfect for when one action needs to trigger multiple independent side effects. For example, when a user updates their profile, a "UserUpdated" event might be published to trigger an analytics service, an email notification service, and a cache invalidation service simultaneously.
Choosing the Right Approach
The distinction comes down to your requirements for ownership:
- Use Point-to-Point when the work has a single "owner" and needs to be completed once. You want to ensure the task is processed, not duplicated.
- Use Pub-Sub when you have multiple decoupled systems that need to react to a state change. If you used a task queue here, you would have to manually orchestrate sending a job to every individual worker, which tightly couples your systems.
Imagine a user registration flow:
// Point-to-Point: Queueing the welcome email
queue.add('send-email', { userId: 123 }); // One worker handles it
// Pub-Sub: Notifying system components of new user
pubsub.publish('user.registered', { userId: 123 });
// Analytics, EmailService, and CRM all receive this independently
If you accidentally use Pub-Sub for task distribution, every worker will attempt the same task, potentially charging a customer three times. If you use Point-to-Point for notifications, only one service will receive the event, leaving your other systems out of the loop.
Key Takeaway: Use Point-to-Point to distribute heavy workloads among competing consumers, and use Pub-Sub to broadcast events to multiple independent systems that need to react simultaneously.