Encryption in Transit (TLS) in Kafka

Encryption in Transit (TLS) in Kafka

A beginner-friendly guide to how Kafka protects messages while they travel across the network: what TLS is, how certificates and trust work, how brokers and clients are set up, and how to run it safely in production.

Imagine sending a postcard through the mail. Everyone who handles it, the sorter, the driver, the neighbour who collects it by mistake, can read every word. Now imagine putting the same message inside a sealed, tamper-proof envelope that only the intended reader can open, and having the receiver show identification before you hand it over. The message is the same, but the journey has become safe. Kafka, by default, sends its messages like postcards. Anyone who can watch the network between an application and a Kafka server can read the data, and even change it. TLS is the sealed envelope and the identification check. This guide explains it step by step from zero, so you can follow it even if you have never worked with encryption before.

1The Problem: Data Travelling in the Open

Before learning the solution, let us understand exactly what can go wrong when Kafka traffic is not protected.

Kafka in one paragraph

Apache Kafka moves streams of messages between applications. Applications that write messages are producers, applications that read them are consumers, and the Kafka servers that store and deliver messages are brokers. Brokers also talk to each other constantly to copy data, and to the management part of the cluster. All of this talking happens over network connections, and that is where the risk lives.

What an attacker on the network can do

Eavesdropping

Anyone who can see the network traffic, for example through a compromised machine, a shared network or a misconfigured cloud setting, can read messages as plain text. Customer names, payment details, health records and passwords inside messages become visible.

Tampering

A person in the middle of the connection can change messages while they travel. An amount can be altered, a command can be inserted, and neither the sender nor the receiver notices.

Impersonation

Without proof of identity, a malicious machine can pretend to be a Kafka broker and collect data from applications that trust it, or pretend to be a legitimate client and read data it should never see.

Simple Analogy

An unprotected Kafka network is like a busy corridor in an office where people carry open folders. Anyone walking past can read the papers, slip in a page, or wear a fake badge and take a folder. Protecting the corridor means locked briefcases, sealed pages and badge checks.

Why this matters more than you might think

Many teams believe that “our network is private, so we are safe.” Private networks are still full of servers, contractors, monitoring tools and cloud components. One compromised machine inside the network is enough to see everything. Rules and laws about protecting personal and financial data also often require encryption whenever data moves across a network, even an internal one. Encrypting Kafka traffic is therefore both a technical and a compliance need.

!
Common Misconception

“Internal traffic does not need encryption.” In practice, attackers who get a foothold inside a network look first for unencrypted internal traffic, because it is the easiest thing to read.

2What Is TLS?

TLS is the standard technology that protects data moving between two computers. You use it every day when you visit a website whose address starts with https.

A short history and a naming quirk

TLS stands for Transport Layer Security. It is the modern successor of an older technology called SSL, or Secure Sockets Layer. The old SSL versions are now considered unsafe and should not be used. Yet the old name stuck around in many places. In Kafka, the settings are still named with “ssl” in front, and the connection type is still called SSL, even though what is really used today is TLS. When you see “SSL” in Kafka, read it as “TLS.”

i
Naming Tip

In Kafka documentation and settings, “SSL” is just a historical label. Modern Kafka setups should use TLS versions, and the old SSL versions should be disabled.

The three promises of TLS

Promise 1

Confidentiality

Data is scrambled during travel, so anyone watching the network sees only unreadable noise.

Promise 2

Integrity

Any change to the data in transit is detected. Tampered messages are rejected instead of being accepted silently.

Promise 3

Authentication

The client can be sure it is talking to the real server. Optionally, the server can also be sure of the client’s identity.

Simple Analogy

TLS is like a sealed armoured van with a verified driver. Confidentiality is the closed van, so nobody sees the cargo. Integrity is the seal, which shows if anyone tampered. Authentication is the driver’s ID card, which proves who is at the wheel.

What TLS does not do

TLS protects data only while it moves between two ends. It does not protect data once it arrives and is written to a disk. It also does not decide what a user is allowed to do. Those are separate jobs: encryption at rest and access control. We will return to this difference later, because mixing them up is a common source of false confidence.

3The Building Blocks: Keys, Certificates and Trust

TLS rests on a few ideas. Once you understand them, every setting in Kafka becomes easy to place.

Term 1

Private key

A secret value that belongs to one server or client. It must never be shared. It is used to prove identity.

Term 2

Public key

The matching value that can be shared with anyone. It can check things that only the private key could have done.

Term 3

Certificate

A digital identity card. It holds a public key, the name of the owner, the validity dates and a signature from an issuer.

Term 4

Certificate Authority (CA)

A trusted organisation that signs certificates, vouching that the certificate really belongs to the named owner.

Simple Analogy

A certificate is like a passport. It shows your name and photo (the public key), it has an expiry date, and it carries an official stamp from the government (the Certificate Authority). A border officer does not know you personally, but trusts the government stamp. In the same way, a client trusts a broker because a Certificate Authority it trusts has signed the broker’s certificate.

The chain of trust

Certificates are usually issued in chains. A root authority signs the certificate of an intermediate authority, and the intermediate signs the certificate of your broker. When a client receives a broker’s certificate, it follows the chain upward until it reaches a root that it already trusts. If the chain leads to a trusted root and every signature and date checks out, the client accepts the certificate.

flowchart TD
    R[Root Certificate Authority - trusted by the client] --> I[Intermediate Certificate Authority]
    I --> B[Broker certificate]
    B --> V{Client checks: signature, dates, name}
    V -- All good --> T[Trusted connection]
    V -- Any failure --> X[Connection rejected]
        
FIG 1 — How a client decides to trust a broker’s certificate

Self-signed versus properly issued certificates

Self-signed certificates

A certificate that vouches for itself, with no outside authority. It is easy to create and useful for quick tests, but every client must be told to trust each one individually, which is hard to manage and easy to get wrong.

Certificates from a company or public authority

Certificates signed by an authority that all your machines already trust. Clients only need to trust the authority once, and new brokers can be added without touching every client. This is the sensible choice for production.

i
Good Practice

Set up a proper internal Certificate Authority, or use your organisation’s existing one, from the start. Moving from self-signed test certificates to a real authority later is possible but painful.

4Keystores and Truststores

Kafka needs a place to keep its own identity and a place to keep the list of identities it trusts. These are two separate files.

Keystore: “who am I?”

A keystore is a protected file that holds your own private key and your own certificate, along with the chain of authorities that signed it. A broker uses its keystore to prove its identity to clients. A client uses its keystore only when it needs to prove its identity to the broker, which is the mutual authentication case we will discuss soon.

Truststore: “whom do I trust?”

A truststore is a protected file that holds the certificates of the authorities you trust. When someone presents a certificate, you check whether it was signed by an authority in your truststore. Clients need a truststore to trust the brokers. Brokers need a truststore to trust each other, and to trust clients when client certificates are required.

AspectKeystoreTruststore
Answers the questionWho am I?Whom do I trust?
ContainsMy private key and my certificate chainCertificates of trusted authorities
SensitivityVery high, holds a private keyLower, holds only public certificates
Needed by brokersAlways when TLS is onAlways for inter-broker trust, and for client certificates
Needed by clientsOnly for mutual authenticationUsually, to trust the brokers
Simple Analogy

The keystore is your own wallet with your passport inside. The truststore is a list at the border desk of which countries’ passports are accepted. You show your passport from your wallet, and the officer checks it against the list.

File formats

These stores come in several formats. The two classic ones are the Java-specific JKS format and the widely used PKCS12 format. Newer Kafka versions can also read certificates and keys directly from PEM files, the plain text format that many non-Java tools use. Which format you choose depends on your tooling and your Kafka version, but the ideas are identical.

!
Common Mistake

Putting a private key into a truststore, or sharing the keystore file between many machines. Each broker should have its own key and certificate, and private keys should never be copied around casually.

Protect the files and their passwords

Keystores are usually protected by passwords, and those passwords appear in configuration. Restrict file permissions so that only the Kafka process can read the keystore, and avoid leaving passwords in plain text in shared repositories or tickets. Kafka supports supplying secret values through safer mechanisms, such as external secret providers and encrypted dynamic configuration, and using them is strongly recommended.

5The TLS Handshake, Step by Step

Before any Kafka message is sent, the two sides perform a short ritual called the handshake. It sets up trust and a shared secret key.

sequenceDiagram
    participant C as Client
    participant B as Broker
    C->>B: Hello, these are the TLS versions and ciphers I support
    B-->>C: Hello, I choose this version and cipher, here is my certificate
    C->>C: Verify certificate chain, dates and hostname
    C->>B: Key exchange material
    B-->>C: Confirm, secure channel ready
    C->>B: Encrypted Kafka requests
    B-->>C: Encrypted Kafka responses
        
FIG 2 — A simplified view of the TLS handshake between a Kafka client and a broker
1

The client introduces itself

It lists the TLS versions and the encryption methods, called cipher suites, that it can use.

2

The broker picks and shows its identity

It chooses the best version and cipher suite that both sides support, and sends its certificate.

3

The client verifies the broker

It checks that the certificate chain leads to a trusted authority, that it has not expired, and that it matches the broker’s name.

4

Both sides agree on a shared secret

Using clever mathematics, the two sides create a secret key that only they know, without ever sending it directly across the network.

5

The secure channel opens

From now on, every Kafka request and response is encrypted with the shared key and protected against tampering.

Simple Analogy

The handshake is like two strangers meeting in a busy square who need to agree on a private code. They first show official ID to prove who they are, then use a clever trick to agree on a secret word that nobody watching could work out. After that, they whisper in code.

Handshake cost and connection reuse

The handshake takes a little time and processor power. Kafka clients keep connections open for a long time and reuse them for many requests, so the handshake cost is paid rarely and spread over a huge number of messages. Problems appear only when clients open and close connections constantly, which can happen with badly written applications or misconfigured tools.

i
Good to Know

Newer TLS versions shorten the handshake, and they remove old weak features. This is one reason to prefer the newest TLS version that your Java and Kafka versions support.

6Where TLS Applies Inside a Kafka System

A Kafka system has many network connections. To be truly protected, every important path needs encryption, not just one.

flowchart LR
    P[Producers] -->|Client to broker| B1[Broker 1]
    C[Consumers] -->|Client to broker| B2[Broker 2]
    B1 |Broker to broker replication| B2
    B1 |Broker to controller| K[Controllers]
    B2 |Broker to controller| K
    KC[Kafka Connect] -->|Client to broker| B1
    SR[Schema Registry] -->|Client to broker| B2
    A[Admin tools] -->|Client to broker| B1
        
FIG 3 — The main network paths in a Kafka system that should be protected
Path 1

Client to broker

Producers, consumers, stream applications, connectors and admin tools all talk to brokers. This is the path most people think of first.

Path 2

Broker to broker

Followers copy data from leaders over the network. If this path is unencrypted, every message is exposed again during replication.

Path 3

Broker and controller

The management part of the cluster exchanges metadata with brokers. Newer clusters use a built-in controller quorum, and older ones used an external coordination service. Both paths should be protected.

Path 4

Supporting services

Web interfaces of Kafka Connect and a schema registry, and monitoring endpoints, also carry sensitive information and should use encrypted connections.

Simple Analogy

Locking the front door of a house while leaving the back door and the windows open does not make the house secure. Encrypting only client connections while leaving broker replication open leaves an equally easy way in.

!
Common Mistake

Enabling TLS for applications but forgetting the connection between brokers. Every message is copied between brokers at least once, so this path carries the same sensitive data and needs the same protection.

7Listeners and Security Protocols

A Kafka broker can listen for connections in several ways at the same time. Each way is called a listener, and each has its own security choice.

What is a listener?

A listener is a combination of a name, a network address and a port on which a broker accepts connections, together with the security protocol used on it. A broker can have several listeners, for example one for internal traffic and another for external applications. This lets you apply different rules to different groups of users.

The four security protocols

ProtocolEncrypted?Users identified?Typical use
PLAINTEXTNoNoLocal experiments only
SSL (meaning TLS)YesOptionally, through client certificatesEncrypted traffic, optionally with certificate-based identity
SASL_PLAINTEXTNoYes, through a login mechanismRarely recommended, because credentials travel unprotected
SASL_SSLYesYes, through a login mechanismEncrypted traffic with username-style identity
Simple Analogy

Think of four kinds of doors at a building. One has no lock at all. One has a lock that hides what is inside the corridor. One has a receptionist who checks names, but the conversation is overheard. One has both the sealed corridor and the receptionist. Only the last two combine privacy and identity properly.

Advertised addresses

When a client first connects to a broker, the broker tells it the addresses of all brokers to use next. These are the advertised addresses. They may differ from the addresses the broker actually listens on, for example when a load balancer or a container network is involved. This matters for TLS because the client will check the certificate against the advertised name. If the name in the certificate does not match the advertised name, the connection is refused.

i
Practical Tip

Decide the advertised names of your brokers first, and only then issue their certificates. Certificates that were issued for the wrong names are one of the most common reasons why a first TLS setup fails.

The inter-broker listener

Brokers also need to choose which listener they use to talk to each other. This is a separate setting, and it should always point to an encrypted option. Keeping a dedicated internal listener for broker traffic, separate from the one used by outside applications, is a common and tidy design.

8Broker Configuration: The Main Ideas

You do not need to memorise every setting. It is enough to know the handful of groups and what each one is for.

Group 1

Listeners and protocol mapping

Declare which listeners exist, their addresses, and which security protocol each name uses. Also set the advertised addresses.

Group 2

Keystore settings

The location, type and passwords of the file holding the broker’s own key and certificate.

Group 3

Truststore settings

The location, type and password of the file holding the authorities that the broker trusts.

Group 4

Client authentication mode

Whether clients must present certificates: not asked, asked but optional, or required.

Group 5

Protocols and ciphers

Which TLS versions and which cipher suites are allowed. Restrict to modern and strong choices.

Group 6

Endpoint identification

Whether names in certificates are checked against the addresses used. This protects against impersonation.

Per-listener settings

When a broker has several listeners, you can give each listener its own keystore and its own TLS settings, by adding the listener name to the setting. This is useful when the internal listener should use certificates from an internal authority, while the external listener uses certificates from a public one.

Changing certificates without stopping the broker

Modern Kafka versions allow the keystore and truststore of a listener to be updated while the broker is running, using its dynamic configuration feature. This is very valuable when certificates need to be renewed, because it avoids restarting every broker. Even so, you should test the process in a non-production cluster first, and check the exact supported behaviour for your version.

1

Plan names and listeners

Decide broker names, listener names and which listeners will be encrypted.

2

Create keys and request certificates

Generate a key for each broker and get certificates signed by your authority, with the correct names inside.

3

Build keystores and truststores

Place each broker’s key and certificate chain into its keystore, and the trusted authorities into the truststore.

4

Apply broker settings and restart carefully

Update the settings, and restart the brokers one at a time so the cluster stays available.

5

Verify from a client

Connect with a test client and confirm that the handshake works and the certificate names are correct.

!
Common Mistake

Changing all brokers at once. If a setting is wrong, every broker fails together and the cluster goes down. Always roll changes out one broker at a time and verify after each.

9Client Configuration: Producers, Consumers and Others

Every application that talks to a TLS-enabled Kafka needs a few settings too.

What a client must be told

Use the encrypted protocol

The client must be told to use the SSL or SASL_SSL protocol, and to connect to the encrypted listener’s address and port. Connecting to the wrong port is the classic first mistake.

Trust the brokers’ authority

The client needs a truststore, or a file with authority certificates, that contains the authority which signed the brokers’ certificates. Without it, the client will reject the brokers.

Provide its own identity if required

If brokers require client certificates, the client also needs a keystore with its own key and certificate.

The same ideas everywhere

Producers, consumers, admin tools, stream applications, connectors and the schema registry are all Kafka clients underneath, so they use the same kinds of settings. Non-Java clients, such as those written in other languages, usually work with plain certificate and key files in the PEM format instead of Java-style stores, and name their settings a little differently, but the concepts of trusting an authority, presenting an identity and choosing the encrypted protocol are the same.

Client typeNeeds truststore?Needs keystore?Notes
Producer or consumer, one-way TLSYesNoOnly trusts the brokers
Producer or consumer, mutual TLSYesYesAlso proves its own identity
Kafka Connect and streams applicationsYesDependsClient settings are passed through with a prefix for each role
Admin and command line toolsYesDependsRead settings from a small configuration file
Simple Analogy

Every visitor to a secure building needs to know which entrance to use, must recognise the official guard uniform, and, in high-security buildings, must carry their own badge. The client’s settings tell it exactly these three things.

i
Practical Tip

Create a small, shared, well-tested client configuration template for your organisation. Teams then copy a known-good file instead of inventing their own, and most connection problems disappear.

10One-Way TLS versus Mutual TLS

TLS can prove the identity of just the server, or of both sides. The choice changes how you manage identities.

One-way TLS

In the common one-way setup, only the broker proves its identity. The client checks the broker’s certificate, but the broker does not ask the client for one. The connection is encrypted and clients know they are talking to a real broker, but the broker does not learn who the client is from TLS alone. If you need to know who each client is, you add another mechanism, such as a username and password login, on top.

Mutual TLS

In mutual TLS, often written mTLS, both sides show certificates. The broker asks the client for a certificate, verifies it against its truststore, and uses the name inside as the identity of the client. This gives strong, certificate-based identity, and it is popular in environments with automated certificate management.

Advantages of mutual TLS

  • Strong identity based on cryptographic keys, not shared passwords
  • No separate login system needed for clients
  • Identity is checked during the handshake itself
  • Works well with automatic certificate issuing tools

Trade-offs

  • Every client needs its own certificate and key
  • Renewing many client certificates is real operational work
  • Certificate names must be planned so they map cleanly to identities
  • Mistakes are harder to debug than a simple password problem

How Kafka uses the certificate name

When a client presents a certificate, Kafka takes the distinguished name inside it, a structured description including the common name and organisation, and turns it into a principal, the identity used for authorisation. Rules can be configured to shorten or reshape this name into something friendlier. Access rules called ACLs then refer to that principal to decide what the client may read or write.

flowchart LR
    A[Client presents certificate] --> B[Broker verifies against truststore]
    B --> C[Broker reads name from certificate]
    C --> D[Name mapped to a principal]
    D --> E[Access rules decide what the principal may do]
        
FIG 4 — How a client certificate becomes an identity used for permissions
Simple Analogy

One-way TLS is like a visitor checking the security guard’s identity but walking in anonymously. Mutual TLS is like both the visitor and the guard showing ID at the door, so the building knows exactly who has entered.

!
Common Mistake

Turning on mutual TLS and forgetting to define access rules. Encryption and identity tell Kafka who is calling, but permissions decide what they may do. Without access rules, the identity has no effect on what clients can access.

11Hostname Verification and Certificate Names

A trusted certificate is not enough. The certificate must also belong to the machine you meant to reach.

Why names matter

Imagine that an attacker obtains a genuine certificate for their own server, signed by a perfectly trusted authority. If clients only checked the signature, they would accept the attacker’s server as a Kafka broker. To prevent this, clients also check that the name inside the certificate matches the address they connected to. This check is called hostname verification or endpoint identification, and modern Kafka clients enable it by default.

Simple Analogy

A passport may be real, but the officer still compares the photo with your face. A real certificate for the wrong name is like a real passport belonging to someone else. Hostname verification is the face check.

Subject Alternative Names

Certificates list the names they are valid for in a field called Subject Alternative Name, or SAN. A broker’s certificate should list every name and address by which clients may reach it, including its advertised names. Modern verification relies on this field, so a certificate that only has a name in the older common name field may be rejected.

Include

The advertised host name

The name that clients are told to use when they connect to this broker.

Include

Alternative names in use

Any load balancer names, internal aliases or container service names that clients may use.

Consider

IP addresses only if needed

If clients connect by address instead of name, the address must appear in the certificate too.

Avoid

Sharing one certificate across all brokers without a reason

A shared certificate widens the damage if its key leaks, and makes rotation harder to do safely.

!
Common Mistake

Turning off hostname verification to “make the error go away.” It removes the protection against impersonation. Fix the certificate names instead.

12TLS Versions and Cipher Suites

Not all encryption is equally strong. Choosing the versions and methods that are allowed is an important part of the setup.

Protocol versions

TLS has gone through several versions. The oldest ones, and the SSL versions before them, have known weaknesses and must be switched off. Modern deployments allow only the newer versions. Kafka lets you list exactly which versions are enabled. The newest version brings a faster handshake and removes many old and risky features, but it needs a recent enough Java runtime and Kafka release, so check what your environment supports. A sensible rule is to allow the newest versions that all your clients can handle, and to disable everything older.

Cipher suites

A cipher suite is a named bundle of the methods used during a connection: how keys are agreed, how data is encrypted and how integrity is checked. During the handshake, the two sides pick one that both support. If you leave the list to defaults, Kafka and Java choose reasonable options for their versions. If you set a list yourself, prefer modern suites that offer forward secrecy and authenticated encryption, and remove old ones.

Simple Analogy

A cipher suite is like a choice of lock and key system for a safe. Old locks can be picked by anyone with modern tools. Choosing the current lock model is the difference between real protection and false comfort.

Concept

Forward secrecy

Each connection uses fresh temporary keys. If a server’s long-term private key is stolen later, old recorded traffic still cannot be decrypted.

Concept

Authenticated encryption

Encryption and tamper detection are combined in one step, which is both safer and usually faster.

Concept

Key size and type

Certificates should use keys of a currently recommended strength. Older, shorter keys should be replaced.

Compatibility versus strength

Tightening the allowed versions and suites improves security but may lock out very old clients. Before restricting settings in production, find out which client versions really connect to your brokers, using logs and inventories, and plan upgrades for those that cannot cope. A well-planned tightening is a one-time effort. A surprise lock-out of an important application is an outage.

i
Practical Tip

Follow your organisation’s security standard or a well-known public recommendation for TLS settings, and review it once a year. Recommendations change as new weaknesses are found.

13TLS, Login and Permissions: Three Different Jobs

Security has several layers. TLS is only one of them, and it is easy to confuse it with the others.

LayerQuestion it answersKafka mechanism
Encryption in transitCan anyone read or change data on the network?TLS
AuthenticationWho is connecting?Client certificates through mutual TLS, or a login mechanism such as SASL
AuthorisationWhat is this identity allowed to do?Access control lists
Encryption at restCan someone read data by stealing a disk?Disk or volume encryption, or application-level encryption
Simple Analogy

Think of a bank. The armoured van protects money on the road (encryption in transit). The guard checks your ID at the door (authentication). The teller decides which accounts you may touch (authorisation). The vault protects the money at night (encryption at rest). Each layer is needed, and none replaces another.

TLS with SASL

Many organisations prefer usernames and secrets, or single sign-on tickets, for client identity, and use TLS only to encrypt. That is the SASL_SSL combination: TLS wraps the connection, and SASL performs the login inside it. This is very common, and it explains why the encrypted-with-login protocol is so widely used. Using a login mechanism without TLS underneath is dangerous, because credentials may be exposed on the network.

Choosing between certificate identity and login identity

Choose certificate identity when

You already have automated certificate issuing and renewal, you want strong keys instead of shared secrets, and you can manage many client certificates.

Choose login identity when

You already have an identity system for users and services, you want easy rotation of secrets, or you would rather not deploy certificates to every client.

!
Common Mistake

Believing that “we turned on TLS, so Kafka is secure.” TLS alone leaves permissions open. Any client that can connect may be able to read or write every topic unless access rules are also in place.

14What TLS Does Not Protect: Data at Rest

TLS ends at the broker. Once a message arrives and is written to disk, TLS has done its job and the message is stored as it is.

Encryption stops at the door

TLS is hop-by-hop. A producer encrypts to the broker, the broker decrypts, stores the message on disk in readable form, and later encrypts again when sending to a consumer. Anyone with access to the disk, a backup or the broker’s memory can read stored messages, regardless of TLS. Administrators of the machines can, in principle, read the data too.

flowchart LR
    P[Producer] -->|Encrypted by TLS| B[Broker]
    B --> D[(Disk - readable unless separately encrypted)]
    B -->|Encrypted by TLS| C[Consumer]
        
FIG 5 — TLS protects the two journeys, not the stored data

Options for protecting stored data

Option 1

Disk or volume encryption

Encrypts everything on the disk transparently. It protects against stolen disks and backups, but not against people who can log into a running broker.

Option 2

Application-level encryption

The producer encrypts the sensitive fields, or the whole message, before sending, and only the consumer decrypts. Even brokers and administrators see only scrambled data.

Option 3

Field masking or tokenisation

Replace the most sensitive values with harmless tokens before they enter Kafka, and keep the real values in a separate protected system.

Simple Analogy

TLS is the armoured van. At the bank, the van’s job is over, and the cash is carried into the building. Whether it is safe now depends on the vault, the guards and the locked drawers, which are separate systems.

i
Good Practice

Ask a simple question for every sensitive field: who could read this if they stole a disk, or if they logged into a broker? If the answer is uncomfortable, add protection beyond TLS.

15The Cost of Encryption: Performance

Protecting data is not free. The good news is that the cost is usually manageable, if you understand where it comes from.

Where the cost comes from

Encrypting and decrypting every byte

Both sides spend processor time scrambling and unscrambling data. Modern processors have built-in hardware help for common ciphers, which makes this cheaper than it used to be.

Loss of the zero-copy shortcut

Without encryption, Kafka can hand data directly from disk to the network card without passing through the application’s memory, a very efficient trick called zero-copy. With TLS, data must be encrypted in the broker’s own memory first, so the shortcut is no longer possible for encrypted connections. This raises processor use on brokers, especially for busy consumers.

Handshakes

Every new connection needs a handshake. With long-lived connections this is negligible, but with many short-lived connections it adds up.

Simple Analogy

Zero-copy is like a conveyor belt that carries parcels straight from the warehouse shelf to the truck. Encryption means every parcel must first go through the sealing desk, so a clerk handles each one. The sealing desk is worth it for valuables, but it needs staff.

Ways to keep the cost under control

1

Use a recent Java runtime and TLS version

Newer runtimes and protocol versions have faster, hardware-assisted cryptography and shorter handshakes.

2

Reuse connections

Make sure clients keep connections open, and avoid applications that create a new producer or consumer for every message.

3

Use larger batches and compression

Fewer, larger, compressed requests mean less encryption work per message.

4

Plan capacity with TLS in mind

Test throughput and processor use with TLS enabled before choosing broker sizes, instead of extrapolating from unencrypted tests.

5

Watch processor use after enabling TLS

Compare before and after, and add capacity if needed, rather than turning encryption off.

!
Common Mistake

Deciding against TLS because of a fear of slowness, without measuring. For most workloads, the extra cost is a moderate increase in processor use, which is a small price for the protection gained.

16Certificate Lifecycle: Expiry, Renewal and Rotation

Certificates expire on purpose. Managing that expiry is the most important day-to-day duty of running TLS.

Why certificates expire

Every certificate has a start date and an end date. This limits the damage if a key is stolen, and forces regular renewal with fresh keys and up-to-date algorithms. But it also creates a risk: on the end date, an expired certificate is rejected, and connections start failing, sometimes across the whole cluster at the same moment.

Simple Analogy

A certificate is like a passport with an expiry date. Nobody remembers to renew a passport until the airport refuses to let them board. Certificate expiry is the same surprise, only it affects a hundred applications at once.

What a healthy lifecycle looks like

Step

Inventory

Know every certificate in your Kafka system, who owns it, where it lives and when it expires.

Step

Monitor

Check expiry dates automatically from outside, and alert weeks before the deadline.

Step

Renew early

Renew well before expiry, leaving time to spot and fix problems without a crisis.

Step

Rotate safely

Deploy new certificates one broker at a time, using dynamic reloading where supported.

Step

Automate

Use tooling that issues and renews certificates automatically, so human memory is not the safety net.

Step

Revoke and replace on compromise

Have a written plan for replacing keys quickly if one is exposed.

Rotating the authority itself

Sometimes not only the certificates but the signing authority must change, for instance when its own certificate expires. During such a change, truststores must hold both the old and the new authority for a while, so that certificates from either are accepted. The order matters: first add the new authority to all truststores, then issue certificates from it, and only later remove the old one.

ANTI-PATTERN-01 Avoid
Problem

Issuing certificates with very long lifetimes, and keeping no record of their expiry dates, so nobody has to think about renewal for years.

Why It’s Harmful

When the end date finally arrives, nobody remembers how the certificates were made. A stolen key remains useful to an attacker for years in the meantime.

Correct Approach

Use moderate lifetimes, automate renewal, monitor expiry and practise rotation regularly, so it becomes routine.

17Moving a Live Cluster From Plaintext to TLS

Most clusters start unencrypted. Moving them to TLS without an outage needs a careful, staged plan.

The key idea is that a broker can listen on several listeners at once. You add an encrypted listener next to the existing plaintext one, move clients over gradually, and only then remove the plaintext option. Nobody is forced to switch at the same moment.

flowchart TD
    A[Start: plaintext only] --> B[Add encrypted listener to each broker, one at a time]
    B --> C[Verify encrypted listener with a test client]
    C --> D[Move brokers' inter-broker traffic to the encrypted listener]
    D --> E[Move applications to the encrypted listener, team by team]
    E --> F[Watch that plaintext traffic falls to zero]
    F --> G[Remove the plaintext listener]
    G --> H[Done: encrypted only]
        
FIG 6 — A staged path from plaintext to encrypted-only
1

Prepare certificates and stores

Issue certificates with the correct names, and build keystores and truststores for all brokers.

2

First rolling restart: add the encrypted listener

Update every broker one at a time to open an additional encrypted listener, while keeping the plaintext one.

3

Test with a real client

Confirm that a test producer and consumer can connect, that certificate names match and that trust works.

4

Second rolling restart: switch broker-to-broker traffic

Point the inter-broker setting at the encrypted listener, again one broker at a time.

5

Migrate applications

Give each team the client settings, let them move their applications, and track which clients still use plaintext.

6

Remove the plaintext listener

Once plaintext connections are gone, remove that listener in a final rolling restart, and confirm by testing that plaintext no longer works.

i
Good Practice

Announce the plan and the final removal date to every application team well ahead, and measure connections per listener. A date with no measurement is a hope, not a plan.

!
Common Mistake

Leaving the plaintext listener open “just in case” after migration. It defeats the purpose, because attackers and mistakes will find the unprotected door. Close it once the last client has moved.

18TLS Across the Kafka Ecosystem

Kafka rarely runs alone. The tools around it all need their own TLS setup, and each has a few quirks.

Tool

Kafka Connect

Has several separate connections: the worker to Kafka, the connectors’ own producers and consumers, and its REST interface. Each may need its own TLS settings, with prefixes to tell them apart.

Tool

Schema Registry

Talks to Kafka as a client, and also offers a web interface that should be encrypted, so applications reach it over secure connections.

Tool

Kafka Streams applications

Use standard client settings, so the same truststore and keystore ideas apply, including for their internal topics.

Tool

Controllers and quorum

The cluster’s management nodes need their own protected listeners, and their own certificates.

Tool

Replication between clusters

Tools that copy data between clusters connect to both, and may need separate trust and identity for each side.

Tool

Monitoring and admin tools

Command line tools, graphical consoles and metric collectors are clients too, and need the right settings to connect.

Load balancers and proxies

Placing a load balancer between clients and brokers is tricky for Kafka, because clients must reach each individual broker, not just any broker. If a proxy terminates TLS and re-encrypts, the certificate the client sees belongs to the proxy, and names must match. If a proxy passes TLS through without opening it, the brokers’ own certificates must include the names that clients use. Plan names and certificates together with the network design.

Containers and Kubernetes

In container platforms, broker addresses often change, and names are internal service names. Certificates must contain those internal names. Automated tools that issue and renew certificates for pods, and mount them into containers, are the usual way to keep this manageable. Restarts of brokers to pick up new certificates should also follow safe rolling rules.

i
Practical Tip

Write down a table of every component that talks to Kafka, which connection it makes, and what TLS settings it needs. Missing a single component is a common cause of surprise failures after a change.

19Monitoring and Troubleshooting TLS

When TLS fails, the message is often cryptic. A calm, methodical approach quickly finds the cause.

What to monitor

Certificate expiry

Check every certificate’s end date from outside the brokers, and alert weeks ahead. This single check prevents the most dramatic TLS outages.

Authentication failures and connection counts

Brokers report rates of successful and failed authentications and the number of connections. Sudden increases in failures point to expired certificates, wrong settings after a deployment, or unwanted probing.

Processor use and request latency

Encryption uses processor time. Watch for growth after enabling TLS, or after a busy period, so capacity can be added early.

Broker and client logs

Handshake errors appear in logs with useful detail. Collect them centrally so you can search across all machines.

Common problems and their meaning

SymptomLikely causeFirst thing to check
Client says it cannot build a path to a trusted authorityClient truststore does not contain the authority that signed the broker certificateTruststore contents and the certificate chain
Client complains that no name matches the hostCertificate lacks the address the client usedSubject Alternative Names against advertised names
Handshake fails immediately with a protocol or cipher errorNo shared TLS version or cipher suiteEnabled versions and suites on both sides, and Java versions
Broker rejects the client with a bad certificate errorMutual TLS is required and the client certificate is missing or untrustedClient keystore and the broker truststore
Everything worked yesterday, fails todayA certificate expiredExpiry dates of all involved certificates
Client hangs or fails strangely when connectingPlaintext client talking to an encrypted port, or the reverseProtocol and port in the client settings
Brokers cannot join or replicate after enabling TLSInter-broker listener or trust is wrongInter-broker protocol and broker truststores
flowchart TD
    A[Connection fails] --> B{Right port and protocol?}
    B -- No --> B1[Fix client protocol and port]
    B -- Yes --> C{Certificate expired?}
    C -- Yes --> C1[Renew and roll out certificate]
    C -- No --> D{Client trusts the issuing authority?}
    D -- No --> D1[Fix client truststore]
    D -- Yes --> E{Names match the address used?}
    E -- No --> E1[Reissue certificate with correct names]
    E -- Yes --> F{Versions and ciphers overlap?}
    F -- No --> F1[Align allowed versions and suites]
    F -- Yes --> G[Check mutual TLS settings and logs]
        
FIG 7 — A thinking path for a TLS connection that will not work
i
Practical Tip

Command line tools that show a server’s certificate chain and validity dates are invaluable for these checks. Learn to use them before you need them urgently.

20Best Practices and Anti-Patterns

Habits that keep encryption strong and manageable, and traps that quietly weaken it.

Good habits

1

Encrypt every path

Client to broker, broker to broker, broker to controller and supporting services all need protection.

2

Use a proper certificate authority

Avoid hand-made self-signed certificates in production, and automate issuing and renewal.

3

Keep hostname verification on

Issue certificates with the correct names instead of turning off the check.

4

Allow only modern versions and strong ciphers

Disable old protocol versions, and review your choices at least yearly.

5

Give each broker its own key and certificate

Limit the damage if one key is exposed, and make rotation simpler.

6

Protect private keys and passwords

Restrict file permissions, keep secrets out of repositories, and use secret providers.

7

Combine TLS with authentication and permissions

Encryption alone does not decide who may do what. Add identity and access rules.

8

Monitor expiry and rehearse rotation

Alert on approaching expiry dates and practise rolling out new certificates in test first.

Anti-patterns to avoid

ANTI-PATTERN-02 Avoid
Problem

Turning off hostname verification, or trusting all certificates, to get past a connection error during setup, and leaving it that way.

Why It’s Harmful

The connection is still encrypted, but the client no longer checks who is at the other end. An attacker can impersonate a broker and receive the data.

Correct Approach

Fix the certificate names and the truststore, keeping full verification on in every environment that handles real data.

ANTI-PATTERN-03 Avoid
Problem

Encrypting client connections but leaving broker-to-broker replication on a plaintext listener.

Why It’s Harmful

Every message is copied between brokers, so the same sensitive data crosses the network in the open, and attackers simply watch that path instead.

Correct Approach

Set the inter-broker listener to an encrypted protocol, and protect controller connections as well.

ANTI-PATTERN-04 Avoid
Problem

Sharing one keystore, with one private key, across every broker and even across clients.

Why It’s Harmful

If the key leaks from any one place, all machines are compromised, and replacing it means touching everything at once.

Correct Approach

Issue a separate key and certificate to each broker and, where certificates are used for identity, to each client application.

ANTI-PATTERN-05 Avoid
Problem

Keeping passwords for keystores in plain text inside shared configuration files and repositories.

Why It’s Harmful

Anyone with access to the files can use the private keys, and secrets remain in version history even after deletion.

Correct Approach

Use secret providers or protected configuration mechanisms, restrict file permissions, and rotate any password that was ever exposed.

21Real-World Scenarios

Let us see how these ideas play out in situations that teams commonly meet.

A payments company protecting card-related events

Rules require encryption of sensitive data in transit. The team enables encrypted listeners for clients and brokers, uses mutual TLS for the payment services, and adds application-level encryption for card numbers, so even people with disk access cannot read them. TLS covers the network, and field encryption covers storage.

A company migrating a long-running plaintext cluster

Dozens of applications are already connected without encryption. The team adds an encrypted listener, moves broker traffic first, then migrates applications team by team while measuring connections per listener. After the last plaintext client moves, the old listener is removed.

A weekend outage caused by an expired certificate

A broker certificate issued years earlier expires on Saturday. Clients start failing with certificate errors. The postmortem leads to an inventory of every certificate, automated expiry alerts weeks ahead, and an automated renewal pipeline with rolling deployment.

A cloud deployment with a load balancer in front

The first TLS setup fails because clients see the load balancer’s name, not the broker’s advertised name. The team gives each broker its own reachable name, issues certificates with those names, and clients connect successfully with full verification enabled.

A shared cluster used by many teams

Each team gets its own client certificate with a clear name. Access rules give each certificate identity rights only to its own topics, and one team’s compromised key cannot read another team’s data.

TLS
protects data moving across the network
Identity
tells Kafka who is connecting
Access rules
decide what each identity may do

22Frequently Asked Questions

Q1Is Kafka encrypted by default?

No. By default, Kafka listeners can run in plaintext, and data travels readable across the network. You must enable and configure TLS yourself.

Q2Why does Kafka say SSL when it really uses TLS?

SSL is the older name of the technology. Kafka’s setting names and protocol labels kept the old word, but modern setups use TLS versions, and old SSL versions should be disabled.

Q3What is the difference between a keystore and a truststore?

A keystore holds your own private key and certificate, answering “who am I?” A truststore holds the authorities you trust, answering “whom do I trust?”

Q4Do clients need certificates?

Not for one-way TLS, where clients only need to trust the brokers. Clients need their own certificates only when brokers require mutual TLS.

Q5Does TLS encrypt data stored on the broker’s disk?

No. TLS protects data only while it moves across the network. To protect stored data, use disk encryption, application-level encryption or both.

Q6Does TLS make Kafka slower?

It adds processor cost for encryption and removes the zero-copy shortcut for encrypted connections, so processor use on brokers rises. With modern hardware, recent Java and connection reuse, the impact is usually manageable, but you should measure it for your workload.

Q7Is TLS enough to secure Kafka?

No. TLS gives encryption and, optionally, identity. You also need authentication for clients and access control rules that limit what each identity can do, plus protection of data at rest where needed.

Q8Why do I get a name mismatch error?

The certificate does not list the address the client used. Reissue it with the advertised host names, and any other names clients use, in the Subject Alternative Name field.

Q9Can I renew certificates without downtime?

Yes, in most setups. Modern Kafka can reload keystores dynamically, or you can restart brokers one at a time. Test the procedure in a non-production cluster first.

Q10Should broker-to-broker traffic be encrypted too?

Yes. Replication carries all of your data, so an unencrypted inter-broker path leaves it exposed even if clients use TLS.

Q11What is mutual TLS and when should I use it?

Mutual TLS means both sides present certificates. It suits environments with automated certificate management where you want strong, key-based client identity without shared passwords.

Q12How do I move an existing cluster to TLS without stopping it?

Add an encrypted listener alongside the plaintext one, move broker traffic and then applications gradually, and remove the plaintext listener only after no clients use it.

23Summary and Key Takeaways

Kafka does not encrypt its network traffic by default, so messages can be read or altered by anyone who can see the network. TLS solves this with three promises: confidentiality, integrity and authentication. It rests on private keys, certificates and a chain of trust from a certificate authority, kept in keystores and truststores. Brokers expose encrypted listeners, clients are told which protocol to use and whom to trust, and mutual TLS can add strong client identity. Every path, including broker-to-broker replication, should be protected, and certificate names must match the addresses that clients use. TLS does not protect stored data or decide permissions, so it belongs in a larger plan that includes access rules and encryption at rest. Running it well means automating certificate renewal, watching expiry dates, allowing only modern versions and migrating existing clusters in careful stages.

Key Takeaways

  • Kafka is not encrypted by default — you must enable TLS on brokers and clients yourself.
  • TLS gives three protections — confidentiality, integrity and authentication while data moves across the network.
  • Keystore means identity, truststore means trust — brokers always need a keystore, and clients need a truststore to trust the brokers.
  • Protect every path — client to broker, broker to broker, controllers and supporting services.
  • Certificate names must match — list advertised names in the Subject Alternative Name field and keep hostname verification on.
  • Mutual TLS adds client identity — certificate names become principals that access rules can use.
  • TLS is not everything — it does not encrypt stored data or replace authentication and access control.
  • Manage the certificate lifecycle — inventory, monitor expiry, automate renewal and migrate live clusters with staged rolling changes.