What Is a Producer in Kafka?

What Is a Producer in Kafka?

A beginner-friendly guide to the client that writes events into Kafka: how it prepares, batches, sends, and confirms every event, and which settings decide whether your data is fast, safe, and correctly ordered.

Imagine a busy courier company. Customers bring parcels to a front desk. The staff check each label, sort parcels by destination, pack those going to the same city into one big sack, hand the sack to a driver, and wait for a signed receipt to prove it arrived. If a driver returns saying the road was closed, the staff try again. A good courier company never loses a parcel and never delivers the same parcel twice. In the world of Apache Kafka, the producer is that courier company. It takes your application’s events, prepares them, packs them efficiently, delivers them to the right Kafka server, and makes sure they arrive safely. This guide explains every step in simple words.

1Where the Producer Fits

Before diving into the producer itself, let us see its place in the larger Kafka picture.

The story so far

Apache Kafka is a system for storing and moving streams of events, such as orders, payments, clicks, or sensor readings. Events are grouped into named categories called topics, and each topic is split into slices called partitions. The servers that store the partitions are called brokers, and a team of brokers is called a cluster.

Brokers are patient. They store what they receive and hand out what is requested. They never go out to look for events. Something has to bring events to them. That something is the producer.

The simple definition

A producer is a client, meaning a program or library inside an application, that writes events into Kafka topics. Whenever a customer places an order, a sensor takes a reading, or a user clicks a button, the application can hand that fact to a producer, and the producer makes sure it is safely recorded in Kafka.

Simple Analogy

Think of a newspaper reporter filing stories. The reporter does not print or distribute the newspaper. The reporter simply writes stories and sends them to the newsroom, where they are stored and later read by many people. The producer is the reporter, Kafka is the newsroom, and consumers are the readers.

i
Helpful Note

A producer does not know or care who will read the events. It only writes. This freedom from knowing the readers is one of the biggest reasons Kafka keeps systems loosely connected.

2What Makes Up an Event

A producer sends records. Each record has a few simple parts.

Part 1

Topic

The name of the category that should receive the event, such as “orders” or “payments”.

Part 2

Key (optional)

An identity, such as a customer number, that decides which partition receives the event and keeps related events together.

Part 3

Value

The actual content of the event, such as the details of an order.

Part 4

Headers (optional)

Small labels that travel with the event, such as where it came from or a tracking number.

Part 5

Timestamp

The time attached to the event, either set by the producer or added when the broker stores it.

Part 6

Partition (optional)

The producer may name an exact partition, though it usually lets the partitioner choose.

Simple Analogy

A record is like a parcel. The topic is the destination city. The key is the recipient’s name, used to decide which delivery van takes it. The value is what is inside the box. Headers are the stickers on the outside, and the timestamp is the date stamped on the label.

!
Common Mistake

Putting huge payloads, such as whole videos or giant documents, inside the value. Kafka is built for many small to medium events. Very large messages strain brokers and slow everyone down.

3The Journey of a Sent Event

When an application sends one event, a whole chain of small steps happens inside the producer.

1

The application hands over the record

The application calls the producer with a topic, key, value, and optional headers. The call returns quickly, because the producer takes over the heavy lifting.

2

The producer knows the cluster

Using metadata, the producer already knows which brokers exist and which broker leads each partition of the topic. If it does not know, it fetches the map first.

3

The serializer converts to bytes

Kafka stores plain bytes, so the key and value are converted by serializers into an agreed format.

4

The partitioner picks a partition

The partitioner decides which partition of the topic receives this record, using the key if there is one.

5

The record joins a batch

The record is placed into a batch buffer belonging to that partition, where it waits for company.

6

The sender thread ships the batch

A background thread collects ready batches, groups them by destination broker, and sends them over the network.

7

The broker stores and confirms

The leader broker appends the batch to the partition log, possibly waits for followers to copy it, and sends back a response.

8

The application learns the result

On success, the application receives the partition and offset where its event now lives. On failure, it receives an error to handle.

flowchart LR
  A["Application"] --> SR["Serializer"]
  SR --> PT["Partitioner"]
  PT --> BF["Batch Buffer per Partition"]
  BF --> SN["Sender Thread"]
  SN --> LB["Leader Broker"]
  LB --> AC["Acknowledgement"]
  AC --> A
        
FIG 1 — The path of one event inside a producer
Simple Analogy

The front desk clerk of the courier company checks the label, decides which delivery route the parcel belongs to, drops it into that route’s sack, and carries on with the next customer. A separate driver collects full sacks and delivers them. The customer never waits for the drive.

4Serializers: Turning Data into Bytes

Kafka does not understand customers, orders, or sensors. It only understands bytes.

Why serialization exists

Your application works with meaningful data, such as an order with a number, a list of items, and a total. Kafka stores raw bytes and treats them as opaque. A serializer is the small translator that turns your data into bytes before sending. Later, a deserializer on the consumer side turns the bytes back. Both sides must agree on the format.

Common formats

FormatReadable by PeopleSizeSchema Rules
Plain textYesLargerNone
JSONYesLargerOptional
AvroNeeds a toolCompactStrong, with rules for safe change
ProtobufNeeds a toolCompactStrong, with rules for safe change

Schemas keep teams safe

A schema is a written description of an event’s shape, listing its fields and their types. A schema registry is a separate service that stores these descriptions and checks that new versions stay compatible with old ones. Without such a check, a producer team might rename a field, and every consumer relying on the old name would break the next morning.

Simple Analogy

Two people who write letters to each other must agree on the language. A schema registry is the shared dictionary kept in a public place. Before anyone changes a word, they check the dictionary to make sure the other person will still understand.

i
Helpful Note

Choose your format early. Switching later means changing every producer and every consumer at the same time, which is a large and risky project.

5Keys and the Partitioner

Deciding which partition gets each event is one of the producer’s most important jobs.

Three ways of choosing

With a key

The producer runs the key through a fixed calculation that always gives the same partition number for the same key. All events for one customer therefore land in the same partition, in the order they were sent.

Without a key

The producer spreads events across partitions to balance the load. Modern clients fill a batch for one partition before moving on to another, which keeps batches large and efficient.

With an explicit partition or custom rule

The application may name the partition directly, or plug in its own partitioner that follows business rules, for example giving a very large customer several partitions.

flowchart TD
  R["Record to send"] --> Q{"Explicit partition given?"}
  Q -->|"Yes"| X["Use that partition"]
  Q -->|"No"| K{"Does it have a key?"}
  K -->|"Yes"| H["Calculate partition from the key"]
  K -->|"No"| S["Spread across partitions to balance"]
        
FIG 2 — How a producer chooses the partition

Why keys protect order

Kafka guarantees order only inside a single partition. If a customer creates an account, changes the address, and then closes the account, those three events must be read in that order. By using the customer number as the key, all three go to the same partition, and their order is preserved. Events with different keys may be read in any relative order, and that is usually fine.

Simple Analogy

A postal service sends all letters for the same postcode to the same van. The letters for your street are delivered in the order they were sorted. Letters for another postcode use another van and have no ordering relationship with yours.

!
Common Mistake

Using a key with very few distinct values, such as a country code or a true/false flag. Most events then land in a handful of partitions, creating hot partitions while the others sit idle.

6Batching: The Secret of Producer Speed

A producer is fast not because it sends events one by one at lightning speed, but because it sends them together.

What is a batch?

A batch is a small group of records headed for the same partition, sent together in one network request. Sending one thousand events in a single request is far cheaper than sending one thousand separate requests, because the overhead of the network trip is shared.

The two dials

Dial 1

Batch size

The maximum amount of data a batch may hold before it is sent. Larger batches usually mean better throughput.

Dial 2

Linger time

How long the producer may wait for more records to join a batch. A small wait, even a few milliseconds, lets batches fill up.

Dial 3

Buffer memory

The total memory reserved for waiting records. If it fills up, the producer slows or blocks the application.

The trade-off

Waiting a little for a fuller batch adds a tiny delay to each event but greatly improves throughput and compression. If you want the lowest possible delay, use a very short wait, and accept smaller batches and more network requests. If you want maximum throughput, allow a slightly longer wait and larger batches. Most systems choose a small wait of a few milliseconds as a good balance.

Simple Analogy

A shuttle bus can leave the moment one passenger sits down, or it can wait a couple of minutes for more passengers. Leaving immediately means shorter waits for the first passenger, but many half-empty trips. Waiting a little fills the bus and moves more people per trip.

flowchart LR
  R1["Record 1"] --> B["Batch for Partition 0"]
  R2["Record 2"] --> B
  R3["Record 3"] --> B
  B --> T{"Full or linger time reached?"}
  T -->|"Yes"| S["Send batch to leader broker"]
  T -->|"No"| W["Keep waiting for more records"]
        
FIG 3 — A batch is sent when it is full or has waited long enough
i
Helpful Note

When a partition receives events quickly, batches fill and leave at once, so the wait rarely matters. The linger time only comes into play when traffic is light.

7Compression: Sending Less Data

Since batches contain many similar records, they compress very well.

How it works

The producer can compress each batch before sending it. The broker stores the batch in its compressed form, and the consumer unpacks it. This reduces network traffic, disk space, and sometimes even delay, because less data has to travel and be written. Text-based formats like JSON compress especially well because they contain a lot of repetition.

Choosing a method

ApproachSpace SavedProcessor CostBest For
NoneNoneLowestTiny events or already compressed data
Fast methods such as LZ4 or SnappyGoodLowGeneral use with high throughput
Stronger methods such as Zstandard or GzipBestHigherSaving network and disk when processing power is plentiful
Simple Analogy

Vacuum-packing clothes before putting them in a suitcase lets you carry more in one trip. It takes a little effort to pack and unpack, but the savings on luggage space are worth it, especially for a long journey.

!
Common Mistake

Compressing data that is already compressed, such as images or encrypted files. It wastes processor time and saves almost nothing.

8Acknowledgements: How Sure Do You Want to Be?

The most important producer decision is how many confirmations to wait for before calling a write successful.

The three levels

LevelWhat the Producer Waits ForSpeedRisk
ZeroNothing; it sends and moves onFastestEvents can vanish silently
OneThe leader broker has written the eventFastLost if the leader fails before followers copy it
AllEvery in-sync replica has written the eventSlowerLowest risk; survives loss of the leader

Why the “all” level is safer

Each partition has a leader and followers on different brokers. The followers that are fully caught up are called in-sync replicas. When the producer asks for the “all” level, the leader confirms only after every in-sync replica has stored the event. If the leader then crashes, a follower with the complete data takes over, and nothing confirmed is lost.

The minimum in-sync rule

Topics also have a minimum number of in-sync replicas required to accept a write. With three copies and a minimum of two, the topic keeps working when one broker is down, because two copies still confirm each event. If two brokers fail, the topic refuses new writes rather than risk keeping only one copy. Kafka chooses safety over availability here, and the producer receives an error it must handle.

sequenceDiagram
  participant P as Producer
  participant L as Leader Broker
  participant F1 as Follower 1
  participant F2 as Follower 2
  P->>L: Send batch
  L->>L: Append to log
  F1->>L: Fetch new data
  L-->>F1: Return data
  F2->>L: Fetch new data
  L-->>F2: Return data
  L-->>P: Confirm after in-sync replicas have it
        
FIG 4 — A confirmation at the “all” level
Simple Analogy

Sending an important contract by courier, you can accept a verbal “yes, I have it” from the first office, or you can insist that the head office, the bank locker, and the lawyer all confirm they hold a copy. The second way takes longer but guarantees that a single fire cannot destroy the contract.

!
Common Mistake

Using the “all” level but leaving the minimum in-sync count at one. If followers fall behind, the in-sync set may shrink to just the leader, and “all” then quietly means “just the leader”. Pair the two settings sensibly.

9Retries, Timeouts, and Duplicates

Networks and servers are imperfect. A good producer expects trouble and recovers gracefully.

Temporary trouble

Sometimes a broker is briefly unavailable, a leader is changing after a failure, or a network packet is lost. These problems are temporary, and the producer handles them by trying again. Kafka producers retry automatically, within an overall delivery time limit that you can set. If the event still cannot be delivered within that limit, the producer gives up and reports an error to the application.

The duplicate problem

Retries create a subtle danger. Suppose the producer sends a batch, and the broker stores it, but the confirmation is lost on the way back. The producer, seeing no answer, sends the same batch again. Now the partition holds the same events twice. Without protection, retries can cause duplicates.

The reordering problem

There is a second danger. If the producer allows several requests in flight to the same broker at once, and the first fails and is retried while the second succeeds, the events could end up stored in the wrong order. For applications that need strict order, this must be prevented.

The idempotent producer

Kafka’s answer to both dangers is the idempotent producer. When enabled, each producer receives a unique identity and numbers its batches for each partition. The broker remembers the latest numbers it has seen and quietly ignores repeats, and it also uses the numbers to keep batches in the right order even when retries happen. The result is that retries become safe, with no duplicates and no reordering inside a partition. Modern client versions enable this protection by default, and it works together with the strongest confirmation level.

Simple Analogy

A cashier stamps a running number on every receipt. If a customer accidentally hands over the same receipt twice, the cashier notices the number has already been recorded and does not charge again. The numbers also show if receipts arrive in the wrong sequence.

1

Send the numbered batch

The producer sends a batch tagged with its identity and a sequence number.

2

The confirmation is lost

The broker stored the batch, but the network dropped its reply.

3

The producer retries

After waiting, it sends the same batch again with the same sequence number.

4

The broker recognises the repeat

It sees that this sequence number was already stored, ignores the duplicate, and sends back a success reply.

i
Helpful Note

Idempotence protects against duplicates caused by the producer’s own retries within one session. It does not remove duplicates created by your application, such as sending the same business event twice on purpose.

10Sending Without Waiting: Asynchronous Sends

Producers are designed so that your application does not stand around waiting for each event to be confirmed.

Three ways to send

Style 1

Fire and forget

Send the event and ignore the result. Fastest, but failures go unnoticed. Suitable only for data you can afford to lose.

Style 2

Synchronous wait

Send and wait for the reply before continuing. Very safe and simple, but slow, because each event waits for its own round trip.

Style 3

Asynchronous with callback

Send and carry on, while a callback function is called later with the result. The best mix of speed and safety for most systems.

Why callbacks matter

Because sending is asynchronous, the call that hands over the record returns before the event is actually stored. The real result arrives later. If your application never checks that result, failures disappear without a trace. A callback lets the application log the problem, retry in its own way, or raise an alert.

Simple Analogy

Posting a letter and walking away is fire and forget. Standing at the post office until the recipient phones to confirm is a synchronous wait. Posting the letter and asking the post office to call you when it is delivered is the callback style, and it lets you get on with your day.

!
Common Mistake

Treating a quick return from the send call as proof of success. It only means the producer accepted the record into its buffer, not that Kafka stored it.

11Transactions: All or Nothing

Sometimes several writes must succeed together or not at all.

The need

Imagine an application that reads a payment event, updates a balance, and writes two new events: one to a “receipts” topic and one to an “audit” topic. If the application crashes after writing the first but before the second, the system is left in an inconsistent state. What is needed is an all-or-nothing guarantee.

How Kafka transactions help

The producer can begin a transaction, write to several partitions and topics, and then either commit or abort the transaction. If it commits, all the writes become visible together. If it aborts or crashes, none of them become visible to readers who ask for committed data only. Consumers choose whether to read everything, or only events from committed transactions.

Simple Analogy

Think of a bank transfer. Money leaves one account and enters another. Either both steps happen or neither happens. It would be unacceptable for the money to leave and never arrive. A transaction is that promise for events.

Where transactions shine: stream processing

A job that reads from one topic, transforms the events, and writes results to another topic can use transactions so each input event affects the output exactly once, even after failures.

Where they are not needed: simple logging

If an application only sends independent log events, the extra cost and complexity of transactions bring little benefit.

i
Helpful Note

Transactions add some delay and coordination work. Use them when the all-or-nothing guarantee truly matters, not by default for every producer.

12When Things Go Wrong: Common Producer Errors

A dependable application prepares for failure. These are the situations every producer team should understand.

SituationWhat It MeansUsual Response
Leader not availableThe broker leading the partition just failed or movedProducer refreshes its map and retries automatically
Not enough in-sync replicasToo few copies are up to date to accept a safe writeRetry later, alert operators, and check broker health
Record too largeThe event exceeds the allowed message sizeReduce the payload or store the big data elsewhere and send a reference
Buffer fullEvents are created faster than they can be sentSlow the application, add capacity, or increase the buffer carefully
Delivery time exceededRetries used up the allowed timeReport the failure, store the event in a fallback location, and investigate
Authorisation failedThe identity is not allowed to write to the topicFix the access rules; retrying will not help

Retriable and non-retriable errors

Some errors are temporary, and trying again is the right move. Others are permanent, and no number of retries will help, such as a message that is too large or an identity without permission. A good producer retries the first kind automatically and reports the second kind immediately to the application.

flowchart TD
  E["Send fails"] --> Q{"Is the error temporary?"}
  Q -->|"Yes"| R["Retry within the delivery time limit"]
  R --> OK{"Success in time?"}
  OK -->|"Yes"| D["Event stored"]
  OK -->|"No"| F["Report failure to application"]
  Q -->|"No"| F
  F --> H["Log, alert, or store in fallback"]
        
FIG 5 — How a producer reacts to a failed send
Simple Analogy

If a delivery van cannot reach a street because of a temporary roadblock, the driver tries again after a while. If the address does not exist at all, trying again tomorrow will not help, and the driver must return the parcel to the sender.

13Choosing Settings for Your Situation

There is no single perfect configuration. The right choices depend on how precious your events are and how fast they arrive.

Three typical profiles

Profile 1: Maximum safety for critical events

Used for payments, orders, and account changes. Choose the “all” confirmation level, keep the idempotent producer on, use three replicas with a minimum of two in-sync copies, allow generous retry time, and check every result through callbacks.

Profile 2: Maximum throughput for bulk data

Used for large volumes of clicks or logs. Use larger batches, a small wait time, strong but fast compression, and keep confirmations at a level that balances speed with an acceptable risk.

Profile 3: Lowest delay for real-time alerts

Used when each event must move quickly. Use a very short wait time, smaller batches, and a confirmation level suited to how much loss you can tolerate.

Safety
Confirmations, replicas, idempotence
Speed
Batching, compression, buffer size
Delay
Linger time and request timeouts
i
Helpful Note

Test settings with realistic traffic before going live. Benchmarks with tiny events and no failures can give a misleading picture of how a producer behaves on a busy, imperfect day.

14Advantages and Trade-offs of the Producer Design

The way Kafka producers work has clear strengths and clear costs.

Advantages

  • Batching and compression give very high throughput
  • Asynchronous sending keeps applications fast and responsive
  • Idempotence makes retries safe without extra code
  • Adjustable confirmations let each application choose its own balance of speed and safety
  • Keys give ordering where it is needed without giving up parallelism
  • Transactions offer all-or-nothing writes across topics

Disadvantages / Trade-offs

  • Many settings to learn, and wrong choices can silently lose data
  • Asynchronous results must be checked, or failures go unnoticed
  • Strong safety settings add delay and can reduce availability during failures
  • Events buffered in memory are lost if the application crashes before they are sent
  • Order is guaranteed only within a partition, not across the whole topic

The in-memory risk

Events waiting in the producer’s buffer live only in memory. If the application process crashes or is killed before the buffer is sent, those events are gone. This is why applications should shut down gracefully by flushing pending events, and why critical systems sometimes write events to a database first and then publish them, so nothing is lost between the business action and Kafka.

15Security and Monitoring for Producers

A producer carries valuable business facts, so it must connect safely and be watched closely.

Connecting safely

Producers can use encrypted connections so that nobody watching the network can read the events. They can prove their identity to brokers through certificates or through a username and secret, which is called authentication. Brokers can then check rules about which identities may write to which topics, which is called authorisation. A well-run company gives each application its own identity, allows it to write only to the topics it needs, and stores passwords and certificates in a proper secrets system rather than inside the program.

Simple Analogy

A courier depot uses sealed vans, checks each driver’s identity card at the gate, and gives each driver keys that open only the loading bays they are permitted to use.

What to watch

Errors
Failed sends and retries per second
Latency
Time from send to confirmation
Buffer
How full the waiting area is

Also watch the average batch size, which reveals whether batching is working, and the compression ratio, which shows how much space is saved. A steadily full buffer means events are created faster than the cluster accepts them. A rising retry rate points to unstable networks or overloaded brokers. Alert on error rates and delivery failures, not only on averages, so small problems are fixed before customers notice.

i
Helpful Note

Give each producer a clear identity name. When something goes wrong, being able to tell exactly which application sent which traffic saves hours of guessing.

16Anti-Patterns to Avoid

Most producer problems repeat across companies. Learn them once and avoid them forever.

ANTI-PATTERN-01 Avoid
Problem

Creating a brand-new producer for every single event.

Why It’s Harmful

Each new producer opens connections, fetches cluster metadata, and starts with empty buffers. This wastes time, burdens the brokers, and destroys batching.

Correct Approach

Create one producer at application startup, share it safely across the application, and close it only when the application shuts down.

ANTI-PATTERN-02 Avoid
Problem

Ignoring the result of sends and assuming they all succeed.

Why It’s Harmful

Sends are asynchronous, so a failure arrives later. If nobody checks, events are lost without any sign.

Correct Approach

Always handle results through callbacks or result objects, log failures, and decide on a fallback or alert.

ANTI-PATTERN-03 Avoid
Problem

Waiting for each send to complete before sending the next, in a loop.

Why It’s Harmful

Every event pays a full network round trip. Batching is defeated, and throughput collapses.

Correct Approach

Send asynchronously, let batches fill, and check results through callbacks or by waiting on many results at once.

ANTI-PATTERN-04 Avoid
Problem

Stopping the application abruptly without flushing the producer.

Why It’s Harmful

Events waiting in the buffer are lost, even though the application believed they were sent.

Correct Approach

On shutdown, flush pending events and close the producer cleanly, giving it time to finish.

ANTI-PATTERN-05 Avoid
Problem

Sending related events with different keys, or with no key, and then expecting them to be read in order.

Why It’s Harmful

Events in different partitions have no ordering relationship, so a later event may be read before an earlier one.

Correct Approach

Use the same key for all events about one business object, such as an order number, so they share a partition.

17Best Practices at a Glance

A short checklist keeps your producers healthy.

Habit 1

One shared producer

Create it once, reuse it everywhere, and close it cleanly at shutdown.

Habit 2

Safe settings for important data

Full confirmation, idempotence on, and sensible replicas with a minimum in-sync count.

Habit 3

Choose keys deliberately

Use an identity with many evenly spread values that groups events needing order.

Habit 4

Handle every result

Log failures, alert on them, and decide what happens to events that cannot be delivered.

Habit 5

Agree on schemas

Use shared, versioned descriptions of events so changes never break readers.

Habit 6

Tune batching with real traffic

Measure batch sizes and delay, then adjust wait time and batch size to fit.

Habit 7

Keep events small and clear

Send only what readers need, and store large files elsewhere with a reference in the event.

Habit 8

Monitor continuously

Watch errors, retries, latency, and buffer fullness, and alert early.

“A good producer is fast because it batches, safe because it confirms, and honest because it reports every failure.”

18A Real-World Walk-Through

Let us see a producer at work in an online shop during a busy sale.

1

A customer clicks “Buy”

The order service saves the order in its database and prepares an order event with the customer number as key.

2

The shared producer accepts it

The order service hands the event to its single, long-lived producer, which returns immediately so the customer’s page loads quickly.

3

Serialization and partitioning

The event is turned into compact bytes using the agreed schema, and the key sends it to the same partition as all earlier events from this customer.

4

Batching under load

During the sale, thousands of events arrive each second. Batches fill instantly, compress well, and leave for the brokers in efficient groups.

5

A broker fails mid-sale

One broker crashes. The producer’s next sends to its partitions fail temporarily, the producer refreshes its cluster map, finds the new leaders, and retries. Idempotence prevents duplicates.

6

Callbacks confirm the results

Each successful send triggers a callback that records the partition and offset. Any permanent failure is logged and raises an alert.

7

Readers react independently

The email, fraud, and warehouse services each read the same event at their own pace. The producer neither knows nor cares.

flowchart LR
  C["Customer Clicks Buy"] --> OS["Order Service"]
  OS --> PR["Shared Producer"]
  PR --> K["Kafka Cluster: orders topic"]
  K --> EM["Email Service"]
  K --> FR["Fraud Service"]
  K --> WH["Warehouse Service"]
  PR --> CB["Callback: log result or alert on failure"]
        
FIG 6 — One producer feeding many independent readers

19Frequently Asked Questions

Q1What is a Kafka producer in one sentence?

A producer is the client that writes events into Kafka topics, handling serialization, partition choice, batching, delivery, and retries on the application’s behalf.

Q2Does the producer need to know which consumers will read the data?

No. Producers and consumers are completely separate. The producer only writes to a topic, and any number of consumer groups can read it later.

Q3How does a producer know which broker to send to?

It starts with a few bootstrap broker addresses and asks for the cluster map, called metadata. The map tells it which broker leads each partition, so it sends each batch straight to the right leader.

Q4Can a producer lose events?

Yes, if configured carelessly. Using no confirmations, ignoring send results, or crashing before the buffer is flushed can all lose events. With full confirmations, idempotence, replication, and proper result handling, loss becomes very unlikely.

Q5Why do I sometimes see duplicate events?

Retries after a lost confirmation can store the same batch twice if idempotence is off. Enable the idempotent producer, and also make consumers safe against seeing an event twice.

Q6What happens if I send without a key?

The producer spreads events across partitions to balance the load. There is no ordering guarantee between those events.

Q7Should I create one producer per event or one for the whole application?

One for the whole application, or a small number when needed. Creating a producer for every event is slow and wasteful, and it defeats batching.

Q8Is sending synchronous or asynchronous?

By default, sending is asynchronous. The call returns once the record is accepted into the buffer, and the real result arrives later through a callback or result object. You may choose to wait for the result, though this reduces throughput.

Q9When should I use transactions?

Use them when several writes, often across topics, must succeed together or not at all, such as in stream processing that reads, transforms, and writes results. For independent events, they are usually unnecessary.

Q10Does the producer store my data permanently?

No. It holds events only briefly in memory before sending them. The durable, replicated copy is stored by the brokers.

20Summary and Key Takeaways

We began with a courier company that checks labels, sorts parcels into sacks, waits for receipts, and retries when roads are closed. A Kafka producer does the same for your events. It serializes each record, chooses a partition using the key, gathers records into batches, optionally compresses them, sends them to the partition leader, and waits for the confirmations you asked for. Idempotence protects against duplicates and reordering during retries, callbacks report the real outcome, and transactions offer all-or-nothing writes when needed. The producer’s power comes from a handful of choices: how sure you want to be, how fast you want to go, and how carefully you handle failures. Choose them deliberately, monitor them continuously, and your events will travel safely from your application into Kafka.

Key Takeaways

  • A producer writes events to Kafka — it never knows or cares who reads them, which keeps systems loosely connected.
  • Each send passes through several steps — serialization, partition choice, batching, and delivery by a background sender, all hidden behind one simple call.
  • Keys protect order — events with the same key share a partition and stay in sequence, while different keys spread the load.
  • Batching and compression create speed — a small wait lets batches fill, cutting network trips and saving space.
  • Confirmations set your safety level — waiting for all in-sync replicas, together with a sensible minimum, is the safest choice for important data.
  • Idempotence makes retries safe — it prevents duplicates and reordering within a partition, and transactions add all-or-nothing writes across topics.
  • Always check results and shut down cleanly — sends are asynchronous, so handle callbacks, flush the buffer on exit, and monitor errors, latency, and buffer fullness.