This blog is part of the Architecting a System series, where we are breaking down what all goes behind designing and building a system.
The previous part covered communication and flow design — synchronous and asynchronous processing, polling, WebSockets, Server-Sent Events, push notifications, and webhooks.
In this part, we look at what sits between components. We will cover queues, pub-sub, logs, what a buffer does and does not protect you from, event-driven design, Kafka, and stream processing.
Introduction
Every mechanism in the previous part connected two things directly. The user polled your endpoint, your server pushed down a socket, your service POSTed to somebody's callback URL. Both ends had to be there at the same time.
That assumption breaks in two ways.
The first is rate. Your users send so many requests, or so much data, that the components behind them cannot keep up. Whenever producers produce faster than consumers consume, you need someplace to put the difference.
The second is availability. The component you are passing data to can be down, restarting, or mid-deploy at the exact moment you have something to give it. A five-second deploy should not mean that data moving internally vanishes into thin air. The consumer here is not slow. It is absent. The producer has something to pass on and nothing to pass it to.
Two different problems, one shape of solution. Keep them apart — the rest of this post keeps pointing back to which one is in play.
Both are solved by putting something in the middle: a holding area, which gets you one or both of these.
- Decoupling in time. The producer and the consumer do not have to be available at the same moment.
- Decoupling in knowledge. The producer does not have to know who the consumers are, or how many of them there are.
What that something is, and what it gives you, depends on its shape.
Three Shapes: Queue, Pub-Sub, Log
Almost everything in this blog is one of three shapes.
A queue distributes each message to one consumer at a time. Once that consumer acknowledges it, the message is deleted. Add more consumers and you get more throughput, because they are dividing the work between themselves. This is work distribution.

A pub-sub topic delivers each message to every subscriber. Each subscriber gets its own delivery of the message. Nothing is divided. This is fan-out.

A log holds an ordered sequence of records and retains them for a configured period, whether or not anyone has read them. Consumers do not remove records; they track their own position, an offset, and move it forward as they read. Two consumers can sit at different offsets on the same log and neither affects the other.

In a queue, a processed message is gone. In a log, it is still there, and a consumer can move its offset backwards and read it again.
Apache Kafka
Kafka is the most widely used system for high-throughput event streaming. Durability and availability both come from replicating partitions across brokers.
Simply put, you have:
- Brokers: machines running Kafka
- Topics: logical categories in which records are stored
- Partitions: ordered subdivisions of a topic, replicated across brokers
- Records: binary data written to a partition in order
At any given time, a partition has one leader replica and one or more follower replicas. Producers write to the leader, and the followers replicate its data.
In newer Kafka deployments using KRaft, cluster metadata and controller elections are managed without requiring a separate supervisor such as ZooKeeper.
Producers use cluster metadata to determine the leader for a partition and write records to it. Consumers, organised into consumer groups, then consume those records. The figure below shows a two-broker cluster where each broker leads one partition of the same topic and holds a replica of the other.

In the above example, we have a Users topic and two brokers with two partitions. In this example, the partition is determined by the first letter of the user's name: A-M maps to one partition and N-Z to another. Broker 1 is the leader for A-M and Broker 2 is the leader for N-Z, with each partition replicated to the other broker. Therefore, a producer wanting to write Susmit will send the record to Broker 2, which is the leader for the N-Z partition. The record is then replicated to Broker 1. With acks=all, the leader acknowledges the write only after all currently in-sync replicas have acknowledged it. min.insync.replicas sets the minimum number of in-sync replicas required for the write to be accepted.
Records survive being read. Retention depends upon time and size policy, not on consumption. A new consumer group can start at the beginning of a topic and process everything that is still retained, which is how you backfill a new service or reprocess after fixing a bug in a consumer.
A partition is assigned to one consumer within a group at a time. This is what makes a consumer group behave like a queue: records are distributed across the consumers rather than each consumer receiving every record. Multiple consumer groups can independently read the same partitions, which gives you fan-out. It is also a hard ceiling. Eight consumers in a single consumer group on a three-partition topic means five of them sit idle, holding no assignment and doing nothing.

Membership changes cost you. When a consumer joins, leaves, or fails a heartbeat, the group rebalances and partition assignments move. Processing pauses while that happens. A consumer with a long poll interval that occasionally exceeds its timeout will be treated as dead and trigger a rebalance, which is a fun one to debug because the consumer is visibly alive in its own logs.
Durability is a dial, not a setting. The producer's acks decides when a write is considered successful: acks=0 does not wait, acks=1 waits for the leader only, and acks=all waits for every in-sync replica. acks=1 will lose data if the leader fails before its followers have caught up. Pair acks=all with min.insync.replicas on the broker, which sets how many replicas must be in sync for a write to be accepted at all. The common configuration is three replicas with min.insync.replicas=2, which tolerates losing one broker while still refusing writes it cannot make durable.
Buffering and Fault Tolerance
Take the absent-consumer case. A job worker reports its progress to the backend through an API, the backend is down, and the status update is simply lost.

Instead, the job worker can emit a message to a queue.
- The backend can consume the message when it is available.
- For low-throughput use cases, a serverless function can consume the message and make the API call.
- The message is removed from the queue only after successful processing, so a temporary failure means a retry rather than a loss.
In the fan-out case, the worker emits a status that you want to deliver to several listeners, but you do not want it calling five different APIs.

The worker publishes to a pub-sub topic. Five subscribers listen to that topic and process the message independently. The worker does not know they exist, and adding a sixth does not require touching it.
You can also buffer locally in an intermediary, either as files or in something such as Redis, before sending it forward as a batch. This is worth doing when the downstream cost is per-call rather than per-byte.
Event Payload Design
An event travels the same chain every time: something happens, state changes, a record is written, it is filtered and routed, and a consumer reacts. What shapes everything downstream is how much you put in that record.

The trigger does not have to be a user action or a message in a queue. Cron jobs fit the same lens: they react to time itself, and a scheduled tick of the clock is the event that starts the chain.
Notification or State
An event has to carry something, either the data itself or a pointer to it.
A notification carries an identifier and a type, and nothing else.
{ "type": "OrderPlaced", "orderId": "ord_8813", "at": "2026-08-26T15:04:11Z" }Small and cheap, and it does not contain a stale snapshot because it carries no state beyond the identifier and event metadata. But every consumer that needs to do anything now calls back to the order service. Five consumers means five calls per event, and you have recoupled them to the producer you were trying to decouple from, this time on the read path.
Event-carried state transfer puts the state in the event.
{
"type": "OrderPlaced",
"orderId": "ord_8813",
"customerId": "cus_2210",
"total": 4599,
"currency": "INR",
"items": [ ... ]
}Consumers can act without calling anyone. The producer can be down and they keep working. What you have given up is that the event is a snapshot from the moment it was published, so a consumer processing it two minutes later is acting on two-minute-old state, and if the order has been amended since then the consumer does not know.
It also means your event now exposes the shape of your data, which is the next problem.
Event Schemas Are Contracts
Once consumers depend on an event, changing its schema becomes a compatibility problem.
Renaming a field breaks every consumer reading it. Removing one breaks the ones using it, and you may not know which those are. Even a type change — an integer amount becoming a decimal string — breaks deserialisation on consumers that were working fine yesterday.
Some rules to keep in mind so everyone stays sane:
- Add fields, never rename or remove them.
- New fields must be optional, because old consumers will not send them and old events will not have them.
- Version the event type when you genuinely need a breaking change, and publish both for a while, the same way you would overlap a rotating secret.
- Use a schema registry if the number of event types is more than you can keep in your head.
Correctness Under Retry
Retries are not an incident. They are normal operation.
The Dual Write Problem
The queue example earlier was the easy version, because the worker only had one thing to do. The harder version, and the one you will actually run into, is when it has two.
You need to update your database and publish an event. Both must happen.

These are two separate systems and there is no transaction spanning them. So there are two ways for this to go wrong.
The save succeeds and the publish fails. Your database has an order that nobody downstream knows about.
The publish succeeds and the save fails, or the process dies between the two lines. Downstream systems act on an order that does not exist.
Neither of these is exotic. A process restart at the wrong instant is enough.
The fix is to stop treating the event as a second write. Write it into a table in the same transaction as the business data.
BEGIN
INSERT INTO orders ...
INSERT INTO outbox (id, type, payload) ...
COMMITNow there is one atomic write, and either both rows are there or neither is. A separate process then reads unpublished rows from the outbox table, publishes them, and marks them done.

That relay can be something you write, or it can be change data capture reading the database log directly. Debezium does this for Postgres, MySQL and others. On DynamoDB, DynamoDB Streams gives you the same thing without a separate component.
Note that the outbox does not give you exactly-once delivery. The relay can publish a row and die before marking it done, and then publish it again. What it gives you is that the event and the state it describes can never disagree, which is the part that is hard to recover from.
At-Least-Once Is the Default
The reason duplicates are unavoidable is that acknowledgement is itself a network call.
A consumer processes a message and sends an ack. The ack is lost. From the broker's point of view nothing happened, so it delivers the message again. There is no way for the broker to distinguish a consumer that never processed the message from one that processed it and could not say so.
You cannot fix this at the transport layer. You handle it at the consumer, by making processing idempotent.
If the same message is produced once but processed twice, it should not cause an issue. Practically, that means deriving a deduplication key from the message rather than from the delivery, storing the keys you have handled, and dropping repeats. A unique constraint on that key, combined with the business update in the same database transaction, is often enough.
Visibility Timeouts and Slow Consumers
Queues do not delete a message when it is picked up, because the consumer might die. They hide it for a while instead.
SQS calls this the visibility timeout and it defaults to 30 seconds. The consumer receives the message, the message becomes invisible to other consumers, and if no delete arrives within the window it becomes visible again.
If your consumer is slower than the visibility timeout, the message can get picked up by another consumer while the initial consumer which picked it up is still processing it.
So the visibility timeout has to be set from the tail of your processing time, not the average, and if processing time is genuinely unbounded, the consumer should be extending the timeout as it goes rather than hoping.
Poison Messages
A message that fails will be retried. A message that fails deterministically will be retried forever.
One malformed payload, one row that violates a constraint, and that message cycles: delivered, fails, becomes visible, delivered again. It occupies consumer capacity indefinitely and it is at the head of the queue, so on a FIFO queue it blocks everything behind it.
The mechanism for this is a redrive policy. After N receives, the broker moves the message to a dead-letter queue instead of making it visible again.
DLQ needs an alarm. A DLQ nobody looks at is a folder where data goes to be forgotten.
And It needs a way back. Once you have fixed the bug, you need to move those messages into the main queue and process them. SQS has redrive for exactly this. If you are building on something that does not, you are writing that tool yourself, and it is better to write it before you need it.
Ordering Costs Parallelism
Global ordering and parallel consumption are fundamentally at odds in a distributed queue. Two consumers pulling from one queue will finish at different times regardless of the order they started in.
SQS standard queues make no ordering promise at all. SQS FIFO queues order messages within a message group ID, and messages in different groups are independent. Kafka orders records within a partition, and a record's partition is determined by its key.
Both are the same idea. You pick something to order by, usually an entity id, and you get ordering for that entity and nothing more.
And that choice sets your parallelism ceiling. If every message carries the same group ID or partition key, you have ordered everything and reduced yourself to one consumer. Use the smallest entity ID that actually requires ordering. If ordering is required per order, use order ID; if it is required per customer, use customer ID.
Where At-Most-Once Comes From
Kafka is the clearest place to see the two guarantees split, because the consumer decides.
A Kafka consumer reads records and separately commits its offset. Those are two operations and their order is your choice.
Commit the offset, then process:
records = consumer.poll()
consumer.commit()
process(records) # crash hereThe offset says these records are done. They are not. On restart the consumer resumes past them and they are never processed. That is at-most-once, and the loss is silent.
Process, then commit:
records = consumer.poll()
process(records)
consumer.commit() # crash hereThe records were processed but the offset was not moved. On restart the consumer reads them again. That is at-least-once, and it is why you needed the idempotency above.
Both are two lines of code and the difference between them is which failure you would rather have. Almost always the answer is the duplicate, because you can deduplicate a duplicate and you cannot recover a record you never knew you dropped.
What the Buffer Absorbs
A buffer absorbs a burst. It does not absorb a deficit.
Say your producers are emitting 1,000 events per second and your consumers can drain 500. The rate mismatch is 500 events per second.

For the first minute this looks like a healthy system. The holding area is 30,000 events deep and rising, latency is up a bit, nothing is failing. Nothing will fail for a while. But it is not absorbing that 500 per second, it is accumulating it, at 1.8 million events per hour, and there is no point in the future at which that reverses on its own.
A burst is different in one specific way: the arrival rate goes back below the drain rate. Depth rises, then falls, then hits zero. The buffer did its job and you never heard about it.
Under a sustained deficit, what you have is a fuse. Which end it burns from depends on what you are running.
Retention-based systems can lose the oldest records. Kafka retains records for a configured period, seven days by default. If a consumer falls far enough behind that its committed offset has been deleted, the requested offset is no longer available. What happens next depends on the consumer's auto.offset.reset policy: it may restart from the earliest available offset, jump to the latest, or fail. Either way, records that expired from the log are gone.
Depth-limited systems reject the newest. Queues with a maximum depth, or a broker out of disk, start refusing writes. Your producers get errors, which sounds worse and is actually better, because the failure is loud and it lands on the side that can slow down.
Stream Processing
When data is being produced continuously, storing every record and processing it much later may not be sufficient. You may need to process the data while it is flowing through the system. First, two concepts related to time, because time is fundamental to stream processing.
Event Time and Watermarks
Every record has two timestamps: when the thing happened (event time), and when your system got to it (processing time).
For a mobile client that went through a tunnel, those can be twenty minutes apart. Aggregate by processing time and you are counting the tunnel, not the users, which is why any windowed computation worth trusting works on event time.
Which raises the problem. If you are counting events in the 10:00 to 10:05 window, when do you emit the result? There is no end of stream. Waiting forever is correct and useless.
A watermark is the answer. It is an assertion the pipeline makes: I do not expect to see any more events with an event time before T. When the watermark passes 10:05, the 10:00 to 10:05 window closes and emits.
The watermark is a heuristic, usually derived from the maximum event time seen so far minus a fixed tolerance. Set the tolerance at 10 seconds and you emit quickly, but events that arrive after the watermark has passed are handled as late. Whether they are dropped, routed elsewhere, or incorporated into a correction depends on the processing framework and its lateness configuration. Set it at 10 minutes and you catch stragglers but every result is 10 minutes old. There is no correct value, only the trade between latency and completeness, and it is the single most consequential number in a streaming pipeline.

Kafka Streams
Kafka Streams is a JVM library. There is no cluster and no submission step; you add it as a dependency, write your topology, and run it as an ordinary application that you deploy and scale like any other service.
Instances of your application coordinate through a Kafka consumer group, so scaling is the same story as before and bounded by partition count. State is kept in a local store, backed by a changelog topic in Kafka, which is how an instance recovers state after a restart.
ksqlDB
ksqlDB puts SQL in front of that. You run a ksqlDB server, submit SQL statements, and it turns them into streaming computations.
The important thing to know is what it compiles to. Every ksqlDB query becomes a Kafka Streams topology running on the Kafka Streams runtime inside the ksqlDB server. It is not a separate engine, which is what explains its shape: Kafka-only, partition-bound, and scaling on exactly the same terms as the previous section.
Apache Flink
When you need a dedicated cluster, multiple sources and sinks, complex event processing, and a robust state-checkpointing mechanism, Apache Flink is well suited to the task. It is a stream-processing engine designed for stateful computations over bounded and unbounded data streams, and unlike the two above it is not tied to Kafka on either end.
Here is a simplified view of how a job runs.
You write a Flink job in Python, Java or Scala, or as Flink SQL. You submit it to the cluster's job manager, which splits the job into tasks and allocates them to task slots within the task managers. State is checkpointed periodically so that a failure restores from the last checkpoint rather than from the beginning.
It can ingest from event streams such as Kafka, perform interval joins if necessary, aggregate over a window, and write results to downstream sinks.
Here are different types of windows:
- Tumbling: fixed size, no overlap. Every event lands in exactly one window.
- Session: no fixed size. The window closes after a configured gap of inactivity, which makes it useful for anything shaped like a user visit.
- Sliding: fixed size, advancing at a configured time interval. If the slide is smaller than the window size, windows overlap and an event can belong to multiple windows. For example, a 10-minute window sliding every 5 minutes produces a new 10-minute window every 5 minutes.
Windows close on the watermark from earlier. Allowed lateness keeps a window's state alive for a configured period past the watermark. An event arriving in that period is still accepted, and the window fires again with an updated result.
That only helps if the sink can accept a correction. A plain append sink cannot; you would get two rows and no indication that the second supersedes the first. A retractable sink can, either by retracting the previous value and emitting the new one, or by upserting on a key. If you are using allowed lateness, the sink has to be one of these, or the late events are computed correctly and then written into a table that lies.
Past the allowed lateness window, the event is dropped, or routed to a side output if you have configured one. Sending it somewhere is usually better than dropping it, because the volume in that side output tells you whether your watermark tolerance is set anywhere near right.
AWS Services
If you are in the AWS ecosystem, the two you will reach for first are Kinesis Data Streams and Amazon Data Firehose.
Kinesis Data Streams is a log, in the sense of the shapes section. Records are retained, consumers track their own position, multiple consumers can read the same stream independently, and you can re-read. You write the consumer and you own the processing logic. Reach for it when you need to process records, fan out to several independent consumers, or replay.
Amazon Data Firehose is managed delivery. You point it at a destination — S3, Redshift, OpenSearch — and it buffers by size or time, optionally transforms via Lambda, optionally converts format, and writes. There are no consumers and no offsets. Reach for it when the goal is to land the data somewhere and you do not want to run anything.
A common arrangement is a Data Stream for real-time consumers and a Firehose off the same stream archiving everything to S3.
In AWS EventBridge, rules filter events and route the matching ones to targets such as Lambda, which covers the routing half of an event-driven flow without you running a broker.
For event-driven workloads, SNS can be combined with SQS and Lambda to build a decoupled fan-out processing pattern.

SNS publishes the same event to multiple SQS queues, where each queue represents a different downstream consumer or processing flow. This is the pub-sub shape and the queue shape composed: fan-out at the topic, then work distribution and durable buffering at each queue.
The reason to put a queue between the topic and the consumer, rather than subscribing the consumer directly, is what we explored in the correctness section. The queue gives each consumer its own retry behaviour, its own visibility timeout, and its own dead-letter queue. A consumer that is down accumulates a backlog instead of missing events.
Lambda is then configured with an SQS event-source mapping, which polls the queue and invokes your function in batches. Two settings to know: batch size controls how many messages arrive per invocation, and partial batch failure reporting lets a function tell Lambda which messages in a batch failed, so the successful ones are deleted rather than the whole batch being redelivered. Without it, one bad message in a batch of ten means all ten come back.
EventBridge Pipes covers the lighter case — point-to-point from a source to a target with optional filtering and enrichment in between, and no compute of your own to run.
If your team already runs Spark, AWS Glue streaming ETL and Amazon EMR let you keep using it for streaming transformations rather than adopting something new. And Amazon Managed Service for Apache Flink runs the Flink from the previous section without you operating the cluster, which is the usual answer when Flink is right but running a job manager is not.
And yes, AWS also runs Kafka for you — Amazon MSK.
Conclusion
Queues, logs, and pub-sub systems let your architecture absorb bursts, survive temporary failures, and process continuously produced data without tightly coupling every component.
We looked at the three shapes those systems come in, at Kafka as the log, at the outbox pattern and why a database write and a publish cannot be treated as one operation, at what at-least-once delivery actually demands of a consumer, and at what happens to a buffer when the deficit is sustained rather than temporary. We then went through event payload design, stream processing from Kafka Streams up to Flink, and the AWS services that cover the same ground.
The thread running through all of it is that these components do not remove failure, they change its shape. A lost message becomes a duplicate. A dropped request becomes a growing backlog. That is almost always a better trade, but only if you have designed for the failure you moved to.
One thing we deferred. When the payload is too large to put in a message, it goes to a blob store and only the pointer travels. Next up, we will look at blob stores, file formats, static hosting, and CDNs — the other half of moving large things around.



