Publish/Subscribe Patterns: Topics, Subscriptions, Filtering
Learn publish-subscribe messaging patterns: topic hierarchies, subscription management, message filtering, fan-out, and dead letter queues.
Publish/subscribe sends events to topics so a producer can notify independent consumers without calling each one. This guide compares topic hierarchies, durable and shared subscriptions, filtering, delivery guarantees, and dead letter queues, including their effects on ordering and consumer lag. It helps you choose a delivery model, plan idempotent consumers for at-least-once delivery, and recognize when a queue or RPC is simpler.
Publish/Subscribe Patterns: Topics, Subscriptions, and Filtering
Introduction
An order service often starts by calling every downstream service itself. When inventory, billing, fraud detection, and analytics each need the same order event, those calls couple checkout to services that should be independent:
// Direct calls make checkout own every downstream dependency.
inventory.reserve(order)
billing.sendReceipt(order)
fraud.check(order)
analytics.record(order)
// With pub/sub, checkout publishes the event and subscribers react.
broker.publish("orders.placed", { order_id: order.id })
In publish/subscribe, publishers send messages to named topics and subscribers listen to the topics they need. The publisher does not need to know who is listening. Whether messages wait for an offline subscriber depends on the broker and subscription configuration.
This guide covers topic design, subscription management, filtering, fan-out, delivery guarantees, and failure handling. It also explains when a queue or direct RPC is a simpler fit.
Topic-Specific Deep Dives
Topic Design
Topics are the core abstraction in pub/sub. Getting them right makes everything else easier.
Flat Topics
The simplest approach: one topic per message type.
user.created
order.placed
payment.processed
Each subscriber chooses which topics to listen to. Simple, but limited. What if you want all user events? You subscribe to multiple topics.
Hierarchical Topics
Hierarchies organize topics into trees, enabling broader subscriptions:
users/
users.created
users.updated
users.deleted
orders/
orders.placed
orders.updated
orders.cancelled
payments/
payments.processed
payments.failed
Subscribing to orders/ gives you all order events. Subscribing to users.* gives you all user lifecycle events.
These wildcard examples are conceptual; topic separators and matching rules vary by broker. RabbitMQ topic exchanges use dot-separated routing keys, * for one word, and # for zero or more words.
graph TD
Publisher -->|publish| Topic[orders.placed]
subgraph Subscribers
Analytics[Analytics Service]
Notifications[Notification Service]
Audit[Audit Service]
end
Topic -->|orders.placed| Analytics
Topic -->|orders.placed| Notifications
Topic -->|orders.placed| Audit
Naming conventions matter. Without some discipline, hierarchies turn into a mess pretty quickly.
Subject-Based vs Content-Based
Most pub/sub systems are subject-based: topics are predefined strings that publishers use. Subscribers choose topics to listen to.
Content-based systems route based on message content. A subscriber might say “give me all messages where amount > 1000.” This is more flexible but harder to implement efficiently. It also raises security concerns—what if a subscriber crafts queries to sniff data they should not see?
Most teams end up using subject-based routing. It is simpler to implement and performs well at scale.
Subscription Management
Subscriptions track what each subscriber wants. Managing their lifecycles is trickier than it sounds.
Durable Subscriptions
A durable subscription is broker-specific. For RabbitMQ’s AMQP 0-9-1 queues, durability belongs to the queue: the queue survives a broker restart, while messages also need to be published as persistent to survive recovery. Publisher confirms give the publisher an acknowledgment after the broker accepts a message. Queue limits, message expiration, and broker health still affect retention; “durable” does not mean “kept forever.”
// RabbitMQ: a separate durable queue per independent subscriber
exchange = declare_exchange("orders", type="topic", durable=true)
queue = declare_queue("billing.orders", durable=true)
bind(queue, exchange="orders", routing_key="orders.#")
publish("orders", routing_key="orders.placed", persistent=true)
The binding is illustrative; the queue must also have a configured retention policy and the publisher should use confirms when it needs to know the broker accepted a publication. Other brokers use different subscription and retention controls.
Shared Subscriptions
“Shared subscription” is not a universal broker feature name. In RabbitMQ, multiple consumers on the same queue compete for deliveries, so each message is normally sent to one of them. To broadcast each event to independent subscribers, give each subscriber its own queue and bind each queue to the exchange.
orders exchange -> billing queue -> [billing-1, billing-2]
-> analytics queue -> [analytics-1]
The billing workers share work from one queue. The analytics queue receives its own copy. With competing consumers, completion order can differ from publish order, especially after retries or redelivery.
Replay
A durable queue and a replayable log solve different problems. RabbitMQ queues remove acknowledged messages, so they do not provide general replay after acknowledgment. RabbitMQ Streams are append-only logs that support reading again from an offset or timestamp while the data remains within the stream’s retention limits. Other brokers expose their own retention and offset models.
Message Filtering
Sometimes subscribers only need a subset of what a topic publishes. Filtering lets them narrow what they receive.
Topic-Level Filtering
Use a broker’s routing key or topic filter to route a narrow class of events. For example, a RabbitMQ topic exchange can route orders.placed to a queue bound with orders.*. It matches the routing key, not fields inside the JSON body.
The publisher must choose the routing key, so routing conventions should describe the event rather than a subscriber’s private implementation details.
Header-Based Filtering
Messages have headers (key-value pairs) that you can use for filtering:
{
"topic": "orders",
"headers": {
"priority": "high",
"region": "us-west",
"source": "web"
},
"body": { "order_id": "12345", "amount": 5000 }
}
Some brokers can filter message attributes or headers, but the expression syntax and supported fields vary. A filter such as region = 'us-west' AND priority = 'high' is illustrative, not portable broker syntax.
This separates the publisher’s classification from the subscriber’s selection when the broker supports it.
Broker Filter Policies
Amazon SNS uses a JSON filter policy, not SQL. Policies match message attributes by default, or the message body when the subscription’s FilterPolicyScope is set to MessageBody.
{
"FilterPolicy": {
"amount": [{ "numeric": [">", 1000] }],
"region": ["us-west"]
}
}
The example matches SNS attributes unless the subscription selects body filtering. This is a broker-defined policy format, not an arbitrary SQL query.
Fan-Out Patterns
Fan-out describes how one message reaches multiple subscribers. The pattern changes depending on what you need.
Broadcast Fan-Out
Every subscriber receives every message. The simplest model.
graph LR
Pub[Publisher] -->|1 message| Topic
Topic -->|copy 1| Sub1[Subscriber 1]
Topic -->|copy 2| Sub2[Subscriber 2]
Topic -->|copy 3| Sub3[Subscriber 3]
The broker makes copies. Cost scales with subscriber count.
Selective Fan-Out
With filtering, only matching subscribers receive the message. More efficient but requires the broker to evaluate filters.
Dead Letter Queues
When a subscriber cannot process a message (crashes, returns error, times out), what happens? Dead letter queues capture failed messages so you can inspect them later.
graph LR
Pub[Publisher] --> Topic
Topic -->|normal| Sub[Subscriber]
Topic -->|failed after retries| DLQ[Dead Letter Queue]
Without DLQs, poison messages block the queue or get dropped silently. DLQs let you see what failed and why.
Implementation Considerations
Picking the right topic design and subscription model is only half the work. Real pub/sub systems face practical challenges once messages start flowing — messages arrive out of order, consumers fall behind, duplicates sneak through, and delivery guarantees need to match what your processing model can handle. Each consideration below shapes how you configure brokers, write consumers, and plan for failure.
Message Ordering
Ordering rules belong to a broker and its topology. RabbitMQ can preserve enqueue order in a queue under constrained conditions, but multiple consumers, priorities, negative acknowledgments, and redelivery can change the order in which work completes. A routing key or correlation ID does not restore order on its own. If updates for one account must be applied in sequence, serialize that account’s work or partition it to one ordered consumer path.
Backpressure Handling
When subscribers cannot keep up with message throughput, backpressure prevents the system from collapsing. Without it, consumers run out of memory or broker queues grow without bound.
Buffer-based approaches accumulate messages locally up to a limit:
local_buffer = RingBuffer(capacity=1000)
while local_buffer.has_capacity():
message = broker.fetch()
local_buffer.push(message)
process_batch(local_buffer.drain())
When the buffer fills, the subscriber must either drop messages, pause consumption, or signal the broker to slow down.
Flow control signals let subscribers push back on publishers:
subscriber --> [Window Full] --> broker --> publisher slows production
RabbitMQ uses basic.qos with prefetch to limit unacknowledged messages. Kafka has consumer group rebalance hooks for similar behavior.
Exponential backoff on consumption failures keeps repeated processing failures from creating message pileup:
retry_delay = 1_000 # ms
for attempt in range(max_retries):
try:
process(message)
ack(message)
break
except TransientError:
sleep(retry_delay)
retry_delay *= 2
retry_delay = min(retry_delay, max_delay)
The key takeaway: backpressure should propagate upward, not accumulate silently. If your subscribers cannot keep up, the system should throttle publishers or shed load, not buffer forever.
Message Deduplication
At-least-once delivery can redeliver the same message. An idempotent consumer tracks stable event IDs so a retry does not apply the same state change twice.
BEGIN DATABASE TRANSACTION
record event_id with a unique constraint
if this event_id is new:
apply the business change
COMMIT
ack message only after commit
Store the event ID and apply the business change in the same database transaction. A separate “check, then write” step can race when two deliveries run at once.
A RabbitMQ consumer contract
For the example below, assume RabbitMQ with AMQP 0-9-1, a durable queue, persistent publications, publisher confirms, manual consumer acknowledgments, and a configured dead-letter exchange. These settings provide a useful at-least-once workflow, but they do not make an arbitrary database side effect exactly once.
- The publisher sends a persistent message and waits for a publisher confirm. If a publication is retried after a lost confirm, it may appear twice; keep a stable
event_id. - The consumer applies the event and records its
event_idin a unique-key table in the same database transaction. It sendsackonly after that transaction commits. If the consumer or connection fails before the ack, RabbitMQ can redeliver the message. - Retry transient errors with a bounded delay and attempt count. Avoid immediate
nack(requeue=true)loops. After the retry limit, reject withrequeue=false; RabbitMQ routes the message to a configured dead-letter exchange, or drops it if none is configured. Monitor the dead-letter queue and redrive only after fixing the cause. - If processing order matters, use a queue and consumer topology that serializes the relevant entity. Multiple competing consumers can finish work out of order even when the queue received messages in order.
The event envelope should carry a stable ID and an explicit schema version:
{
"event_id": "evt_01J8Q4M7N2",
"event_type": "orders.placed",
"schema_version": 2,
"occurred_at": "2026-11-24T12:00:00Z",
"data": {
"order_id": "ord_123",
"currency": "USD",
"total_minor": 2599
}
}
Consumers can usually tolerate additive optional fields if they ignore fields they do not recognize. For a breaking change, publish a new schema version and keep old consumers working during migration. Validate the envelope before applying side effects.
See RabbitMQ’s documentation for topic exchanges, durable queues, acknowledgments and publisher confirms, dead-letter exchanges, and stream replay and retention.
Delivery Guarantees Deep Dive
Pub/sub systems offer different delivery guarantees. The right choice depends on your processing model.
| Handling choice | Typical loss path | Typical duplicate path | Implementation note |
|---|---|---|---|
| At-most-once | Consumer acknowledges or drops before the side effect completes | Usually none from broker retry | Simple, but work can be lost |
| At-least-once | Depends on publisher, broker, and retention configuration | Consumer fails after side effect but before acknowledgment | Use idempotent side effects |
| Exactly-once | Depends on the broker’s stated scope and transaction model | External effects can still repeat outside that scope | Verify the specific broker feature and boundary |
These labels describe a configured delivery contract, not a guarantee shared by every broker. The RabbitMQ example above uses manual acknowledgments and idempotent processing. An “exactly once” broker feature does not automatically make an external database or API call exactly once; see delivery guarantees and their limits.
Pub/sub connects closely to event-driven architecture, where topics carry domain events between services. It also relates to message queue types for understanding where pub/sub fits in the broader messaging landscape.
Trade-off Analysis
| Design Choice | Pros | Cons | When to Use |
|---|---|---|---|
| Flat Topics | Simple, easy to understand | No wildcard subscriptions, subscribers must list each topic | Small number of independent topics |
| Hierarchical Topics | Wildcard subscriptions, natural organization | Naming discipline required, can become messy | Large topic spaces with natural groupings |
| Subject-Based Routing | Efficient, simple broker logic | Limited flexibility | Most production systems |
| Content-Based Routing | Maximum flexibility for subscribers | Complex broker logic, security concerns | Specialized filtering requirements |
| Durable Queues/Subscriptions | Can retain configured messages while consumers are offline | Storage use and retention limits need planning | Consumers that can be unavailable temporarily |
| Competing Consumers | Divide one queue’s work across instances | Processing order can change; duplicates still need handling | Parallel, mostly independent work |
| Separate Subscriber Queues | Each subscriber receives its own routed copy | More queues and storage to operate | Independent fan-out and recovery |
| Broadcast Fan-Out | Simple, all subscribers get all messages | Scales with subscriber count | Notifications, event broadcasting |
| Selective Fan-Out | Efficient, subscribers get only relevant messages | Broker must evaluate filters | Targeted deliveries, filtered streams |
When to Use / When Not to Use
When to Use Publish-Subscribe
Pub/sub is for those one-to-many situations. One event, multiple consumers, all independent of each other. Fits naturally when you notice your code calling three different services after a single operation and each one is doing something unrelated.
Where it fits:
| Scenario | Why Pub/Sub Fits | Example |
|---|---|---|
| Event broadcasting | One message triggers several downstream actions | order.placed → inventory update, receipt generation, fraud check, analytics push |
| Cross-service data sync | Same data ends up in multiple systems | Profile update → refresh search index, invalidate cache, push to warehouse |
| Webhook delivery | External services subscribe to internal events | Payment complete → notify partners, update dashboards, fire Slack alerts |
| IoT ingestion | Many devices, many consumers of that stream | Sensor readings → real-time dashboard, anomaly detection, long-term archive |
| Audit logging | Every action recorded without coupling to business logic | Admin action → audit trail, suspicious-activity alert |
The tell: you have a service that currently calls three downstream services in sequence after one database write, and none of them have anything to do with the original operation. The order service should not know about your notification system or your analytics pipeline. Pub/sub lets you drop that coupling — publish order.placed and move on. What happens downstream is someone else’s problem.
When Not to Use Publish-Subscribe
Pub/sub breaks down when your use case needs something it was never designed to provide. The decoupling that makes it powerful works against you the moment you need to track outcomes or enforce sequence.
The clearest misfit is request-response. When service A calls service B and needs a result before continuing, topics do not help. A publishes and moves on without knowing whether B received anything or what it did. For synchronous calls, use RPC (gRPC, REST) or a queue with a reply-to header.
Ordering across topics and publishers depends on the broker. Many systems preserve order only within a queue, partition, or key. A correlation ID helps trace related events; it does not sort them. If a consumer must apply updates for one account in order, route that account through a serialized processing path.
Work distribution sounds like a good fit for topics but is simpler with a queue. Topics broadcast to all subscribers by default. Without filtering, every worker gets every message, and you end up building de-duplication and load balancing on top of pub/sub when a queue with competing consumers gives you that for free.
The trickiest case is synchronous choreography. When the order service needs to wait until inventory, fraud check, and receipt generation all finish before it can confirm the order, you are building a synchronous workflow on an asynchronous backbone. A saga pattern or a direct call chain fits that better than topics.
Bottom line: pub/sub assumes producers and consumers are independent and the producer does not care what happens downstream. The moment you need to track outcomes, know who handled something, or enforce sequence, use a different pattern.
Production Failure Scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Broker goes down | All publishing and subscribing stops | Deploy broker clusters with replication; use multiple broker endpoints |
| Subscriber crash during processing | Message may be lost or reprocessed | Use manual acknowledgment; configure prefetch limits |
| Message explosion (too many subscribers) | Network saturation, increased latency | Limit subscription count; use content filtering at broker |
| Topic explosion (too many topics) | Memory pressure on broker | Implement topic naming policies; use topic hierarchies instead of flat topics |
| Subscription drift | Consumers receiving unintended messages | Use filter policies; audit subscriptions regularly |
| Ordering violations | Processing order differs from publish order | Serialize work by entity and check the broker’s documented ordering scope |
| Poison message blocking | Failed messages block subscriber | Configure dead letter queues; set retry limits with exponential backoff |
Common Pitfalls / Anti-Patterns
Common Pitfalls
Even experienced teams make the same mistakes when adopting pub/sub. These anti-patterns show up in production repeatedly — topic sprawl that overwhelms the broker, treating asynchronous messaging like synchronous RPC, ignoring what happens when subscribers go offline, and forgetting about poison messages that silently pile up. Watch for these during design reviews and post-incident analysis.
Pitfall 1: Topic Proliferation
Creating too many topics (one per event type) leads to management overhead and broker resource exhaustion. Use hierarchical topics to group related events and apply naming policies.
Pitfall 2: Treating Pub/Sub as Synchronous Communication
Pub/sub is inherently asynchronous. If you need synchronous request/response, do not use topics. Clients must be designed to handle out-of-order, asynchronous responses.
Pitfall 3: Forgetting That Subscribers Can Go Offline
If a broker does not retain messages for a subscription, downtime can mean loss. Check the broker’s persistence and retention settings for the subscription or queue.
Pitfall 4: Not Designing for Message Replay
An acknowledged RabbitMQ queue message is removed and cannot be replayed from that queue. If consumers need to reread history, choose a retained log such as RabbitMQ Streams and plan for its retention window.
Pitfall 5: Over-Filtering at the Publisher
When publishers classify messages for subscribers, they become coupled to subscriber requirements. Push filtering to subscribers and keep publishers unaware of subscriber specifics.
Pitfall 6: Ignoring Dead Letter Queue Accumulation
If DLQs are accumulating, something is wrong with message processing. Monitor DLQ depth and investigate root causes promptly.
Observability Checklist
Track pub/sub health per topic and subscription. A healthy broker can still hide a subscriber that has stopped making progress, so compare published, delivered, and acknowledged messages rather than watching broker uptime alone.
- Measure publish, delivery, and acknowledgment rates for each subscription.
- Track subscriber lag as both message distance and the age of the oldest unprocessed event where the broker supports it.
- Count delivery failures, retries, redeliveries, and dead letter queue arrivals; break them down by subscription.
- Record filter match and discard rates so a changed policy does not silently stop useful deliveries.
- Monitor active connections, consumer rebalances, broker capacity, and publish-to-delivery latency.
- Put a trace or correlation ID on each event and carry it through consumer logs. Log topic and subscription metadata, not message bodies or secrets.
- Alert on lag against each consumer’s service objective, sustained delivery failures, unusual publish-rate changes, and growing dead letter queues.
Avoid using an unbounded tenant ID as a metrics label. Keep per-tenant diagnosis in access-controlled logs or traces, and use bounded dimensions for fleet-wide dashboards.
Security and Compliance Notes
Treat topic access as a data boundary. Authenticate publishers, subscribers, and administrators, then grant each identity only the actions and topics it needs. A service in one tenant should not be able to publish to or subscribe to another tenant’s topics, even when wildcard subscriptions or content filters are available.
- Enforce topic-level publish, subscribe, and administration permissions; review wildcard patterns and filter expressions server-side.
- Separate tenant topics or enforce tenant identity in broker authorization rules. Do not rely on a client-supplied tenant header alone.
- Put only routing metadata in topic names and headers. Keep personal data, credentials, and payment details out of them.
- Minimize event payloads. Use an authorized reference to fetch sensitive data when subscribers do not all need the full record.
- Encrypt broker connections and stored messages. Use field-level encryption when broker operators or unrelated subscribers must not read particular fields.
- Validate event schemas and size limits before accepting messages; treat payloads and filter values as untrusted input.
- Keep payloads out of logs, traces, and dead letter queue dashboards. Redact sensitive fields before recording failure details.
- Restrict and audit topic creation, subscription changes, replay access, and dead letter queue inspection. Set retention and deletion rules for stored messages.
For regulated data, map each topic and subscription to its data classification, retention period, and authorized consumers before enabling broad fan-out.
Quick Recap Checklist
- Use a documented topic naming scheme that groups related events without creating unnecessary topics.
- Configure the broker’s durable storage and retention for consumers that must catch up after downtime.
- Use the broker’s competing-consumer or shared-subscription model when instances should divide the work.
- For at-least-once delivery, expect possible duplicates and make message processing idempotent.
- Set retry limits and route messages that keep failing to a monitored dead letter queue.
- Track subscriber lag, delivery failures, and dead letter queue depth.
Interview Questions
Expected answer points:
- Subject-based routing uses predefined topic strings; subscribers choose which topics to listen to
- Content-based routing evaluates message body attributes; subscribers define filter conditions on message content
- Content-based routing is more flexible but harder to implement efficiently and raises security concerns
Expected answer points:
- Durability is implemented differently by each broker.
- In RabbitMQ, use a durable queue and persistent publications; publisher confirms show that a publication was accepted.
- Retention limits and expiration policies still determine how long a message remains available.
Expected answer points:
- A configured dead-letter route can capture messages rejected after the retry policy is exhausted.
- In RabbitMQ, rejecting with
requeue=falseroutes to a configured dead-letter exchange; without one, the message is discarded. - Monitor the destination and redrive only after correcting the failure cause.
Expected answer points:
- Broadcast fan-out delivers every message to every subscriber; broker makes copies
- Selective fan-out uses filtering so only matching subscribers receive the message
- Selective fan-out is more efficient but requires broker to evaluate filters
- Cost scales with subscriber count in broadcast; less so in selective
Expected answer points:
- Bind a separate queue for each subscriber that must receive its own copy of an event.
- Attach multiple consumers to one queue when they should compete to process its messages.
- These are RabbitMQ queue patterns; other brokers use their own subscription terms.
Expected answer points:
- Backpressure prevents system collapse when subscribers cannot keep up with message throughput
- Without it, consumers run out of memory or broker queues grow without bound
- Buffer-based approaches accumulate messages locally up to a limit
- Flow control signals let subscribers push back on publishers to slow things down
- Should propagate upward, not accumulate silently
Expected answer points:
- At-most-once can lose work if it is acknowledged before the side effect completes.
- At-least-once can redeliver after a crash or lost acknowledgment, so side effects should be idempotent.
- Exactly-once claims apply only to the specific broker feature and transaction boundary documented by that product.
- An external database update or API call can still repeat unless the consumer makes it idempotent.
Expected answer points:
- Multiple consumers on one queue compete to process its deliveries.
- Separate queues bound to the exchange give independent subscribers their own copies.
- With competing consumers, completion order may differ from delivery order.
Expected answer points:
- Topic message rate (messages published per second per topic)
- Subscription delivery rate (messages delivered per second per subscription)
- Subscriber lag (time between publish and delivery)
- Dead letter queue depth (failed messages waiting to be inspected)
- Filter match rate (percentage of messages matching subscriber filters)
- Connection count (active publishers and subscribers per topic)
Expected answer points:
- Broker failure: Deploy broker clusters with replication; use multiple broker endpoints
- Subscriber crash during processing: Use manual acknowledgment; configure prefetch limits
- Message explosion (too many subscribers): Limit subscription count; use content filtering
- Topic explosion (too many topics): Implement naming policies; use topic hierarchies
- Ordering violations: Serialize work for the affected entity and use the broker's documented ordering scope.
- Poison message blocking: Configure dead letter queues; set retry limits with exponential backoff
Expected answer points:
- SNS filter policies use JSON rules that match message attributes by default.
- Set the subscription's
FilterPolicyScopetoMessageBodyto match JSON body properties. - The policy format is broker-defined, not arbitrary SQL.
Expected answer points:
- Pub/sub is often the messaging backbone for event-driven architecture
- In EDA, topics carry domain events between services that react to those events
- Pub/sub provides the decoupled, asynchronous communication that EDA requires
- Services do not call each other directly; they subscribe to topics and react to events
- This separation allows services to evolve independently without tight coupling
Expected answer points:
- Flat topics are simple but require explicit subscriptions for each topic
- Hierarchical topics enable broad subscriptions using wildcard patterns (e.g., orders/*)
- Hierarchies reduce coupling between publishers and subscribers
- The tradeoff is naming discipline—without conventions, hierarchies become messy
- Hierarchies work well when there is a natural domain tree; flat works when topics are independent
Expected answer points:
- At-least-once delivery can duplicate messages; idempotent processing handles duplicates
- Idempotent processing means processing a message multiple times has the same effect as once
- Record processed message IDs with a unique constraint in the same transaction as the state change.
- A Bloom filter can report false positives, so it should not be the authority for dropping messages.
- Design retries around the broker's delivery behavior and make side effects idempotent.
Expected answer points:
- Pub/sub does not guarantee ordering across topics or publishers
- A correlation ID groups messages from one operation; it does not establish their order.
- Use sequence numbers or timestamps with a defined ordering rule if consumers must detect gaps.
- For ordered processing, choose a broker topology that serializes work for each entity.
- Check the selected broker's behavior for competing consumers and redelivery.
Expected answer points:
- Buffer-based approaches accumulate messages locally in a ring buffer up to capacity
- When buffer fills, the subscriber must drop messages, pause consumption, or signal the broker
- Flow control signals let subscribers push back on publishers to slow production
- RabbitMQ uses basic.qos with prefetch to limit unacknowledged messages
- Kafka has consumer group rebalance hooks for similar backpressure behavior
- Backpressure should propagate upward, not accumulate silently
Expected answer points:
- Authentication: Require credentials for publishers and subscribers; use mutual TLS
- Authorization: Implement topic-level access controls; restrict who can publish to which topics
- Encryption in transit: Enable TLS for all broker connections
- Encryption at rest: Enable disk encryption if broker stores messages
- Message-level security: Validate message schemas; sanitize content to prevent injection
- Subscription security: Prevent unauthorized subscription creation
Expected answer points:
- Workers compete for deliveries from that queue; separate subscriber queues are needed for broadcast copies.
- Completion order may change when workers run concurrently or messages are retried.
- Use a serialized consumer path when per-entity processing order matters.
Expected answer points:
- Exponential backoff increases retry delays progressively after transient failures
- Starting delay doubles or triples after each failed attempt up to a maximum
- Prevents message pileup from repeated processing failures creating backlog
- Example: retry_delay starts at 1000ms, doubles each attempt, caps at max_delay
- Keeps the system responsive while failed messages are retried at sustainable rate
Expected answer points:
- Topic message rate: Messages published per second per topic
- Subscription delivery rate: Messages delivered per second per subscription
- Subscriber lag: Time between message publish and delivery to subscribers
- Dead letter queue depth: Failed messages awaiting inspection
- Filter match rate: Percentage of published messages matching subscriber filters
- Connection count: Active publishers and subscribers per topic
- Alerts should trigger when DLQ depth exceeds threshold or delivery failures exceed rate
Further Reading
- Event-Driven Architecture - Companion pattern for building event-driven systems
- Message Queue Types - Understanding where pub/sub fits in the broader messaging landscape
- Exactly-Once Delivery - Scope and limits of delivery guarantees
- Amazon SNS message filtering - AWS’s filter policy reference
- RabbitMQ Routing Topics - RabbitMQ’s official tutorial on topic routing patterns
Conclusion
Publish/subscribe lets one publisher send an event to several independent subscribers through a topic. Topic structure, broker-specific persistence, and filtering determine who receives each message and what happens when consumers go offline. Check the chosen broker’s delivery contract, make side effects safe to retry, and monitor retries and dead-letter traffic. Pub/sub fits when the publisher can continue without waiting for each subscriber.
Pre-Deployment Checklist
- [ ] Topic naming convention documented and enforced
- [ ] Broker persistence and retention configured for critical subscribers
- [ ] Dead letter queues configured with monitoring
- [ ] Filter policies documented per subscription
- [ ] Manual acknowledgment implemented in consumers
- [ ] Idempotent message processing implemented
- [ ] Retry limits set with exponential backoff
- [ ] TLS/encryption enabled for all connections
- [ ] Topic-level access controls configured
- [ ] Alert thresholds set for DLQ depth and delivery failures
- [ ] Competing-consumer or shared-subscription scaling strategy defined for the chosen broker
- [ ] Correlation ID propagation implemented for distributed tracing
Category
Related Posts
CQRS Pattern
Decide whether separate command and query models solve a real problem, how to begin in one store, and when a read model can tolerate lag.
Event Sourcing
Storing state changes as immutable events. Event store implementation, event replay, schema evolution, and comparison with traditional CRUD approaches.
Message Queue Types: Point-to-Point vs Publish-Subscribe
Understand the two fundamental messaging patterns - point-to-point and publish-subscribe - and when to use each, including JMS, AMQP, and MQTT protocols.