LogoMasst Docs

Pub/Sub

Understanding the publish-subscribe messaging pattern.

What is Pub/Sub?

Pub/Sub (Publish-Subscribe) is a messaging pattern where publishers send messages to topics, and subscribers receive messages from topics they're interested in. Publishers and subscribers are decoupled.


How It Works

Publishers                Topics              Subscribers
     │                      │                      │
Publisher A ─── orders ────►│                      │
     │          topic       │──► orders ──────────► Subscriber 1
     │                      │                      │
Publisher B ─── payments ──►│                      │
     │          topic       │──► orders ──────────► Subscriber 2
     │                      │                      │
     │                      │──► payments ────────► Subscriber 3

Pub/Sub vs Message Queue

AspectMessage QueuePub/Sub
DeliveryOne consumer per messageAll subscribers get message
PatternPoint-to-pointBroadcast
Use caseTask distributionEvent notification
Message removalAfter consumptionAfter delivery to all

Key Concepts

ConceptDescription
PublisherProduces messages to topics
SubscriberConsumes messages from topics
TopicNamed channel for messages
SubscriptionConnection between topic and subscriber
Fan-outOne message to many subscribers

Delivery Models

Push

Messages pushed to subscribers:

Topic ──push──► Subscriber (webhook, streaming)

Pull

Subscribers poll for messages:

Subscriber ──pull──► Topic

Use Cases

Use CaseExample
Event-driven architectureOrder placed → inventory, shipping, notification
Real-time updatesStock prices, live scores
Log aggregationMultiple services → central logging
Cache invalidationDB update → invalidate caches
Microservices communicationService events

SystemTypeStrengths
Apache KafkaLog-basedHigh throughput, replay
Google Pub/SubManagedServerless, global
AWS SNSManagedAWS integration
Redis Pub/SubIn-memorySimple, fast
RabbitMQBrokerFlexible routing

Kafka vs Traditional Pub/Sub

AspectKafkaTraditional (Redis)
PersistenceMessages stored on diskMessages in memory
ReplayCan replay old messagesMessages lost after delivery
OrderingOrdered within partitionBest effort
ThroughputVery highHigh

Fan-out Pattern

One event triggers multiple actions:

Order Placed

     ├──► Inventory Service (reduce stock)
     ├──► Email Service (send confirmation)
     ├──► Analytics Service (track order)
     └──► Shipping Service (prepare shipment)

Interview Tips

  • Explain difference from message queues
  • Discuss fan-out and event-driven architecture
  • Compare push vs pull delivery
  • Mention Kafka for ordered, persistent events
  • Give real-world examples: notifications, event sourcing