Module 2 · Backend architectureLesson 18 of 887 minIntermediate
Event-driven architecture
Instead of calling every service that cares, a service announces what happened and lets others react.
Publish an event and watch three services get their own copy. Then take the email service down and see its copy wait until it's back.
In a request-driven system, checkout calls email, then inventory, then analytics, then loyalty points. Each new feature means changing checkout, and if any of them is slow or down, checkout suffers.
In an event-driven system, checkout publishes one event, OrderPlaced, to an event bus. Every service that cares subscribes and reacts on its own.
Queue vs publish/subscribe
- In a queue, each message goes to one worker. Great for sharing out work.
- In pub/sub, each event goes to every subscriber group. Great for "tell everyone who cares".
Kafka topics, Google Pub/Sub, SNS and RabbitMQ exchanges all support the pub/sub pattern.
Benefits
- Loose coupling: publishers and subscribers can be built, deployed and scaled separately.
- Resilience: if email is down, events wait for it; checkout doesn't fail.
- Easy to extend: new features subscribe to existing events.
- History: with a durable log like Kafka, you can replay old events into a new service.
Costs
- Eventual consistency: the email is sent a moment after the order, not at the same instant.
- Harder to follow: there's no single function that shows the whole flow. You need tracing and good documentation of events.
- Duplicates and ordering: events can arrive twice or out of order, so subscribers must handle that.
Naming events well
Name events as facts in the past tense (PaymentFailed), not commands (SendEmail). A fact lets each subscriber decide what to do; a command quietly couples the publisher to one receiver again.