In this post we are going to cover Event Hubs for Apache Kafka. These are 7 real Event Hubs interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: the company wants to migrate twenty Kafka topics to Event Hubs with no code changes, and you make the plan.
Event Hubs speaks the Kafka protocol itself. A Kafka producer or consumer can connect to an Event Hubs namespace like a Kafka cluster, with no brokers to run. Interviewers ask about this because many teams move from Kafka to Azure, and "no code changes" is only true if you know what maps one to one, which settings are required, and which Kafka features are not supported.
Part 5 of the Real Time Azure Event Hubs Interview Questions and Answers series on TechBrothersIT.
- The short answer
- Let's set up the project
- Question 1: The team runs Kafka clients and wants to move to Azure. How does the Event Hubs Kafka endpoint work?
- Question 2: A teammate asks how Kafka concepts map to Event Hubs. How do you explain the mapping?
- Question 3: A Kafka producer can't connect to Event Hubs. Which client settings are required?
- Question 4: Someone asks whether Kafka consumer groups and offsets work the same on Event Hubs. How do you answer?
- Question 5: Your manager asks which Kafka features Event Hubs does not support. What do you tell them?
- Question 6: A teammate asks whether to use the Kafka client or the native Event Hubs SDK. How do you decide?
- Scenario 7: The company wants to migrate twenty Kafka topics to Event Hubs with no code changes. What is your plan?
- The full script
The short answer
Standard, Premium and Dedicated namespaces expose a Kafka endpoint on port 9093: Kafka 1.0+ clients connect with SASL_SSL and $ConnectionString (or OAUTHBEARER) and keep their code. A topic is an event hub; consumer groups and offsets work as in Kafka. Topics are created as code (the config page lists Kafka topic admin as unsupported), no broker configs, only gzip compression, and transactions and Kafka Streams are preview on Premium and Dedicated.
Let's set up the project
We run Microsoft's official Event Hubs emulator locally, with small Python scripts that use confluent-kafka for the Kafka endpoint and the azure-eventhub client for the native side, so every output is real. Features the emulator doesn't support are shown as code. The emulator reads its entities from Config.json: orders with 4 partitions and the consumer group analytics, and payments and shipments with 2 partitions each. kafka_config.py holds the Kafka client settings, and kafka_produce.py sends keyed orders.
{
"UserConfig": {
"NamespaceConfig": [
{
"Type": "EventHub",
"Name": "emulatorNs1",
"Entities": [
{
"Name": "orders",
"PartitionCount": 4,
"ConsumerGroups": [
{
"Name": "analytics"
}
]
},
{
"Name": "payments",
"PartitionCount": 2,
"ConsumerGroups": []
},
{
"Name": "shipments",
"PartitionCount": 2,
"ConsumerGroups": []
}
]
}
],
"LoggingConfig": {
"Type": "File"
}
}
}import os
# The emulator: SASL_PLAINTEXT on 9092. Azure: SASL_SSL on 9093.
KAFKA = {
"bootstrap.servers": "localhost:9092",
"security.protocol": "SASL_PLAINTEXT",
"sasl.mechanism": "PLAIN",
"sasl.username": "$ConnectionString",
"sasl.password": os.environ["EVENTHUB_CONNECTION_STRING"],
}import json, sys
from confluent_kafka import Producer
from kafka_config import KAFKA
producer = Producer(KAFKA)
report = []
def on_delivery(err, msg):
if err:
print("delivery failed:", err)
return
order = json.loads(msg.value())["order_id"]
report.append((msg.partition(), msg.offset(), msg.key(), order))
first, count = int(sys.argv[1]), int(sys.argv[2])
for order_id in range(first, first + count):
customer = ("alice", "bob", "carol")[order_id % 3]
value = json.dumps({"order_id": order_id, "customer": customer})
producer.produce("orders", key=customer, value=value,
headers={"event_type": b"OrderPlaced"},
on_delivery=on_delivery)
producer.flush(30)
for partition, offset, key, order in sorted(report):
print(f"partition {partition} offset {offset}"
f" key {key.decode()} order {order}")Question 1: The team runs Kafka clients and wants to move to Azure. How does the Event Hubs Kafka endpoint work?
Event Hubs speaks the Kafka protocol itself. Here is what that means:
- Standard, Premium, Dedicated - not Basic
- Kafka 1.0 and later clients - no brokers to run
- Configuration only -
bootstrap.serverson port 9093 + SASL
So moving is a configuration change, not a code change. Bootstrap servers point at the namespace on port 9093, and the client authenticates with SASL.
Let's send from a plain confluent-kafka producer. kafka_produce.py sends six orders, keyed by customer, and prints the delivery reports that come back from Event Hubs. We run python kafka_produce.py 1001 6.
$ python kafka_produce.py 1001 6
partition 0 offset 0 key bob order 1003
partition 0 offset 1 key bob order 1006
partition 3 offset 0 key carol order 1001
partition 3 offset 1 key alice order 1002
partition 3 offset 2 key carol order 1004
partition 3 offset 3 key alice order 1005Bob's orders are on partition 0, offset 0 and offset 1. Alice and carol are on partition 3, with offsets 0 to 3. The offsets count up in each partition.
Ordering works the way Kafka users expect: per partition. The Kafka client picks the partition from the key with its own partitioner, and different client libraries can hash the same key differently.
Rerun your load test against Event Hubs before the cutover. The tier's quotas apply now, like the 1 MB event limit on Standard.
Question 2: A teammate asks how Kafka concepts map to Event Hubs. How do you explain the mapping?
It's almost one to one. A Kafka cluster is an Event Hubs namespace, a topic is an event hub, and partitions, consumer groups and offsets keep their names and meaning.
Let's see it from the Kafka side. metadata.py uses the Kafka admin client to list the topics. We run python metadata.py.
from confluent_kafka.admin import AdminClient
from kafka_config import KAFKA
admin = AdminClient(KAFKA)
meta = admin.list_topics(timeout=15)
for name in sorted(meta.topics):
partitions = sorted(meta.topics[name].partitions)
print(f"topic {name}: partitions {partitions}")$ python metadata.py
topic orders: partitions [0, 1, 2, 3]
topic payments: partitions [0, 1]
topic shipments: partitions [0, 1]The topics are exactly the three event hubs in the emulator's configuration, with their partition counts: topic orders: partitions [0, 1, 2, 3], and payments and shipments with [0, 1].
Here is the full mapping, and what is different.
| Kafka | Event Hubs | What is different |
|---|---|---|
| Cluster | Namespace | no brokers: sized in TUs, PUs or CUs, shared by its event hubs |
| Topic | Event hub | create it with the portal, CLI or ARM templates |
| Partition | Partition | ordered log; count fixed on Standard |
| Consumer group | Consumer group | Kafka: no need to create it first |
| Offset | Offset | Kafka offsets are committed to Event Hubs |
The differences are in management. There are no brokers to tune: we size the namespace in throughput, processing or capacity units, and on Standard the partition count is fixed at creation.
Consumer groups differ a little. A Kafka consumer group doesn't have to be created first, while AMQP readers need the consumer group to exist on the event hub.
One namespace per topic, or one for everything. Units are bought per namespace and shared by its event hubs, so group topics that scale together.
Question 3: A Kafka producer can't connect to Event Hubs. Which client settings are required?
Five settings. Bootstrap servers: the namespace host name on port 9093. Security protocol: SASL_SSL, because Event Hubs requires TLS. Mechanism PLAIN, the user name is the literal text $ConnectionString, and the password is the connection string itself.
# Azure Event Hubs: Standard, Premium or Dedicated
bootstrap.servers=tbshop-prod.servicebus.windows.net:9093
security.protocol=SASL_SSL
sasl.mechanism=PLAIN
sasl.username=$ConnectionString
sasl.password=Endpoint=sb://tbshop-prod.servicebus.windows.net/;...
# or sasl.mechanism=OAUTHBEARER with Microsoft Entra IDOr use OAUTHBEARER with Microsoft Entra ID, which Microsoft recommends. The emulator differs: port 9092 with SASL_PLAINTEXT, as the comment in our kafka_config.py says.
Now let's break it. connect_check.py sends with the required settings, then with a wrong user name, then with no SASL. We run python connect_check.py.
from confluent_kafka import KafkaError, Producer
from kafka_config import KAFKA
def try_send(label, changes):
causes = set()
def on_error(e): # the real reason is here
if e.code() == KafkaError._AUTHENTICATION:
causes.add(e.str().split(": ", 1)[1].split(" (after")[0])
conf = dict(KAFKA, **changes)
conf.update({"message.timeout.ms": 6000, "log_level": 0,
"error_cb": on_error})
producer, result = Producer(conf), []
producer.produce("payments", b"ping",
on_delivery=lambda err, msg: result.append(err))
producer.flush(15)
print(label, "->", result[0].str() if result[0] else "delivered")
for cause in sorted(causes):
print(" error_cb:", cause)
try_send("required settings", {})
try_send("user name orders-app", {"sasl.username": "orders-app"})
try_send("no SASL", {"security.protocol": "PLAINTEXT"})$ python connect_check.py
required settings -> delivered
user name orders-app -> Local: Message timed out
error_cb: SASL authentication error: Invalid SASL PLAIN user name.
no SASL -> Local: Message timed outThe required settings print delivered. A wrong user name and no SASL don't fail fast: the send just ends in Local: Message timed out. Only the error callback shows the real cause: SASL authentication error: Invalid SASL PLAIN user name.
So register error_cb or read the client log, and check those five settings first. The emulator accepts any key, so test the key against a real namespace.
Use request.timeout.ms=60000, well above the 20 second minimum Event Hubs expects, and metadata.max.age.ms=180000, below four minutes, because Azure closes idle connections after that.
Question 4: Someone asks whether Kafka consumer groups and offsets work the same on Event Hubs. How do you answer?
For the client, yes. Kafka consumers use the normal group protocol: a group.id, one member per partition, a rebalance when members join or leave, and offsets committed to Event Hubs itself.
Let's try it. kafka_consume.py reads orders with a group, commits after processing, and prints the committed offsets. We run it for billing, produce two more orders, run billing again, then run a new group, audit.
import json, sys, time
from confluent_kafka import Consumer
from kafka_config import KAFKA
group = sys.argv[1]
consumer = Consumer(dict(KAFKA, **{"group.id": group,
"auto.offset.reset": "earliest",
"enable.auto.commit": False}))
consumer.subscribe(["orders"])
read, stop = {}, time.time() + 15
try:
while time.time() < stop:
msg = consumer.poll(1.0)
if msg is None or msg.error():
continue
order = json.loads(msg.value())["order_id"] # process it
p = msg.partition()
read.setdefault(p, []).append((msg.offset(), order))
if read:
consumer.commit(asynchronous=False) # after processing
done = consumer.committed(consumer.assignment(), timeout=10)
finally:
consumer.close()
print(f"group {group}: read {sum(map(len, read.values()))} events")
for p, rows in sorted(read.items()):
offsets, orders = zip(*sorted(rows))
print(f" partition {p} offsets {list(offsets)}"
f" orders {list(orders)}")
print(" committed:", sorted((t.partition, t.offset) for t in done
if t.offset >= 0))$ python kafka_consume.py billing
group billing: read 6 events
partition 0 offsets [0, 1] orders [1003, 1006]
partition 3 offsets [0, 1, 2, 3] orders [1001, 1002, 1004, 1005]
committed: [(0, 2), (3, 4)]
$ python kafka_produce.py 1007 2
partition 3 offset 4 key carol order 1007
partition 3 offset 5 key alice order 1008
$ python kafka_consume.py billing
group billing: read 2 events
partition 3 offsets [4, 5] orders [1007, 1008]
committed: [(0, 2), (3, 6)]
$ python kafka_consume.py audit
group audit: read 8 events
partition 0 offsets [0, 1] orders [1003, 1006]
partition 3 offsets [0, 1, 2, 3, 4, 5] orders [1001, 1002, 1004, 1005, 1007, 1008]
committed: [(0, 2), (3, 6)]The first billing run: read 6 events, and committed: [(0, 2), (3, 4)]. The committed offsets are the next ones to read: 2 on partition 0, 4 on partition 3.
Then we produce orders 1007 and 1008, on partition 3. Billing resumes from its commit: read 2 events, orders [1007, 1008].
The new group, audit, has no commit, so auto.offset.reset earliest gives it all of them: read 8 events.
Event Hubs adds limits:
- Offset commits - throttled to 2 calls per second per partition, so commit in batches
- Kafka consumer groups - up to 1,000 per namespace
Committed offsets only point into retained data. If they fall outside retention, auto.offset.reset decides where the group starts again, so set it explicitly on every consumer.
Question 5: Your manager asks which Kafka features Event Hubs does not support. What do you tell them?
Microsoft's Kafka configuration page lists them. No topic management through the Kafka admin client, though the Kafka Connect tutorial relies on it: create event hubs as code. No broker configurations, no server-side custom partitioner, and no compression except gzip.
Let's test on the emulator. unsupported.py creates a topic, then sends with gzip, zstd and idempotence. transactions.py starts a transactional producer. We run python unsupported.py and python transactions.py.
from confluent_kafka import KafkaException, Producer
from confluent_kafka.admin import AdminClient, NewTopic
from kafka_config import KAFKA
admin = AdminClient(KAFKA)
future = admin.create_topics([NewTopic("refunds", 4)])["refunds"]
try:
future.result(timeout=15)
except KafkaException as e:
print("create_topics:", e.args[0].name())
print(" ", e.args[0].str())
def send(label, settings):
producer, results = Producer(dict(KAFKA, **settings)), []
for i in range(3):
producer.produce("payments", key="pay-1",
value=f"{label} payment {i} " * 20,
on_delivery=lambda err, m: results.append(err))
producer.flush(20)
ok = sum(err is None for err in results)
print(f"{label}: delivered {ok} of 3")
for reason in sorted({e.str() for e in results if e is not None}):
print(" ", reason)
send("gzip", {"compression.type": "gzip"})
send("zstd", {"compression.type": "zstd"})
send("idempotent", {"enable.idempotence": True})import logging, textwrap
from confluent_kafka import KafkaException, Producer
from kafka_config import KAFKA
class BrokerLog(logging.Handler): # librdkafka's debug log
reasons = set()
def emit(self, record):
text = record.getMessage()
if "INVALID_REQUEST: " in text:
self.reasons.add(text.split("INVALID_REQUEST: ")[1])
log = logging.getLogger("librdkafka")
log.addHandler(BrokerLog())
log.setLevel(logging.DEBUG)
log.propagate = False
producer = Producer(dict(KAFKA, **{"transactional.id": "payments-tx",
"debug": "eos", "logger": log}))
try:
producer.init_transactions(10)
except KafkaException as e:
print("init_transactions:", e.args[0].name())
print(" ", e.args[0].str())
producer.poll(1) # hand over the queued log lines
for reason in sorted(BrokerLog.reasons):
print("broker log:")
for line in textwrap.wrap(reason, 66):
print(" ", line)$ python unsupported.py
create_topics: INVALID_REQUEST
Kafka CreateTopics API is not supported for EventHubs Emulator.
gzip: delivered 0 of 3
Broker: Message format on broker does not support request
zstd: delivered 3 of 3
idempotent: delivered 3 of 3
$ python transactions.py
init_transactions: _TIMED_OUT
Timed out waiting for operation to finish, retry call to resume
broker log:
FindCoordinator asked for coordinator with type code 1 which is
not supported. type code 1 is only supported in Premium or
Dedicated sku.create_topics: INVALID_REQUEST. Gzip is rejected, delivered 0 of 3, and zstd is accepted, delivered 3 of 3. That's the opposite of the Azure docs, which say gzip only, and the overview page limits Kafka compression to Premium and Dedicated. Never decide compression from the emulator.
The idempotent producer works, delivered 3 of 3, and Event Hubs supports idempotent producers, so keep it on. Transactions don't work here: init_transactions: _TIMED_OUT, and the broker log says why: only supported in Premium or Dedicated sku.
| Kafka feature | Azure Event Hubs (Microsoft docs) | This emulator (real run) |
|---|---|---|
| Topic admin (CreateTopics) | config page: not supported (docs differ) | rejected: INVALID_REQUEST |
| Compression | gzip only (overview: Premium, Dedicated) | gzip rejected, zstd accepted |
| Idempotent producer | supported | works: 3 of 3 delivered |
| Transactions | preview, Premium and Dedicated only | times out: "Premium or Dedicated sku" |
| Kafka Streams | preview, Premium and Dedicated only | not tested |
| Broker configs, server-side partitioner | not supported | not tested |
So treat Kafka transactions as preview, on Premium and Dedicated only. Kafka Streams is the same: public preview, Premium and Dedicated only.
Scan every client config for compression.type, transactional.id and admin calls.
Question 6: A teammate asks whether to use the Kafka client or the native Event Hubs SDK. How do you decide?
Both use the same event hubs, so it's a choice per application.
| Kafka client (Kafka endpoint) | Native Event Hubs SDK (AMQP) |
|---|---|
| existing Kafka apps, Kafka Connect, MirrorMaker | new Azure apps: EventHubConsumerClient |
| offsets committed to Event Hubs | checkpoints in your Blob Storage, load balancing |
| SAS or OAUTHBEARER (Microsoft Entra ID) | SAS or Microsoft Entra ID via azure-identity |
| idempotent producer supported | Python SDK: no idempotent producer |
| Standard, Premium and Dedicated only | every tier, Basic included |
They interoperate. Let's read partition 0, which our Kafka producer wrote, with the native SDK: python native_read.py.
import logging, os, threading
from azure.eventhub import EventHubConsumerClient
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
client = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"],
consumer_group="analytics", eventhub_name="orders")
seen = []
threading.Timer(8, client.close).start() # stop after 8 seconds
with client:
client.receive(on_event=lambda ctx, ev: seen.append(ev),
partition_id="0", starting_position="-1")
for event in sorted(seen, key=lambda ev: ev.sequence_number):
print("seq", event.sequence_number, "key", event.partition_key)
print(" properties", event.properties)
print(" body", event.body_as_str())$ python native_read.py
seq 0 key b'bob'
properties {b'event_type': b'OrderPlaced'}
body {"order_id": 1003, "customer": "bob"}
seq 1 key b'bob'
properties {b'event_type': b'OrderPlaced'}
body {"order_id": 1006, "customer": "bob"}Bob's two orders, seq 0 and seq 1. The Kafka key became the partition key, key b'bob', and the header became an application property, in bytes: {b'event_type': b'OrderPlaced'}.
The other direction needs care. amqp_send.py sends a shipment with the native SDK, with a string and a bytes property. Then a Kafka consumer reads it. We run python amqp_send.py and python kafka_read.py.
import os
from azure.eventhub import EventData, EventHubProducerClient
producer = EventHubProducerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], eventhub_name="shipments")
event = EventData('{"shipment_id": 501, "order_id": 1003}')
event.properties = {"event_type": "ShipmentCreated", "carrier": b"UPS"}
with producer:
producer.send_event(event, partition_key="bob")
print("sent shipment 501 with the native SDK")import time
from confluent_kafka import Consumer
from kafka_config import KAFKA
consumer = Consumer(dict(KAFKA, **{"group.id": "shipping",
"auto.offset.reset": "earliest"}))
consumer.subscribe(["shipments"])
msg, stop = None, time.time() + 20
try:
while msg is None and time.time() < stop:
msg = consumer.poll(1.0)
finally:
consumer.close()
print("key:", msg.key())
for name, value in msg.headers():
print("header:", name, value)
print("value:", msg.value().decode())$ python amqp_send.py
sent shipment 501 with the native SDK
$ python kafka_read.py
key: b'bob'
header: event_type b'\xa1\x0fShipmentCreated'
header: carrier b'\xa0\x03UPS'
value: {"shipment_id": 501, "order_id": 1003}The Kafka consumer gets both as headers, but each value starts with AMQP type bytes, a type code and a length: b'\xa1\x0fShipmentCreated' and b'\xa0\x03UPS'.
So if both protocols share a stream, agree on one contract: needed fields in the body, or one shared header decoder.
Kafka where Kafka tooling or portability matters, the native SDK for new Azure services, and one protocol per stream unless there's a reason.
Scenario 7: The company wants to migrate twenty Kafka topics to Event Hubs with no code changes. What is your plan?
Here is the plan, in order:
- Target tier - Premium or Dedicated for production Kafka
- One event hub per topic - created as code
- Check limits - partitions, retention, 1 MB, gzip or none
- Client config only - 9093, SASL_SSL, OAUTHBEARER
- MirrorMaker 2 - history + sync, then cut over
First, the target. Microsoft recommends Premium or Dedicated for full Kafka protocol compatibility in production; Standard has limitations. Then one event hub per Kafka topic, created as code with the partitions and retention we chose.
# one event hub per Kafka topic, created as code
while read -r topic partitions; do
az eventhubs eventhub create --resource-group rg-kafka \
--namespace-name tbshop-kafka-prod --name "$topic" \
--partition-count "$partitions" \
--cleanup-policy Delete --retention-time-in-hours 168
done < topics.txt # 20 lines: name partitionsNext, check what Event Hubs enforces.
| Check | Event Hubs |
|---|---|
| Partitions | increase on Premium and Dedicated only, never decrease |
| Retention | Standard up to 7 days, Premium and Dedicated up to 90 |
| Event size | 1 MB on Standard and Premium, 20 MB on Dedicated |
| Compression | gzip or none |
| Event hubs | Standard: 10 per namespace; Premium: 100 per PU |
Then the client change: bootstrap servers, SASL_SSL and the credentials, ideally OAUTHBEARER with Entra ID. Scan for transactional IDs, admin calls and other codecs: those are where "no code changes" breaks.
MirrorMaker 2 copies history and keeps the topics in sync, with the identity replication policy so topic names stay the same.
# kafka-to-eh-connect-mirror-maker.properties
clusters = source, destination
source.bootstrap.servers = kafka-onprem:9092
destination.bootstrap.servers = \
tbshop-kafka-prod.servicebus.windows.net:9093
destination.security.protocol=SASL_SSL
destination.sasl.mechanism=PLAIN
destination.sasl.jaas.config=org.apache.kafka.common.security.\
plain.PlainLoginModule required username='$ConnectionString' \
password='<namespace connection string>';
source->destination.enabled = true
source->destination.topics = .*
# keep topic names (the default policy adds a "source." prefix)
replication.policy.class = org.apache.kafka.connect.mirror.\
IdentityReplicationPolicyThen switch consumers. Offsets on Event Hubs don't match the old cluster's, so set auto.offset.reset deliberately and keep processing idempotent. Then switch producers, and stop the mirror.
Use the emulator for client wiring, but run final tests on a real namespace in the target tier: compression, transactions and authentication differ there.
Key points to remember
- Kafka endpoint on Standard, Premium, Dedicated: Kafka 1.0+ clients, port 9093
- Cluster = namespace, topic = event hub; partitions, groups, offsets map 1:1
- SASL_SSL + PLAIN with $ConnectionString, or OAUTHBEARER with Entra ID
- Topics as code, no broker configs, only gzip; transactions are preview
- Migrate: one event hub per topic as code, MirrorMaker 2, test on the target tier
The full script
This is a Python script that writes every file and runs every command above in order against the Event Hubs emulator: start the emulator with the Config.json above, run pip install azure-eventhub azure-eventhub-checkpointstoreblob azure-storage-blob confluent-kafka fastavro first, and set EVENTHUB_CONNECTION_STRING and STORAGE_CONNECTION_STRING.
Show the full script that writes the files and runs every step
# ========================================================================
# Event Hubs Interview Q&A #5 - Event Hubs for Apache Kafka
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run on the official Azure Event Hubs emulator (Docker image, version 2.2.1) with Azurite
# and azure-eventhub 5.15.1; the outputs in the video and the blog post are the real outputs.
# To run it yourself:
# 1. Start the emulator with Microsoft's installer (github.com/Azure/azure-event-hubs-emulator-installer),
# using a Config.json with the event hubs and consumer groups listed below.
# 2. pip install azure-eventhub azure-eventhub-checkpointstoreblob azure-storage-blob confluent-kafka fastavro
# 3. Set EVENTHUB_CONNECTION_STRING to the emulator connection string (Endpoint=sb://localhost;
# SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;)
# and STORAGE_CONNECTION_STRING to the Azurite blob connection string, then run python EventHubs_Interview_QA_05_Code.py.
# Entities in Config.json: orders (4 partitions, groups analytics); payments (2 partitions); shipments (2 partitions)
# Steps that restart the emulator say so in a comment: stop and start it by hand at that point.
# ========================================================================
import os, subprocess, time
def write(path, text):
if text is None:
if os.path.exists(path): os.remove(path)
return
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(text.strip("\n") + "\n")
def run(cmd, expect_error=False, allow_error=False, env=None):
print("\n$ " + cmd, flush=True)
rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
if rc != 0 and not (expect_error or allow_error):
raise SystemExit("stopped: this command was expected to succeed")
# Step 0: the starting files
write('kafka_config.py', """\
import os
# The emulator: SASL_PLAINTEXT on 9092. Azure: SASL_SSL on 9093.
KAFKA = {
"bootstrap.servers": "localhost:9092",
"security.protocol": "SASL_PLAINTEXT",
"sasl.mechanism": "PLAIN",
"sasl.username": "$ConnectionString",
"sasl.password": os.environ["EVENTHUB_CONNECTION_STRING"],
}
""")
write('kafka_produce.py', """\
import json, sys
from confluent_kafka import Producer
from kafka_config import KAFKA
producer = Producer(KAFKA)
report = []
def on_delivery(err, msg):
if err:
print("delivery failed:", err)
return
order = json.loads(msg.value())["order_id"]
report.append((msg.partition(), msg.offset(), msg.key(), order))
first, count = int(sys.argv[1]), int(sys.argv[2])
for order_id in range(first, first + count):
customer = ("alice", "bob", "carol")[order_id % 3]
value = json.dumps({"order_id": order_id, "customer": customer})
producer.produce("orders", key=customer, value=value,
headers={"event_type": b"OrderPlaced"},
on_delivery=on_delivery)
producer.flush(30)
for partition, offset, key, order in sorted(report):
print(f"partition {partition} offset {offset}"
f" key {key.decode()} order {order}")
""")
# Step 1: A plain Kafka producer sends six keyed orders to the event hub orders
run('python kafka_produce.py 1001 6')
# Step 2: The Kafka admin client lists the event hubs as topics
write('metadata.py', """\
from confluent_kafka.admin import AdminClient
from kafka_config import KAFKA
admin = AdminClient(KAFKA)
meta = admin.list_topics(timeout=15)
for name in sorted(meta.topics):
partitions = sorted(meta.topics[name].partitions)
print(f"topic {name}: partitions {partitions}")
""")
run('python metadata.py')
# Step 3: Required settings vs a wrong user name vs no SASL
write('connect_check.py', """\
from confluent_kafka import KafkaError, Producer
from kafka_config import KAFKA
def try_send(label, changes):
causes = set()
def on_error(e): # the real reason is here
if e.code() == KafkaError._AUTHENTICATION:
causes.add(e.str().split(": ", 1)[1].split(" (after")[0])
conf = dict(KAFKA, **changes)
conf.update({"message.timeout.ms": 6000, "log_level": 0,
"error_cb": on_error})
producer, result = Producer(conf), []
producer.produce("payments", b"ping",
on_delivery=lambda err, msg: result.append(err))
producer.flush(15)
print(label, "->", result[0].str() if result[0] else "delivered")
for cause in sorted(causes):
print(" error_cb:", cause)
try_send("required settings", {})
try_send("user name orders-app", {"sasl.username": "orders-app"})
try_send("no SASL", {"security.protocol": "PLAINTEXT"})
""")
run('python connect_check.py')
# Step 4: A Kafka consumer group commits, resumes from its commit, and a new group starts at earliest
write('kafka_consume.py', """\
import json, sys, time
from confluent_kafka import Consumer
from kafka_config import KAFKA
group = sys.argv[1]
consumer = Consumer(dict(KAFKA, **{"group.id": group,
"auto.offset.reset": "earliest",
"enable.auto.commit": False}))
consumer.subscribe(["orders"])
read, stop = {}, time.time() + 15
try:
while time.time() < stop:
msg = consumer.poll(1.0)
if msg is None or msg.error():
continue
order = json.loads(msg.value())["order_id"] # process it
p = msg.partition()
read.setdefault(p, []).append((msg.offset(), order))
if read:
consumer.commit(asynchronous=False) # after processing
done = consumer.committed(consumer.assignment(), timeout=10)
finally:
consumer.close()
print(f"group {group}: read {sum(map(len, read.values()))} events")
for p, rows in sorted(read.items()):
offsets, orders = zip(*sorted(rows))
print(f" partition {p} offsets {list(offsets)}"
f" orders {list(orders)}")
print(" committed:", sorted((t.partition, t.offset) for t in done
if t.offset >= 0))
""")
run('python kafka_consume.py billing')
run('python kafka_produce.py 1007 2')
run('python kafka_consume.py billing')
run('python kafka_consume.py audit')
# Step 5: Not supported: CreateTopics, gzip and transactions on the emulator; zstd and idempotence work
write('unsupported.py', """\
from confluent_kafka import KafkaException, Producer
from confluent_kafka.admin import AdminClient, NewTopic
from kafka_config import KAFKA
admin = AdminClient(KAFKA)
future = admin.create_topics([NewTopic("refunds", 4)])["refunds"]
try:
future.result(timeout=15)
except KafkaException as e:
print("create_topics:", e.args[0].name())
print(" ", e.args[0].str())
def send(label, settings):
producer, results = Producer(dict(KAFKA, **settings)), []
for i in range(3):
producer.produce("payments", key="pay-1",
value=f"{label} payment {i} " * 20,
on_delivery=lambda err, m: results.append(err))
producer.flush(20)
ok = sum(err is None for err in results)
print(f"{label}: delivered {ok} of 3")
for reason in sorted({e.str() for e in results if e is not None}):
print(" ", reason)
send("gzip", {"compression.type": "gzip"})
send("zstd", {"compression.type": "zstd"})
send("idempotent", {"enable.idempotence": True})
""")
write('transactions.py', """\
import logging, textwrap
from confluent_kafka import KafkaException, Producer
from kafka_config import KAFKA
class BrokerLog(logging.Handler): # librdkafka's debug log
reasons = set()
def emit(self, record):
text = record.getMessage()
if "INVALID_REQUEST: " in text:
self.reasons.add(text.split("INVALID_REQUEST: ")[1])
log = logging.getLogger("librdkafka")
log.addHandler(BrokerLog())
log.setLevel(logging.DEBUG)
log.propagate = False
producer = Producer(dict(KAFKA, **{"transactional.id": "payments-tx",
"debug": "eos", "logger": log}))
try:
producer.init_transactions(10)
except KafkaException as e:
print("init_transactions:", e.args[0].name())
print(" ", e.args[0].str())
producer.poll(1) # hand over the queued log lines
for reason in sorted(BrokerLog.reasons):
print("broker log:")
for line in textwrap.wrap(reason, 66):
print(" ", line)
""")
run('python unsupported.py')
run('python transactions.py')
# Step 6: The native SDK reads events a Kafka producer wrote
write('native_read.py', """\
import logging, os, threading
from azure.eventhub import EventHubConsumerClient
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
client = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"],
consumer_group="analytics", eventhub_name="orders")
seen = []
threading.Timer(8, client.close).start() # stop after 8 seconds
with client:
client.receive(on_event=lambda ctx, ev: seen.append(ev),
partition_id="0", starting_position="-1")
for event in sorted(seen, key=lambda ev: ev.sequence_number):
print("seq", event.sequence_number, "key", event.partition_key)
print(" properties", event.properties)
print(" body", event.body_as_str())
""")
run('python native_read.py')
# Step 7: A Kafka consumer reads an event the native SDK wrote: AMQP-encoded header values
write('amqp_send.py', """\
import os
from azure.eventhub import EventData, EventHubProducerClient
producer = EventHubProducerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], eventhub_name="shipments")
event = EventData('{"shipment_id": 501, "order_id": 1003}')
event.properties = {"event_type": "ShipmentCreated", "carrier": b"UPS"}
with producer:
producer.send_event(event, partition_key="bob")
print("sent shipment 501 with the native SDK")
""")
write('kafka_read.py', """\
import time
from confluent_kafka import Consumer
from kafka_config import KAFKA
consumer = Consumer(dict(KAFKA, **{"group.id": "shipping",
"auto.offset.reset": "earliest"}))
consumer.subscribe(["shipments"])
msg, stop = None, time.time() + 20
try:
while msg is None and time.time() < stop:
msg = consumer.poll(1.0)
finally:
consumer.close()
print("key:", msg.key())
for name, value in msg.headers():
print("header:", name, value)
print("value:", msg.value().decode())
""")
run('python amqp_send.py')
run('python kafka_read.py')
Part 6: Retention, Capture and Replay
The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on the official Azure Event Hubs emulator (2.2.1) with Azurite and azure-eventhub 5.15.1. Features the emulator does not support are shown as code. Part of the Real Time Azure Event Hubs Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Azure Event Hubs documentation (learn.microsoft.com/azure/event-hubs) for anything you quote in an interview.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.