Kafka Architecture
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Message delivery semantics — covered in Lecture 6 (Message Delivery Semantics)
- The three decision questions — covered in Lecture 6 (Message Delivery Semantics)
- The data flow layer and the rate mismatch problem — covered in Lecture 4 (Stream Processing: Architecture and Processing Strategies)
- Topics and the email subject-line analogy — covered in Lecture 2 (Events, Topics, Non-Functional Requirements, and the Big Data Data Model)
- Horizontal scaling and clusters — covered in Lecture 4 (Stream Processing: Architecture and Processing Strategies)
- Zookeeper z-node types — covered in Lecture 5 (ZooKeeper: Configuration and Coordination in the Streaming Pipeline)
7.1 Message Delivery Semantics: The Three-Question Decision Framework
7.1.1 The Three Delivery Semantics in Review
Why would any streaming system ever choose to lose a message? If you could build a system that never loses anything and delivers every message exactly once, why would anyone settle for less? The catch: stronger guarantees cost more — more coordination, more storage, more complexity. That trade-off is why the three delivery semantics exist at all.
The session opened with a recap of message delivery semantics, the concept carried over from the previous session: exactly once, at least once, and at most once. These are the three ways a streaming system can behave when it moves messages between components. A message is either delivered exactly one time, delivered one or more times, or delivered at most one time (which means it is allowed to drop the message). This was flagged as a very, very important concept — not a topic to skim, because it drives how every streaming use case gets designed.
The three promises, stated precisely:
- At most once. A message may be lost, but it will never be read again by a consumer. The system does not retry and does not redeliver. Losing a message is allowed; repeating one is not.
- At least once. A message will never be lost, but it may be read again. The system retries deliveries, so the same message can reach a consumer two or more times. Repeating is allowed; losing is not.
- Exactly once. A message is never lost and is read by a consumer once and only once. This is the strongest promise, and it is the most expensive to deliver.
| Semantics | Losing a message? | Reading the same message twice? | Typical cost |
|---|---|---|---|
| At most once | Allowed | Never | Lowest — no retries, no tracking |
| At least once | Never | Allowed | Medium — retries and delivery tracking |
| Exactly once | Never | Never | Highest — deduplication and reconciliation |
The three semantics are not a menu of "nice features". They are answers to the question of what your business can and cannot live with. That is why the practical payoff of the recap matters: for any use case you can run a small set of questions, and the answers tell you which delivery semantics fits. The class walked through the three questions one by one.
7.1.2 The Three Questions That Decide the Semantics
Question one is about impact. What will be the impact if communication between the components breaks down? This is the business impact question — if the stream stalls or messages get lost, what does that cost the business in the real world? For a fraud-detection service, a stalled stream means fraudulent purchases pass unnoticed while they happen — the cost is direct and immediate. For a recommendation engine, a stalled stream means less-personalized product pages — the cost is softer and indirect.
Question two is about tolerance. How much data loss can the business tolerate? Not "would you like to lose data", but how much worth of data the business can afford to lose. Some businesses can shrug off a dropped reading; others cannot. A bank that loses a transaction record may lose a customer's trust and face legal trouble; an analytics dashboard that loses one temperature reading out of a thousand is barely affected. Notice the question is asked in terms of worth, not volume: ten minutes of lost stock-market ticks can matter more than ten hours of lost sensor logs.
Question three is about storage. What is the requirement for long-term storage of historical data? The scope of storage decides how much you must keep around, which changes what the system has to guarantee. If a business needs to replay a month of events for reporting, the queue must keep messages durable for weeks — that is a very different system from one that deletes each message as soon as a consumer reads it.
So the framework is: business impact, data-loss tolerance, and storage scope. Every use case goes under these three and gets answered before you pick a name for the delivery semantics.
7.1.3 Using the Framework: Bank Application and Recommendation System
Two example domains were revisited as the running examples that motivated the framework: a bank application and a recommendation system. (The full worked-through versions of both belong to the previous session; this class returned to them only as reminders.) The point of the recap is the method: you do not start from the answer. You start from the three questions, and the use case's answers align you to one of the three semantics.
Sketching the alignment only briefly: for a bank application, a communication breakdown is expensive (a missed payment instruction can cost money and trust), data loss is not tolerable (every transaction is financially meaningful), and historical records are needed for statements and audits — all three answers point toward exactly-once. For a recommendation system, a stalled stream costs some sales, an occasional lost browsing event barely matters, and historical data is used to refine the model rather than to keep legal records — the answers point toward at-least-once, and sometimes even at-most-once is enough.
Scope: the three-question framework applies whenever you design a streaming pipeline, before you pick any technology. The answers are business answers, not technical preferences — "exactly-once is safer" is not a reason; "our business cannot afford to miss a fraudulent transaction" is. The storage question also carries a hidden scope decision: retention is bounded by disk and time. Keeping messages forever is rarely free, so "must keep historical data" usually comes with "for how long?" attached.
Common traps:
- Treating delivery semantics as a performance setting. At-most-once is not "the fast mode"; it is a business promise that messages may vanish.
- Assuming exactly-once is always the right answer. It is the right answer only when the business genuinely cannot tolerate loss or duplication; otherwise it adds cost without adding value.
- Answering the tolerance question with "we would like to lose nothing". The question is about what you can afford, not what you prefer.
7.1.4 Exam Note: How to Answer a Delivery Semantics Question
Exam note: if the exam gives you a use case and asks you to discuss message delivery semantics, you must write these three questions, discuss the use case aligned with each of them, and only then decide which delivery semantics is appropriate. The examiner wants to see the three-question path, not a one-line answer. A safe answer shape: (1) business impact, (2) data-loss tolerance, (3) storage scope, (4) the semantics the three answers point to, (5) one line on what that semantics costs the system.
Why does the framework lead, rather than the definition? Because the definitions say what each semantics does, but only the three questions say which one a given use case needs. An answer that names exactly-once without walking the three questions has skipped the reasoning the question is testing.
Q: In the next session, can we have a discussion with some sample questions — a question-and-answer discussion — so that we get a fair idea of how to answer?
A: Yes. Expect practice questions of that shape before the exam.
7.2 Kafka in the Generalized Streaming Architecture
7.2.1 Kafka as the Data Flow Layer
Why not connect the collectors straight to the processors? If both sides run at the same speed, direct wiring looks simpler. The problem: the two sides almost never run at the same speed. Events arrive at one rate and get consumed at another, and the moment the consumer falls behind, data starts to pile up — or leak. A layer in the middle that absorbs the speed difference is what keeps the pipe from bursting.
Kafka is a messaging system. In the generalized streaming architecture, data moves from a collection tier to a processing layer, and between them sits the data flow layer. Kafka is what you keep in place of that data flow layer — that is its main utility. Its job is to match the impedance in terms of speed: events arrive at the collection tier at one speed, and the analysis tier can only consume at another speed. The message queue in the middle absorbs that difference.
Impedance is a word borrowed from electronics. Two circuits connected directly transfer signal well only when their impedances match; a mismatch causes reflections and wasted power. The streaming version is the same: the collection tier and the analysis tier have different natural rates, and the data flow layer is the matching element between them. The word keeps its meaning here: match the rates, and data flows smoothly; leave them mismatched, and the system wastes effort or drops data.
The generalized picture runs collection tier → data flow layer (Kafka) → analysis layer. The processing engine used alongside it in this course is Spark: Kafka performs the data ingestion, the messages are then sent to Spark, processing happens in Spark, and the results go onward to a sink. Kafka architecture itself continues as a topic even after the mid-semester exam.
7.2.2 The Publish–Subscribe Model and Kafka Connect
Kafka works on a publish–subscribe model. Publishers push messages into a message queue, and downstream client applications consume them on the other side. On one end you have a producer API; on the other end, a consumer API. In the Kafka Connect framework these map to source connectors on the producer side that bring data in (source connect), and sink connectors that push processed data out (sink connect) — different types of interfaces on each side.
The producer API works with concrete classes — concrete meaning set up against specific, defined producer topics. Producers can be added on the fly and removed on the fly; you can scale them dynamically. Consumers work the same way: many consumer API instances, added dynamically, each identified by a key ID, because the key ID is what tells you which producer or consumer you are dealing with. Messages are produced for further analysis, and they arrive in batches — batches of, say, 100 events, or 20 events, and so on. Batching is a throughput trick: one network round trip that carries 100 events moves more data per second than 100 separate trips ever could.
The key characteristic: producers are completely separated from consumers. A data pool layer sits between them, so neither side needs to know about the other. This decoupling is what lets different data sources feed the same streaming application — the main advantage of the architecture is that different variations of data sources can be used for the streaming application. A new data source joins by writing to the pool; an existing consumer never changes. A new consumer joins by reading from the pool; producers never change. Producers and consumers live independent lifecycles — that is the whole point of the middle layer.
One scope note: this course does not look at orchestrating Spark and PySpark components. Platforms like Databricks make that configuration easy, and it is treated as a separate matter.
7.2.3 Student Questions: Topics Only, and Where Spark Fits
Q: Does Kafka support both queues and topics, or only topics?
A: Only topics. Everything is encapsulated into a topic. You can have more than one topic, and each topic carries many messages; from there the whole system behaves as discussed in the architecture.
That answer is worth slowing down on, because "queue" is the loaded word in it. In traditional messaging products like RabbitMQ or ActiveMQ, a queue is a first-class object with its own rules, and a message disappears from the queue once a consumer takes it. Kafka deliberately has no such object: the unit of organization is the topic, and everything — grouping, buffering, reading — happens through topics and their parts. The queue-like behavior people expect comes from the topic machinery itself, not from a separate queue facility.
Q: When we talk about the Kafka architecture, does Spark feature in that architecture?
A: No. As an abstract model, Kafka architecture is a set of producers and a set of consumers. Spark may or may not be in the picture: Spark needs some kind of data ingestion, and that ingestion may happen with Kafka or may happen without Kafka. Kafka, in turn, may feed Spark or may feed something else. In this course's working setup, though, Kafka ingests and Spark processes.
The abstract view is the one to carry into the exam: the Kafka architecture is defined by the producer–consumer relationship, not by any particular processing engine that happens to sit on either side. The course's wiring — Kafka into Spark into a sink — is one instance of the general picture, not the definition of it.
Q: In layman's terms — like the Amazon marketplace, many producers in AWS put their products on Amazon, and a subscriber is like a customer who comes along, selects a product, and filters it out?
A: Correct. That is exactly the streaming model: producers publish into a central place, and consumers select what they need.
The marketplace picture maps cleanly: producers publish products (messages) into one central place (the broker), customers (consumers) walk in, and each customer selects what they need (subscribes to topics) rather than taking everything on the shelf. The analogy has a limit worth noting: a market has finite shelves, while a Kafka topic keeps accumulating until retention removes old segments.
7.2.4 Industry Applications: Kafka in Production
Real-world: Adidas uses Kafka as a data streaming platform. Its purpose is enabling the teams to implement real-time event processing for monitoring, analytics, and reporting.
Real-world: a Shopper Stop purchase is a real event. When a purchase happens, a message is generated that carries which bank card you used, the volume of the transaction, and the kind of purchase. Different customers come in and generate such messages continuously, and depending upon the business objective the system generates appropriate insights from those instant details.
Real-world: Agoda uses Kafka for analytical streaming purposes, and an event-cloud platform was mentioned for monitoring messages. Coursera is another user: Kafka powers education at scale, serving as the data pipeline for real-time learning analytics and dashboards.
These use cases share a shape: a real-world event (a purchase, a click, a course interaction) becomes a message, and the business value comes from acting on the message while it is still fresh. That freshness is exactly what the data flow layer buys — the analysis tier no longer waits for a nightly batch to learn what happened today.
7.2.5 A Distributed, High-Throughput System
Apache Kafka is a distributed publish–subscribe model — which means it runs as a cluster of machines. It is designed as a high-throughput distributed system, suitable for large-scale applications. Its importance lies in scalability: you can add producers and consumers, where producers are nothing but the various data systems through which data actually comes into the processing engine (Spark, in this course's setup). The log-based design lets a production cluster handle millions of messages per second: the work is spread across machines, and each machine only sees its own slice of the load.
Kafka takes care of many non-functional requirements — reliability, scalability, maintainability, and so on. Within the cluster there is a notion of leaders and followers; the leader is also a node. A bunch of machines are connected together and all work toward one common goal. In replication terms, each partition of a topic has one leader, and the leader serves all reads and writes for that partition; follower nodes hold copies of the partition, so that if the leader fails the cluster can keep going with another node.
The basic running model: a broker is the Kafka server. In the Java distribution you run a server start script (the server.bat file), and executing it is how you configure Kafka. A set of producers publish to topics, and consumers subscribe to those topics and consume them. In a single-machine setup one broker sits at the center; in a production cluster, brokers are the nodes of the cluster.
The architecture, in one line: producers → topics on brokers → consumers, with a cluster of broker nodes in the middle so the whole system can scale horizontally and survive node failures. The queue-like buffering happens inside topics; Spark is a downstream consumer in this course, not part of the Kafka architecture itself.
7.3 Topics and Partitions
7.3.1 What a Topic Is: The Inbox and Subject-Line Analogy
A topic is a group of messages of the same type — a kind of entity, a subject. The best way to feel it is through the inbox. Think of your Outlook inbox at the office: do you respond to every message you receive? Nobody does; some messages are not even read. On what basis do you decide? The subject line. The subject line tells you what a message is about, and that decides whether you pay attention to it or not.
A Kafka topic is the subject line for messages. Incoming messages are segregated into named streams by topic, and that segregation is what lets the right consumers pick them up. The topic determines which messages a consumer will receive.
The mapping in simple words: a message's topic is what tells a consumer "this is for you" or "this is not for you". A consumer subscribes to the topics it cares about and ignores the rest — exactly like reading only the emails whose subject lines matter to you. The analogy's limit: an inbox subject line is written by a human and read by a human, while a topic label in Kafka is a technical contract between producer and consumer — both sides agree on the topic name and the message shape before any data moves.
7.3.2 How Messages Reach Consumers
Messages come into the system as a stream. They are written to topics, and the topics are read by the broker. When a producer sends messages, it cannot write directly to consumers — the messages go to a topic first, and it is the broker that looks at the topics (a topic, or several topics, each internally divided). Because the messages are sent based on some schema, they can be segregated by topic as they arrive. Consumers then consume the messages they are interested in through their subscribe method, based on the topics that are part of their subscription. The topics a subscriber holds are processed in small portions, and the analysis runs on those portions.
Under the hood, a topic is a log — an append-only sequence of records on disk. Producers do not overwrite old messages; they append new ones to the end. Consumers read the log from front to back. This one design choice explains the queue behavior from the previous section: messages wait inside the log until a consumer is ready, and a new consumer can even start from the beginning of the log and read history — something a traditional queue that deletes consumed messages cannot do.
7.3.3 Partitions: The Data-Frame Analogy
Each topic is made up of many partitions — that rule is emphasized as important. A partition is a logical group of messages. The analogy: a data frame. You take a data frame and divide it into subsets of data frames, and each subset is then modified independently. Kafka partitions a topic the same way: the topic's messages are split into subsets, and each partition can be processed independently, which is what gives Kafka its parallelism.
The partitions live across the nodes of the cluster — it is a distributed network, and each node maintains its share of partitions. So Kafka supports partition-level processing of the same family that Spark performs, all facilitated through Kafka's own topic and partition machinery.
Two properties follow from this layout, and both matter for exams and for design:
- Parallelism is bounded by partition count. Within one partition, messages keep their order; the broker assigns every message a sequence number called an offset (a counter that starts at 0 and grows by 1 per message). Parallel processing comes from assigning different partitions to different nodes and different consumers — not from splitting one partition's stream among several workers. A topic with 4 partitions can be consumed by at most 4 consumers working in parallel (one per partition); a topic with 40 partitions can spread the load much wider.
- Ordering is guaranteed within a partition, not across the topic. If messages A, B, C land in the same partition, consumers see A then B then C. If they land in different partitions, no global order exists. So when order matters, the producer must route related messages (say, all events for one customer) to the same partition.
Where the data-frame analogy stretches: a data frame you split and modify in parallel is usually reassembled afterward; Kafka partitions are deliberately never merged back — the whole point is that independent consumers each chew on their own subset forever.
Scope: the partition count is chosen at topic creation, and changing it later is expensive — Kafka cannot split an existing partition in half for you. Partitions also carry a cost: each partition means more files and bookkeeping on the broker, so "more partitions = more parallel" is not a license to create thousands without measuring. Zookeeper keeps track of which partition lives where as brokers join and leave the cluster, so the mapping stays correct even when machines come and go.
Common traps:
- Believing a topic is ordered globally. Only one partition's stream is ordered; two partitions can interleave.
- Believing every consumer gets every message. That is true only for fan-out use cases; within a consumer group, each partition is consumed by exactly one member.
- Confusing partitions with replicas. Partitions split a topic for parallelism; replicas copy a partition for safety. They are different reasons to hold more than one copy of the data.
A topic is a named stream of messages of one type; the broker splits each topic into partitions so the work can spread across the cluster. The inbox subject line tells you which messages are yours; the partition layout tells the system where each slice of those messages is processed and in what order.
7.4 Ingestion Rate vs Processing Rate (Ri and Rp)
7.4.1 The Rate-Matching Problem
Back to the architecture picture: the collection tier emits events at some speed, and the analysis tier processes events at some speed. Two rates govern the design. (R-sub-i) is the ingestion rate — the rate at which messages are incoming to the streaming layer. (R-sub-p) is the processing rate — the rate at which messages are being processed. The message queue in the data flow layer exists to match the impedance between these two speeds.
Picture the two tiers as pipes of different diameter. The collection pipe feeds events into a tank (the queue), and the analysis pipe drains the tank. If the feeding pipe is wider, the tank fills; if the draining pipe is wider, the tank stays empty. The water level at any moment is the backlog — the number of messages waiting. The two rates decide whether that level rises, falls, or stays flat, and the queue exists so the tank is there to absorb the difference instead of letting the pipe burst.
Whenever you compare the two rates, first make sure the units are matched. You can only divide or compare them when both are in the same unit — for example, both in MB per second. Comparing 16 GB per minute against 10 MB per second without converting is not a comparison at all: it is two different numbers about two different things.
7.4.2 Worked Example: Rp = 0.8 × Ri
Setup. Suppose and , in the same unit (say, MB per second).
Step 1 — write the ratio. Compare the two rates by dividing:
So ingestion arrives at 1.25 times the processing speed.
Step 2 — turn the ratio around. The same relationship written from the processing side:
Answer: the processing rate is 0.8 times the ingestion rate — 80 percent of it.
Sense-check. If the processor handles 8 of every 10 messages arriving, then for every 10 messages that arrive only 8 get processed — one message in five waits. The backlog grows by 2 messages per 10 arrivals, which is the shape of a system that must buffer or scale. The numbers agree with intuition: processing slower than arrival means the queue fills.
7.4.3 Worked Example: Ri = 30 × Rp
Setup: GB per minute and MB per second. One unit is in GB, the other in MB; one is per minute, the other per second — nothing matches yet. Before any division, the unit conversion must happen.
Q: When converting, should we consider 1024 or 1000 megabytes per gigabyte?
A: For all practical purposes, 1000 MB per GB. And from an examination standpoint you will be asked exactly this kind of question: given an ingestion rate and a processing rate, work out the ratio and what it means.
The rule to remember: this course converts with the decimal convention, 1 GB = 1000 MB, not the binary convention of 1024 MB per GB. The binary convention exists (it comes from powers of 2 in memory addressing), but exam problems in this course are set with 1000, because the arithmetic stays clean.
Step 1 — convert the ingestion rate to MB per second, using 1 GB = 1000 MB:
The conversion chain, line by line: 16 GB becomes MB because 1 GB = 1000 MB; 1 minute becomes 60 seconds; . The intermediate form is just written compactly. The value was then rounded to roughly MB/s (about 300 MB/s) to keep the arithmetic clean.
Step 2 — divide by the processing rate:
Answer:
The rate of ingestion is 30 times the rate of processing.
Sense-check. Keeping the exact value instead of the rounded one gives , which rounds to roughly 27 — still "about 30 times", and the problem was deliberately framed with the rounded 300 so the ratio falls out as the clean integer 30. Such problems are often framed with numbers chosen to divide evenly, so the ratio falls out neatly. The professor's rule for these questions: when the problem says Rp is 10 MB/s (or any value that divides evenly into Ri after rounding), expect the ratio to come out as a whole number.
7.4.4 Interpreting Ri = 30 × Rp: What Your Architecture Must Do
Q: Which layer is working faster, the streaming layer or the ingestion layer?
A: The ingestion layer. If Rp is 1 and Ri is 30, lots and lots of messages are arriving and the processor is not able to process them — 30 messages arrive for every one it handles.
The question's trap is the word "streaming". Both layers belong to the streaming system, so "the streaming layer" is ambiguous; the rate comparison removes the ambiguity. The ingestion rate is 30 times the processing rate , so the ingestion side wins the race by a factor of 30 — and winning the race is exactly the problem.
Q: Ri = 30 Rp — what should I understand from this, or how should my architecture be?
A: It should be able to buffer that much: for every message the analysis tier processes, you must be able to store 30 messages in the queue. Your processing speed is slower than the ingestion speed, and unless you do something, messages will be lost.
So what do you do? First option: scale up the streaming layer — instead of a one-node cluster, use a 20-node or 30-node cluster, so parallel processing happens across the nodes. In other words, speed up the processing time. Second option: keep a buffer storage to hold data before processing. The catch with a buffer: after one minute you get that many new messages again, so buffering alone never finishes the job. The backlog is not an accident; it is the arithmetic of repeated every minute. Put concrete numbers on it: writing continuously at 150 MB/s, a 6 TB disk fills in about 11 hours (6,000,000 MB ÷ 150 MB/s ≈ 40,000 seconds). So a buffer buys time measured in hours or days, not forever — it is a breathing room, not a solution.
Q: Do I really need to store all these messages?
A: It depends on the delivery semantics. Some cases require storing all the messages; some do not. For example, in an operational monitoring use case, depending on the scenario, you may want to store all messages.
Q: Is all the ingested data required, or can we drop some?
A: In general, event dropping is not acceptable. But it can make sense: take temperature sensor readings — you do not need all the data processed, only data from certain times. You can also use multiple queues to hold the data, and in a queue-based setup you can pipeline the data to some extent. Where you do not have a single subscriber, you may go with something like Azure Event Hub or a multiple-topic-based design.
The delivery semantics also decides how much you must keep around. With exactly-once semantics you need to do something extra — you can make it a queue and handle each message once. With at-most-once semantics you do not need every message persisted, stored and processed; you can take small samples and process those, because at-most-once allows you to drop messages, which fits operational monitoring. With exactly-once you cannot blindly drop messages; some kind of rework or reconciliation has to be done.
Scope: the rate analysis assumes the two rates are steady, at least over the window you are designing for. Real systems burst: a flash sale or a spike in sensor traffic changes from one minute to the next, and the queue must be sized for the worst window, not the average. The ratio is a snapshot; the design question is what happens in the busiest minute.
Common traps:
- Comparing the rates without matching units first. 16 GB per minute vs 10 MB per second means nothing until both are in MB per second.
- Reaching for 1024 MB per GB in an exam problem. This course uses 1000 for all practical purposes.
- Thinking the buffer is a permanent fix. The buffer absorbs one window of backlog; the next window brings the same inflow again.
- Reading backwards. It says ingestion is 30 times processing — the ingestion side is faster, which is why the queue fills.
7.4.5 Exam Notes on Rate Numericals
Exam note: these numericals are very important. Expect a question that gives you an ingestion rate and a processing rate — often in different units, deliberately — and asks for the ratio and its consequences. The recipe: match the units first, convert to MB per second using 1000 MB per GB, then divide, then interpret. Ri much larger than Rp means ingestion is faster, and messages will be lost without buffering or scaling. Ri in the same order as Rp means the system can keep up.
The interpretation is worth full marks, not just the arithmetic: a ratio of 30 means the architecture must buffer 30 messages per message processed and scale the processing tier or the queue will overflow. Write the conversion chain in full — the examiner wants to see 16 GB/min → 16000 MB/60 s → 266.67 MB/s, not just the final 30.
7.5 Design Decisions for the Data Flow Layer
7.5.1 Choosing a Strategy from the Rates
The rates decide how you process. If Ri is of the order of Rp, you can write messages directly to the processing layer — the queue is barely needed. If Ri is much greater than Rp, you go for batch processing, horizontal scaling, and buffer or queue storage. So depending on these rates, you basically decide how you want to process them. The boundary case to keep straight: it is the fast ingestion side (Ri much larger than Rp) that forces the buffered or batched path, because the processor cannot keep up with what arrives. If the rates are comparable, the system can afford to hand each message straight to the analysis tier.
Message delivery semantics also plays a role. At-least-once semantics means a lot of messages must be sent (retries included), which changes how the rates can be tuned — the delivery promise constrains how Ri and Rp may be fine-tuned, because the effective volume a system must absorb includes every retransmission, not just the first copy of each message.
7.5.2 Horizontal Scaling and the Kafka Cluster
Horizontal scaling means: instead of a single machine, you create a Kafka cluster. A cluster has multiple brokers, and each broker is one node in the cluster. Adding brokers is the standard way to scale the data flow layer — you keep adding more brokers, and parallel processing happens across the nodes. The partitions of the topics spread over the broker nodes, so each new broker takes on a share of the partition-level work, and the throughput of the whole layer grows with the number of machines.
A practical sizing rule from production practice: for a development or test environment one broker is usually enough, while a production system runs at least three to five brokers so that replicas of a partition live on different machines and a single node failure does not take the layer down.
Scope: horizontal scaling works because the topic partitions are the unit of work — adding a broker without partitions to distribute is like hiring workers without a workload to hand them. The cluster also needs enough partitions to spread: the parallelism a topic can deliver is capped by its partition count. And scaling the data flow layer does not change the arithmetic of section 7.4: if Ri stays 30 times Rp, a bigger cluster changes Rp's denominator (more nodes sharing the processing), which is exactly the intended fix.
Common traps:
- Confusing the two scaling directions. Vertical scaling makes one machine bigger; horizontal scaling adds machines. Kafka clusters scale the second way.
- Expecting one broker to behave like a cluster. A single broker is a convenient test setup, not a high-throughput deployment — there is no one else to hold replicas or share partitions.
7.5.3 Queue and Broker Together
Q: How do you scale the data flow layer?
A: Two ways. One is multiple brokers — keep adding more. The other is to store a message queue in the data flow layer, simply maintain a message queue in which all the events are stored before your processing layer.
The two answers come from two different pressures. Brokers address the processing side of the mismatch: more nodes, more parallel processing, faster . The queue addresses the arrival side: it holds the events that arrive while the processors catch up, which is what the "buffer 30 messages per message processed" rule from the previous section calls for.
Q: I am confused — are these two different solutions, a message queue or brokers? Can we use a queue and a broker at once?
A: Yes, you can use all of them together. Q: Then the queue should be forwarding messages to the broker?
A: Exactly.
So the two tuning knobs — horizontal scalability and buffering — combine rather than compete. The queue sits in front of the brokers and feeds them; the brokers parallelize the processing of what the queue hands over. A common pipeline shape in this course's architecture is exactly this: incoming events land in the queue, the queue forwards them to the broker cluster, and the brokers feed the analysis layer.
7.5.4 Delivery Semantics Interplay
Which strategy goes with which scenario was deferred to the next session, but the logic is already visible. At-most-once semantics lets you drop messages, so sampling small portions is legitimate — that is the operational monitoring class of use cases. At-least-once means the system must keep delivering, with retransmission, so the ingestion volume handled is higher. Exactly-once means every message matters: you cannot drop, and something must be done about duplicates — the queue-and-handle pattern, where each message is worked exactly once and any repeat delivery is detected and reconciled.
The data flow layer has three coupled decisions: the rate comparison (does Ri outrun Rp?), the scaling response (more brokers, a buffer, or both), and the delivery semantics (what may and may not be lost or repeated). The numbers decide the architecture; the semantics decide what the architecture must guarantee. None of the three can be chosen in isolation.
7.6 Setting Up and Running Kafka
7.6.1 Download and Folder Structure
Downloading Kafka (the Confluent Kafka distribution was used for the demonstration) puts a folder on your local machine. Inside it you open the bin directory: it contains so many batch files or shell scripts. The scripts are Unix or Linux shell scripts; when you work on a Windows system you double-click into the Windows folder, which holds the equivalent batch (BAT) files. Same scripts, same order of steps, different file extension — the Windows side wraps the same commands in .bat files so they run without a Unix shell.
7.6.2 The Four Startup Steps
Running a Kafka application requires four steps, in order:
The four startup steps, with the reason each one exists:
- Start the Zookeeper (the coordination service). Kafka's only external dependency is a Zookeeper installation. Zookeeper keeps the cluster's shared facts — which brokers are alive, which partition lives on which broker — so that every node agrees on the state of the system. Nothing in Kafka starts correctly without it, which is why it comes first.
- Start the Kafka server (the broker). The broker is started by the server start script — when you execute it, you configure Kafka. The script reads a properties file that defines the broker itself: the broker ID, the port it listens on (9092 by default), the log directories where topic partitions are written, and the Zookeeper connection string. In a single-machine setup one broker is enough; a production cluster starts one broker process per node.
- Specify the configuration for the producer. The producer side is configured with the details it needs to send messages: which brokers to talk to (the metadata broker list) and how to serialize messages. The producer writes to topics through this configuration — the concrete producer topic classes from section 7.2 are set up here.
- Specify the configuration for the consumer. The consumer side is configured with where the broker cluster is, which topics to subscribe to, and the identity of the consumer group. Each consumer instance is identified by its key ID, and the group coordinates which consumer handles which partitions.
These steps were shown only as a preview; the actual walkthrough was deferred to the next session because the scripts take time to execute.
7.6.3 Student Questions: Live Demo Next Session
Q: Is it possible to run the batch files and see how it works?
A: Next session — I will show how to install Kafka, how to run it, and how to see the output. The scripts themselves take some time to execute, so a five-minute slot is not enough today.
The preview is worth keeping straight until the demo: the order is Zookeeper first, broker second, then the two client configurations. Every Kafka application — including the one shown in the live demo — follows this same sequence.
7.7 Zookeeper Recap: Node Types
7.7.1 Persistent, Ephemeral, Sequential
A quick recap from the Zookeeper session: Zookeeper keeps data in nodes called z-nodes, and there are three types. Persistent nodes stay until they are explicitly removed. Ephemeral nodes exist only as long as the session that created them is alive. Sequential nodes get a sequence number appended, so ordering among them is preserved.
The three z-node types, side by side:
- Persistent — the node survives session disconnects and process restarts; it is removed only when someone deletes it on purpose. Use it for facts that must outlive any single connection, like the configuration of the cluster.
- Ephemeral — the node dies with the session that created it. When a client disconnects or crashes, its ephemeral nodes disappear automatically. Use it for liveness markers: a broker that is currently alive registers an ephemeral node, and the cluster can see it vanish the moment the broker goes away.
- Sequential — the node gets an auto-incremented sequence number appended to its name, so the creation order of a set of nodes is preserved. Use it wherever order matters, such as electing the first of several contenders.
These three node types — persistent, ephemeral, sequential — are the building blocks discussed earlier, and they matter again here because Kafka uses Zookeeper for cluster coordination: it is the first thing you start when you launch Kafka. The connection to the Kafka startup steps is direct: Zookeeper tracks which brokers are live (ephemeral nodes that vanish on failure), where partitions live, and which replicas are in sync — the shared state that step 1 of the four startup steps provides.
Persistent for durable facts, ephemeral for liveness, sequential for ordering — and Kafka leans on all three the moment its cluster runs. The four-step startup exists because Kafka cannot coordinate itself; Zookeeper is the memory of the cluster.
Exam Guidance Summary
- Message delivery semantics is a very important concept. A use-case question on it expects the three-question framework written out: business impact if communication breaks down, how much data loss the business can tolerate, and long-term storage requirements. Discuss the use case along all three before naming the delivery semantics.
- Rate numericals on Ri and Rp are important. Expect given ingestion and processing rates in different units; match the units (1000 MB per GB, both converted to MB per second), compute the ratio, and interpret what it means for the architecture.
- The topics and partitions model is examinable: what a topic is, how partitions give parallelism, and the inbox and data-frame analogies are the mental models the examiner expects you to reproduce.
- Syllabus status: the material up to and including this session — the Kafka architecture — is part of the mid-semester scope; everything covered today is examinable.
- A list of mid-semester topics to focus on will be shared.
- A sample question-and-answer discussion is planned for the next session, so you can see how answers are expected to be structured — useful for both the delivery-semantics questions and the architecture questions.
Key Industry Applications
- Real-world: Adidas uses Kafka as its data streaming platform, enabling teams to implement real-time event processing for monitoring, analytics, and reporting.
- Real-world: a Shopper Stop purchase generates a real-time message carrying which bank card was used, the transaction volume, and the kind of purchase; different customers generate such messages continuously, and the system derives appropriate insights from those instant details.
- Real-world: Agoda uses Kafka for analytical streaming purposes.
- Real-world: Coursera uses Kafka to power education at scale — it serves as the data pipeline for real-time learning analytics and dashboards.
- Real-world: event-cloud platforms use Kafka-style streaming for monitoring messages.
- Real-world: Azure Event Hub is the alternative mentioned when a single-subscriber queue model is not enough — multiple topics or an event hub carry the data instead.
- Real-world: the producer–consumer picture is the same one you see in a marketplace — producers publish products, and subscribers (customers) select and filter what they want.
SPA Lecture 07 notes · Kafka Architecture
Sections Breakdown
The three delivery semantics, the three-question decision framework, and the exam answer shape.
Kafka as the data flow layer, the publish-subscribe model, industry applications, and the distributed cluster.
What a topic is, how messages reach consumers, and how partitions give parallelism.
Rate-matching, worked rate numericals with unit conversion, and what a large ratio means.
Choosing a strategy from the rates, horizontal scaling, and the queue-broker combination.
Download layout and the four Kafka startup steps.
Persistent, ephemeral, and sequential z-nodes and their role in Kafka coordination.
What is examinable from this session and how answers should be structured.
Real-world Kafka deployments: Adidas, Shopper Stop, Agoda, Coursera, and Azure Event Hub.
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
Message Delivery Semantics: The Three-Question Decision Framework
Must-know: Before naming a delivery semantics, walk the use case through three questions: business impact if communication breaks down, how much data loss the business can tolerate, and long-term storage requirements.
Top pitfall: Treating at-most-once as 'the fast mode' or assuming exactly-once is always right; the semantics is a business promise, not a performance setting.
Self-check: Why does the bank application point toward exactly-once semantics?
Connects to: 7.4 Ingestion Rate vs Processing Rate; 7.5 Design Decisions for the Data Flow Layer
Kafka in the Generalized Streaming Architecture
Must-know: The Kafka architecture is an abstract model of producers and consumers around topics; Spark is not part of the architecture — Kafka ingests, Spark processes in this course’s setup.
Top pitfall: Assuming Spark is part of the Kafka architecture, or expecting Kafka to support queues as first-class objects alongside topics.
Self-check: Which component of the streaming architecture does Kafka replace?
Connects to: 7.3 Topics and Partitions; 7.4 Ingestion Rate vs Processing Rate; 7.5 Design Decisions for the Data Flow Layer
Topics and Partitions
Must-know: Each topic comprises many partitions; partitions are distributed across cluster nodes and processed independently, which is what gives Kafka its parallelism.
Top pitfall: Assuming a topic is ordered globally — ordering holds within a partition only, not across partitions.
Self-check: Why does a topic with 4 partitions support at most 4 consumers working in parallel?
Connects to: 7.2 Kafka in the Generalized Streaming Architecture; 7.5 Design Decisions for the Data Flow Layer
Ingestion Rate vs Processing Rate (Ri and Rp)
Must-know: Match units first (1000 MB per GB, both to MB per second), then divide: 16 GB/min becomes 266.67 MB/s, so Ri/Rp = 300/10 = 30 and the architecture must buffer 30 messages per message processed or scale.
Top pitfall: Comparing rates without matching units, or using 1024 MB per GB — the course convention is 1000.
Self-check: If Ri = 16 GB per minute and Rp = 10 MB per second, what is the ratio and what must the architecture do?
Connects to: 7.1 Message Delivery Semantics; 7.5 Design Decisions for the Data Flow Layer
Design Decisions for the Data Flow Layer
Must-know: Scale the data flow layer two ways that combine: add brokers (horizontal scaling, parallel processing across nodes) and keep a message queue that forwards events to the brokers.
Top pitfall: Treating brokers and buffering as competing solutions — they work together, with the queue in front feeding the broker cluster.
Self-check: If Ri is much greater than Rp, which processing strategy does the rate comparison force?
Connects to: 7.4 Ingestion Rate vs Processing Rate; 7.2 Kafka in the Generalized Streaming Architecture
Setting Up and Running Kafka
Must-know: The four Kafka startup steps in order: Zookeeper first, then the broker server, then producer configuration, then consumer configuration.
Top pitfall: Starting the broker before Zookeeper — Kafka’s only external dependency is the Zookeeper coordination service.
Self-check: Why must Zookeeper be started before the Kafka server?
Connects to: 7.7 Zookeeper Recap: Node Types; 7.2 Kafka in the Generalized Streaming Architecture
Zookeeper Recap: Node Types
Must-know: Z-node types: persistent nodes stay until explicitly removed, ephemeral nodes live only as long as their session, sequential nodes preserve creation order via appended sequence numbers.
Top pitfall: Confusing ephemeral with persistent nodes — ephemeral nodes vanish automatically when the session dies.
Self-check: Which z-node type is a natural fit for tracking which brokers are currently alive?
Connects to: 7.6 Setting Up and Running Kafka
Exam Guidance Summary
Must-know: The Kafka architecture material is in the mid-semester scope; practice questions in the three-question framework format are coming before the exam.
Self-check: Which examinable topics are part of the mid-semester scope?
Key Industry Applications
Must-know: Kafka powers real-time event processing at Adidas, Agoda, Coursera, and for event-cloud monitoring; Azure Event Hub is the multi-topic alternative.
Self-check: Which platform was mentioned as the alternative when a single-subscriber queue model is not enough?
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.