Event Driven Architecture vs Pub Sub: Core Differences
I used to treat event driven architecture vs pub sub as interchangeable terms. They are not. Pub sub is a messaging pattern. Event driven architecture is a system design philosophy where events represent immutable facts that drive state changes across service boundaries. If you are wiring services together with a message broker, you are doing pub sub. If those messages represent domain events that other services react to without the producer knowing who consumes them, you are doing event driven architecture.
What is the core conceptual difference?
The coupling model is the dividing line. In pub sub the publisher knows a topic exists and may even know the schema consumers expect. The coupling is loose but intentional. In event driven architecture the producer emits a domain event like OrderPlaced or PaymentFailed with zero knowledge of downstream consumers. The event is a fact, not a command. This distinction matters because it changes how you version schemas, how you handle failures, and how you reason about system behavior at 3 AM.
I learned this the hard way when a notification service started sending welcome emails before the user record was visible in the read replica. The publisher assumed immediate consistency. The consumer did not. Event driven architecture forces you to design for eventual consistency from day one. Pub sub lets you pretend otherwise until it breaks.
When to choose event driven architecture over pub sub
Choose event driven architecture when you have multiple bounded contexts that need to react to the same business fact. An order placement triggers inventory reservation, payment authorization, warehouse notification, and analytics enrichment. None of these services should call each other directly. They should each subscribe to OrderPlaced and act independently.
Choose pub sub when you need simple work distribution or fan-out without domain semantics. A video processing pipeline where workers pull VideoUploaded tasks from a queue is pub sub. The uploader knows workers exist. The workers know the uploader exists. There is no domain event, just a job ticket.
Do not reach for event driven architecture if you have three services and a monolith. The operational overhead of schema registry, dead letter queues, replay tooling, and distributed tracing is real. I have seen teams spend six months building event infrastructure for a system that would have been fine with synchronous REST and a background job queue. See my breakdown on Event Driven Architecture vs Request Response: Trade-offs for the decision matrix I use.
Implementation patterns with Redis Streams vs Kafka vs RabbitMQ
The broker shapes what is practical. Redis Streams gives you consumer groups, blocking reads, and automatic acknowledgment with XREADGROUP. It is excellent for moderate throughput where you want Redis operational simplicity. Here is a minimal producer in Python:
import redisimport json
r = redis.Redis(decode_responses=True)
def emit_order_placed(order_id: str, payload: dict): event = { "event_type": "OrderPlaced", "event_id": str(uuid.uuid4()), "timestamp": datetime.utcnow().isoformat(), "payload": payload } r.xadd("orders:events", event, maxlen=100000, approximate=True)Kafka gives you log retention, partitioning by key, and exactly-once semantics with transactional producers. It is the right choice when you need event replay, audit logs, or throughput above 100k events per second. The operational cost is higher. You need ZooKeeper or KRaft, partition leadership awareness, and capacity planning for disk retention.
RabbitMQ gives you flexible routing with exchanges, TTL, dead letter exchanges, and priority queues. It shines when you need complex routing logic like “route payment events to the fraud service only for amounts over $10k.” The trade-off is that RabbitMQ queues are not logs. You cannot replay from an arbitrary offset without a plugin.
I run Kafka for the event backbone and RabbitMQ for command-style workloads that need routing. Redis Streams handles idempotency keys and rate limiting. Each tool does one thing well.
How do you handle ordering guarantees and exactly-once delivery
True exactly-once delivery does not exist in distributed systems. You get at-least-once delivery with idempotent consumers. Design your consumers to be idempotent by tracking processed event IDs in a deduplication store. Redis with TTL works for short windows. PostgreSQL with a unique constraint on event_id works for durable deduplication.
async def handle_order_placed(event: dict, db: AsyncSession): event_id = event["event_id"] try: await db.execute( text("INSERT INTO processed_events (event_id) VALUES (:eid)"), {"eid": event_id} ) await db.commit() except IntegrityError: return # already processed
# safe to apply business logic await reserve_inventory(event["payload"])Ordering is only guaranteed within a partition or shard key. If you need OrderPlaced before OrderShipped for the same order, partition by order_id. If you partition by customer_id, those events can arrive out of order. I have debugged too many race conditions caused by assuming global ordering. Partition by the entity that requires ordering.
Observability and debugging strategies for async flows
You cannot debug async flows with logs alone. You need distributed tracing with a correlation ID that flows through every service. OpenTelemetry is the standard. Inject the traceparent header into every message header. Here is a FastAPI middleware that extracts and propagates context:
from opentelemetry import tracefrom opentelemetry.propagate import inject, extract
@app.middleware("http")async def tracing_middleware(request: Request, call_next): ctx = extract(request.headers) with trace.get_tracer(__name__).start_as_current_span( request.url.path, context=ctx ) as span: inject(request.headers) response = await call_next(request) return responseFor message consumers, extract context from message headers before processing. Log the trace ID and span ID in every structured log line. When something breaks you can query your trace backend for the full causal chain.
I also emit a EventProcessed log with event_id, consumer, duration_ms, and status. This lets me build dashboards for end-to-end latency per event type. Alert on p99 latency exceeding your SLA, not on queue depth. Queue depth is a symptom. Latency is the disease.
Migration path from synchronous REST to event-driven
Do not rewrite. Strangle. Identify one write path that causes cascading latency or coupling. Extract the side effects into an event handler. Keep the synchronous response for the caller. Emit the event after the primary write commits.
Step one: add an outbox table in the same transaction as your domain write.
CREATE TABLE outbox ( id UUID PRIMARY KEY, event_type TEXT NOT NULL, payload JSONB NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW());Step two: a relay process polls the outbox and publishes to Kafka. This guarantees at-least-once delivery without dual-write problems. Step three: migrate consumers one at a time. Run the old synchronous call and the new event handler in parallel. Compare results. Cut over when they match.
I used this pattern to migrate a payment service that called fraud, ledger, and notification synchronously. The migration took three months with zero downtime. The key was keeping the synchronous contract intact while building the async path in shadow mode. For more on this transition see Event-Driven Architecture vs Microservices: How to Choose.
FAQ
Is pub sub a subset of event driven architecture? Pub sub is a messaging mechanism. Event driven architecture is an architectural style that often uses pub sub as transport. You can have pub sub without event driven architecture. You cannot have event driven architecture without some form of event transport.
Can I use Redis Streams for event sourcing? You can but I would not recommend it for the event store. Redis Streams lacks the durable ordering guarantees and retention policies of Kafka or EventStoreDB. Use Redis for caching, idempotency keys, and transient streams. Use a log-based broker for the system of record.
How do I version events in event driven architecture? Include a version field in the event envelope. Consumers handle multiple versions. Never mutate an existing event type. Add new optional fields. Deprecate old versions only after all consumers migrate. Schema registry tools like Confluent Schema Registry or Karapace enforce this.
What is the biggest mistake teams make?
Treating events as commands. An event says “this happened.” A command says “do this.” If your event is named SendWelcomeEmail you are coupling the producer to the consumer. Name it UserRegistered and let the notification service decide what to do.
Key Takeaways
- Pub sub is a transport pattern. Event driven architecture is a design philosophy centered on immutable domain events.
- Choose event driven architecture when multiple bounded contexts react to the same business fact. Choose pub sub for work distribution.
- Kafka for the event backbone. RabbitMQ for complex routing. Redis Streams for lightweight consumer groups.
- Exactly-once is a myth. Build idempotent consumers with deduplication stores.
- Distributed tracing with correlation IDs is non-negotiable for debugging.
- Migrate with the outbox pattern. Strangle the synchronous calls one write path at a time.
Working on something similar?
If you're building backend or AI systems and want a second set of senior eyes, let's talk.