Events vs commands, producers and consumers, and at-least-once delivery for decoupled systems.
Events vs commands, producers and consumers, and at-least-once delivery for decoupled systems.
Lesson outline
A command is a request to do something ("CreateOrder", "SendEmail"). The sender expects a direct response. An event is something that happened ("OrderCreated", "PaymentReceived"). The publisher does not know who consumes it; subscribers react. Events decouple services: the order service publishes OrderCreated; inventory, email, and analytics subscribe independently.
Events are usually immutable (facts) and timestamped. Store them in a log or stream so new consumers can replay history.
Producers publish events to a message broker or event stream (e.g. Kafka, RabbitMQ, SQS). Consumers subscribe to topics or queues and process events. The broker handles delivery, retention, and (in Kafka) partitioning. Multiple consumers can read the same stream (competing or fan-out).
Design consumers to be idempotent: the same event may be delivered more than once (at-least-once). Use a deduplication key (event ID) and skip or overwrite if already processed.
At-least-once: the broker may redeliver until the consumer acknowledges. Simple and common; consumers must handle duplicates. Exactly-once is harder: it requires idempotent producers, transactional commits, and idempotent consumers (or a single transactional sink). Many systems aim for at-least-once and rely on idempotency.
Ordering: within a partition (e.g. by user_id), Kafka preserves order. Use partition keys so related events go to the same partition when order matters.
Use events when: multiple systems need to react to the same occurrence; you want to add new consumers without changing producers; or you need replay (e.g. rebuild state, backfill). Use commands (sync or async RPC) when you need a direct response or strong consistency with one service.
Ready to see how this works in the cloud?
Switch to Career Paths for structured paths (e.g. Developer, DevOps) and provider-specific lessons.
View role-based pathsSign in to track your progress and mark lessons complete.
Questions? Discuss in the community or start a thread below.
Join DiscordSign in to start or join a thread.