In this post we are going to cover consumer groups and checkpointing in Azure Event Hubs. 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: a consumer writes to a database and must survive restarts without losing or double-writing events.
A consumer group is an independent view of the stream, and a checkpoint is how a consumer saves its position in that view. Event Hubs never tracks what we read for us, so the consumer decides where to start, where to save, and when. Interviewers ask about this because it decides what happens after a restart: do we start over, skip events, or write some of them twice?
Part 4 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: A new service must read the stream without disturbing existing readers. How do consumer groups work?
- Question 2: A consumer restarts and processes everything from the beginning again. What is checkpointing?
- Question 3: Four instances of a consumer run at once. How does the processor balance partitions between them?
- Question 4: A teammate checkpoints after every single event and the job is slow. How often should you checkpoint?
- Question 5: A bug corrupted a day of output. How do you reprocess from an offset or a point in time?
- Question 6: Two readers on the same partition keep kicking each other off. What are epoch, or exclusive, receivers?
- Scenario 7: A consumer writes to a database and must survive restarts without losing or double-writing events. How do you design it?
- The full script
The short answer
A consumer group is an independent view of the stream with its own positions. A checkpoint saves a position in a checkpoint store (blob storage), which also drives load balancing across instances. Checkpoint every N events after the commit, replay with a starting position and a separate group, and make writes idempotent: delivery is at least once.
Let's set up the project
We run Microsoft's official Event Hubs emulator locally, with Azurite for the checkpoint store, and small Python scripts that use the azure-eventhub client and its blob checkpoint store, so every output is real. Features the emulator doesn't support are shown as code. The emulator reads its entities from Config.json: orders, clicks and payments with 4 partitions each, and invoices with 2. Orders has the consumer groups billing, fraud and warehouse, and invoices has replay. Before the first step we run python setup.py once. It creates one blob container per use, like cp-billing and cp-fraud. send.py sends a number of events to partition 0 of a hub.
{
"UserConfig": {
"NamespaceConfig": [
{
"Type": "EventHub",
"Name": "emulatorNs1",
"Entities": [
{
"Name": "orders",
"PartitionCount": 4,
"ConsumerGroups": [
{
"Name": "billing"
},
{
"Name": "fraud"
},
{
"Name": "warehouse"
}
]
},
{
"Name": "clicks",
"PartitionCount": 4,
"ConsumerGroups": []
},
{
"Name": "payments",
"PartitionCount": 4,
"ConsumerGroups": []
},
{
"Name": "invoices",
"PartitionCount": 2,
"ConsumerGroups": [
{
"Name": "replay"
}
]
}
]
}
],
"LoggingConfig": {
"Type": "File"
}
}
}import os
from azure.storage.blob import BlobServiceClient
blobs = BlobServiceClient.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"])
for name in ["cp-billing", "cp-fraud", "lb-2", "lb-4", "lb-5",
"every-event", "every-batch", "warehouse"]:
blobs.create_container(name) # one container per useimport os, sys
from azure.eventhub import EventHubProducerClient, EventData
hub, count = sys.argv[1], int(sys.argv[2])
producer = EventHubProducerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], eventhub_name=hub)
with producer:
batch = producer.create_batch(partition_id="0")
for i in range(1, count + 1):
batch.add(EventData(f"order-{i}"))
producer.send_batch(batch)
print("sent", count, "events to", hub, "partition 0")Question 1: A new service must read the stream without disturbing existing readers. How do consumer groups work?
A consumer group is an independent view of the event stream. Each group tracks its own position, and reading never removes events. So a new service simply gets its own consumer group.
Let's try it. We send six orders to partition 0 with python send.py orders 6. Then billing reads four and checkpoints, with python read.py billing 4, and fraud, a second group, reads six, with python read.py fraud 6. Last, python positions.py prints both checkpoints.
import logging, os, sys, threading
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
group, limit = sys.argv[1], int(sys.argv[2])
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"cp-{group}")
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], consumer_group=group,
eventhub_name="orders", checkpoint_store=store)
done, read = threading.Event(), []
def on_event(partition_context, event):
if len(read) == limit:
return # stopped: not processed
read.append(event.body_as_str()) # process, then checkpoint
partition_context.update_checkpoint(event)
if len(read) == limit:
done.set()
worker = threading.Thread(target=consumer.receive, kwargs=dict(
on_event=on_event, starting_position="-1")) # if no checkpoint
worker.start(); done.wait(8); consumer.close(); worker.join()
print(group, "read", read)import os
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
for group in ["billing", "fraud"]:
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"cp-{group}")
for cp in store.list_checkpoints("localhost", "orders", group):
print(group, "partition", cp["partition_id"],
"checkpoint at sequence", cp["sequence_number"])$ python send.py orders 6
sent 6 events to orders partition 0
$ python read.py billing 4
billing read ['order-1', 'order-2', 'order-3', 'order-4']
$ python read.py fraud 6
fraud read ['order-1', 'order-2', 'order-3', 'order-4', 'order-5', 'order-6']
$ python positions.py
billing partition 0 checkpoint at sequence 3
fraud partition 0 checkpoint at sequence 5Billing read order-1 to order-4. Fraud read all six, order-1 to order-6: billing took nothing away.
The checkpoints show it: billing partition 0 checkpoint at sequence 3 and fraud partition 0 checkpoint at sequence 5. Two positions on the same partition, one per group.
Here are the limits per event hub.
| Tier | Consumer groups per event hub |
|---|---|
| Basic | 1 |
| Standard | 20 |
| Premium | 100 |
| Dedicated | 1,000 |
Every event hub has the default group, and Microsoft allows up to five non-epoch readers per partition in one group.
Every application gets its own consumer group, never a shared default. And on the emulator, a group must be in its config file: an unknown group just returns nothing.
Question 2: A consumer restarts and processes everything from the beginning again. What is checkpointing?
A checkpoint is the consumer saving its position. With AMQP, that's the consumer's job. Without a checkpoint store, positions live only in memory, and a restart begins again at the starting position.
The Python client here uses a blob checkpoint store: one blob per consumer group and partition. Let's look inside with python blobs.py. Then we restart the billing consumer with python read.py billing 10, a new process that starts at -1, the beginning, and check the blobs again.
import os
from azure.storage.blob import ContainerClient
for group in ["billing", "fraud"]: # one container each
container = ContainerClient.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"cp-{group}")
owners = 0
for blob in container.list_blobs(include=["metadata"]):
if "/checkpoint/" in blob.name:
print(blob.name, dict(blob.metadata))
else:
owners += 1
print(f"cp-{group}: ownership blobs:", owners)$ python blobs.py
localhost/orders/billing/checkpoint/0 {'offset': '216', 'sequencenumber': '3'}
cp-billing: ownership blobs: 4
localhost/orders/fraud/checkpoint/0 {'offset': '360', 'sequencenumber': '5'}
cp-fraud: ownership blobs: 4
$ python read.py billing 10
billing read ['order-5', 'order-6']
$ python blobs.py
localhost/orders/billing/checkpoint/0 {'offset': '360', 'sequencenumber': '5'}
cp-billing: ownership blobs: 4
localhost/orders/fraud/checkpoint/0 {'offset': '360', 'sequencenumber': '5'}
cp-fraud: ownership blobs: 4The blob is named localhost/orders/billing/checkpoint/0: namespace, event hub, consumer group, checkpoint, partition. The position is in its metadata: {'offset': '216', 'sequencenumber': '3'}.
The restarted billing consumer reads only ['order-5', 'order-6']. The checkpoint wins over the starting position, and billing moves to 'sequencenumber': '5'.
Next to the checkpoints are ownership blobs: ownership blobs: 4 in each container, one per partition. They record which instance owns a partition, and that's how load balancing works.
Two tips from real projects:
- One container per consumer group - soft delete and versioning off
- Emulator restart - events gone, Azurite checkpoints kept: old offsets skip new events
The second one bites quietly: after an emulator restart, nothing fails, the consumer just skips the new events.
Question 3: Four instances of a consumer run at once. How does the processor balance partitions between them?
Through the checkpoint store. Every instance with the same consumer group and store claims partitions by writing ownership blobs, and the store makes sure only one instance owns a partition at a time.
Let's start two, four, then five instances on the clicks hub, which has four partitions: python balance.py 2, python balance.py 4 and python balance.py 5.
import collections, logging, os, sys, threading, time
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
n = int(sys.argv[1]) # instances to start
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"lb-{n}")
clients = []
for i in range(n):
client = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], "$Default",
eventhub_name="clicks", checkpoint_store=store,
load_balancing_interval=2, # default: 30 s
load_balancing_strategy="greedy") # the default
threading.Thread(target=client.receive, kwargs=dict(
on_event=lambda pc, e: None)).start()
clients.append(client)
time.sleep(15 if n == 2 else 30)
blobs = store.list_ownership("localhost", "clicks", "$Default")
owners = collections.Counter(b["owner_id"] for b in blobs)
counts = list(owners.values()) + [0] * (n - len(owners))
print(n, "instances, 4 partitions, partitions per instance:",
sorted(counts))
for client in clients: client.close()$ python balance.py 2
2 instances, 4 partitions, partitions per instance: [2, 2]
$ python balance.py 4
4 instances, 4 partitions, partitions per instance: [1, 1, 1, 1]
$ python balance.py 5
5 instances, 4 partitions, partitions per instance: [0, 1, 1, 1, 1]Two instances get [2, 2], and four get [1, 1, 1, 1]. Five get [0, 1, 1, 1, 1]: the fifth instance gets nothing, because partitions cap the parallel readers in a group.
Here are the client defaults.
| Setting | Default |
|---|---|
| load_balancing_interval | 30 s |
| ownership expires | 6 intervals: 180 s |
| strategy | greedy (or balanced) |
Each instance rechecks the balance every load balancing interval: 30 seconds by default, 2 seconds here to keep the demo short. Ownership expires after six intervals, so by default a crashed instance's partitions move after about three minutes.
The default strategy is greedy: it grabs all the unclaimed partitions it needs at once. Balanced claims one per cycle. Either way, an instance with too few steals one partition per cycle.
Size instances to partitions, and expect some rebalancing while you scale. If it goes on for more than five minutes, something's wrong.
Question 4: A teammate checkpoints after every single event and the job is slow. How often should you checkpoint?
Every checkpoint is a write to blob storage. Microsoft notes that checkpointing after each event has performance and cost implications, and suggests a queued pattern, where a Service Bus queue might fit better.
Let's measure it. We send 400 payments with python send.py payments 400. frequency.py reads them with receive_batch, 100 per batch. We run python frequency.py event, then python frequency.py batch.
import logging, os, sys, threading
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
mode = sys.argv[1] # "event" or "batch"
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"every-{mode}")
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], "$Default",
eventhub_name="payments", checkpoint_store=store)
stats = {"events": 0, "writes": 0}
def on_event_batch(partition_context, events):
for event in events:
stats["events"] += 1 # process the event
if mode == "event": # a blob write per event
partition_context.update_checkpoint(event)
stats["writes"] += 1
if mode == "batch" and events: # one write per batch
partition_context.update_checkpoint(events[-1])
stats["writes"] += 1
threading.Timer(12, consumer.close).start()
with consumer:
consumer.receive_batch(on_event_batch=on_event_batch,
max_batch_size=100, starting_position="-1")
cp = store.list_checkpoints("localhost", "payments", "$Default")
print(f"per {mode}: {stats['events']} events, {stats['writes']}",
"checkpoint writes, at sequence",
[c["sequence_number"] for c in cp])$ python send.py payments 400
sent 400 events to payments partition 0
$ python frequency.py event
per event: 400 events, 400 checkpoint writes, at sequence [399]
$ python frequency.py batch
per batch: 400 events, 4 checkpoint writes, at sequence [399]Per event: 400 events, 400 checkpoint writes. Per batch: 400 events, 4 checkpoint writes. Both end at sequence [399].
The trade-off is replay. After a crash, we reprocess everything since the last checkpoint, here up to 100 events. That's fine when the writes are idempotent.
So the rule is:
- Crash: replay since the checkpoint - idempotent writes
- Every N events or N seconds - whichever comes first
- After the commit - never before
I batch the work and checkpoint once per batch. It keeps storage calls low and the restart cost predictable.
Question 5: A bug corrupted a day of output. How do you reprocess from an offset or a point in time?
Set the starting position, as long as the events are still within retention. In Python, its type picks the filter.
| starting_position | Starts at |
|---|---|
| "-1" | the beginning of the partition |
| "@latest" | the end: new events only (the default) |
| a str, such as "360" | an offset |
| an int, such as 3 | a sequence number |
| a datetime | an enqueued time |
Let's try it. send_invoices.py sends six invoices, and the bug goes live before invoice 4. It saves the deploy time to a file. Then replay.py replays partition 0 twice: from sequence number 3, inclusive, and from the deploy time. We run python send_invoices.py and python replay.py.
import datetime, os, time
from azure.eventhub import EventHubProducerClient, EventData
producer = EventHubProducerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"],
eventhub_name="invoices")
with producer:
for i in [1, 2, 3]:
producer.send_event(EventData(f"inv-{i} ok"),
partition_id="0")
time.sleep(1)
deployed = datetime.datetime.now(datetime.timezone.utc)
open("bug_deployed_at.txt", "w").write(deployed.isoformat())
time.sleep(1) # the buggy release is live
for i in [4, 5, 6]:
producer.send_event(EventData(f"inv-{i} bad"),
partition_id="0")
print("sent inv-1 to inv-6; the bug went live before inv-4")import datetime, logging, os, threading
from azure.eventhub import EventHubConsumerClient
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
def replay(start, inclusive):
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"],
consumer_group="replay", eventhub_name="invoices")
got = []
threading.Timer(5, consumer.close).start()
with consumer:
consumer.receive(
on_event=lambda pc, e: got.append(e.body_as_str()),
partition_id="0", starting_position=start,
starting_position_inclusive=inclusive)
return got
print("from sequence number 3:", replay(3, True)) # an int
deployed = open("bug_deployed_at.txt").read()
start = datetime.datetime.fromisoformat(deployed) # a datetime
print("from the deploy time:", replay(start, False))$ python send_invoices.py
sent inv-1 to inv-6; the bug went live before inv-4
$ python replay.py
from sequence number 3: ['inv-4 bad', 'inv-5 bad', 'inv-6 bad']
from the deploy time: ['inv-4 bad', 'inv-5 bad', 'inv-6 bad']from sequence number 3: ['inv-4 bad', 'inv-5 bad', 'inv-6 bad']. And from the deploy time, the same three.
The catch: a checkpoint wins over the starting position. So replay with a separate consumer group, here replay, or a new checkpoint container, and the live consumer keeps running.
Replay is also a source of duplicates: the replayed events hit the same sinks again. So the writes must be idempotent, or we clean up the bad output first.
And mind retention.
| Tier | Max retention |
|---|---|
| Standard | 7 days |
| Premium / Dedicated | 90 days |
For anything older, replay from the Capture files in the data lake.
Question 6: Two readers on the same partition keep kicking each other off. What are epoch, or exclusive, receivers?
An owner level, also called an epoch, makes a receiver exclusive. On one partition and consumer group, the receiver with the highest owner level wins, and the others are disconnected.
Let's try three readers on partition 0. epoch.py connects reader A with owner level 1, then B with owner level 2, then C with no owner level. We run python epoch.py.
import logging, os, threading, time
from azure.eventhub import EventHubConsumerClient
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
log = set()
def reader(name, owner_level):
client = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"],
consumer_group="$Default", eventhub_name="orders")
def on_error(pc, error):
first = str(error).split(". ")[0] + "." # drop the run IDs
log.add(f"{name}: {type(error).__name__}: {first}")
def on_close(pc, reason):
log.add(f"{name}: closed, {reason}")
threading.Thread(target=client.receive, kwargs=dict(
on_event=lambda pc, e: None, on_error=on_error,
on_partition_close=on_close, partition_id="0",
owner_level=owner_level, max_wait_time=1)).start()
return client
a = reader("A owner_level=1", 1); time.sleep(4)
b = reader("B owner_level=2", 2); time.sleep(4)
c = reader("C no owner_level", None); time.sleep(4)
print(*sorted(log), sep="\n")
for client in (a, b, c): client.close()$ python epoch.py
A owner_level=1: ConnectionLostError: New receiver 'nil' with higher epoch of '2' is created hence
current receiver 'nil' with epoch '1' is getting disconnected.
A owner_level=1: closed, CloseReason.OWNERSHIP_LOST
C no owner_level: ConnectionLostError: At least one receiver for the endpoint is created with epoch of
'2', and so non-epoch receiver is not allowed.
C no owner_level: closed, CloseReason.OWNERSHIP_LOSTA gets a ConnectionLostError: a New receiver 'nil' with higher epoch of '2' is created, so A is disconnected, and its partition closes with CloseReason.OWNERSHIP_LOST. B owns partition 0.
C, with no owner level, is refused: non-epoch receiver is not allowed while an epoch receiver exists.
With a checkpoint store, the event processor uses this itself, with owner level 0. So when another instance takes a partition, the old owner is disconnected, and that error during load balancing is expected.
Look for two deployments sharing a consumer group with separate checkpoint stores, or a manual reader next to the processor. Give each one its own consumer group.
Scenario 7: A consumer writes to a database and must survive restarts without losing or double-writing events. How do you design it?
Event Hubs delivers at least once, so the design is: write first, checkpoint after, and make the write idempotent. A restart can redeliver events, but none is lost and no row is written twice.
The warehouse loader has its own consumer group, warehouse, and two steps per event:
- Upsert - an insert keyed by
order_id, withON CONFLICT DO NOTHING - Checkpoint - every two events, after the commit
Let's crash it. With CRASH_AT=2, loader.py exits right after writing order-3, before the next checkpoint, so the last checkpoint is order-2. Then we restart it with python loader.py.
import logging, os, sqlite3, threading
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
crash_at = int(os.environ.get("CRASH_AT", -1)) # simulate a crash
db = sqlite3.connect("warehouse.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS orders"
" (order_id TEXT PRIMARY KEY, seq INT)")
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], "warehouse")
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], "warehouse",
eventhub_name="orders", checkpoint_store=store,
load_balancing_interval=2) # ownership expires after 12 s
def on_event(partition_context, event):
order_id, seq = event.body_as_str(), event.sequence_number
with db: # 1. idempotent write by order_id
cur = db.execute("INSERT INTO orders VALUES (?, ?)"
" ON CONFLICT (order_id) DO NOTHING",
(order_id, seq))
print(order_id, "written" if cur.rowcount else "already there")
if seq == crash_at:
print("crash: written, not checkpointed"); os._exit(1)
if seq % 2 == 1: # 2. then checkpoint, every 2 events
partition_context.update_checkpoint(event)
threading.Timer(25, consumer.close).start()
with consumer:
consumer.receive(on_event=on_event, starting_position="-1")
rows = db.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
print("rows in the warehouse:", rows)$ CRASH_AT=2 python loader.py
order-1 written
order-2 written
order-3 written
crash: written, not checkpointed
$ python loader.py
order-3 already there
order-4 written
order-5 written
order-6 written
rows in the warehouse: 6The first run prints order-1 written, order-2 written, order-3 written, then crash: written, not checkpointed.
The restarted loader waits until the dead instance's ownership expires, 12 seconds with a 2 second interval, then resumes after order-2. Order 3 comes again: order-3 already there. Then order-4, order-5 and order-6 are written, and we get rows in the warehouse: 6. No gaps, no doubles.
A crash in between loses events. And when the sink can't do upserts, store the partition and sequence number with the data, and skip what's already there.
Key points to remember
- A consumer group = an independent view with its own positions
- Checkpoints live in blob storage: offset + sequence number per partition
- Ownership blobs drive load balancing: at most one owner per partition
- Checkpoint every N events, after the commit; replay with a separate group
- Owner level = exclusive reader; at-least-once means idempotent writes
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 #4 - Consumer groups and checkpointing
# 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_04_Code.py.
# Entities in Config.json: orders (4 partitions, groups billing, fraud, warehouse); clicks (4 partitions); payments (4 partitions); invoices (2 partitions, groups replay)
# 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('setup.py', """\
import os
from azure.storage.blob import BlobServiceClient
blobs = BlobServiceClient.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"])
for name in ["cp-billing", "cp-fraud", "lb-2", "lb-4", "lb-5",
"every-event", "every-batch", "warehouse"]:
blobs.create_container(name) # one container per use
""")
write('send.py', """\
import os, sys
from azure.eventhub import EventHubProducerClient, EventData
hub, count = sys.argv[1], int(sys.argv[2])
producer = EventHubProducerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], eventhub_name=hub)
with producer:
batch = producer.create_batch(partition_id="0")
for i in range(1, count + 1):
batch.add(EventData(f"order-{i}"))
producer.send_batch(batch)
print("sent", count, "events to", hub, "partition 0")
""")
run('python setup.py')
# Step 1: Two consumer groups read the same six orders, each with its own position
write('read.py', """\
import logging, os, sys, threading
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
group, limit = sys.argv[1], int(sys.argv[2])
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"cp-{group}")
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], consumer_group=group,
eventhub_name="orders", checkpoint_store=store)
done, read = threading.Event(), []
def on_event(partition_context, event):
if len(read) == limit:
return # stopped: not processed
read.append(event.body_as_str()) # process, then checkpoint
partition_context.update_checkpoint(event)
if len(read) == limit:
done.set()
worker = threading.Thread(target=consumer.receive, kwargs=dict(
on_event=on_event, starting_position="-1")) # if no checkpoint
worker.start(); done.wait(8); consumer.close(); worker.join()
print(group, "read", read)
""")
write('positions.py', """\
import os
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
for group in ["billing", "fraud"]:
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"cp-{group}")
for cp in store.list_checkpoints("localhost", "orders", group):
print(group, "partition", cp["partition_id"],
"checkpoint at sequence", cp["sequence_number"])
""")
run('python send.py orders 6')
run('python read.py billing 4')
run('python read.py fraud 6')
run('python positions.py')
# Step 2: Checkpoint blobs in Azurite, then the billing consumer restarts and resumes
write('blobs.py', """\
import os
from azure.storage.blob import ContainerClient
for group in ["billing", "fraud"]: # one container each
container = ContainerClient.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"cp-{group}")
owners = 0
for blob in container.list_blobs(include=["metadata"]):
if "/checkpoint/" in blob.name:
print(blob.name, dict(blob.metadata))
else:
owners += 1
print(f"cp-{group}: ownership blobs:", owners)
""")
run('python blobs.py')
run('python read.py billing 10')
run('python blobs.py')
# Step 3: Load balancing: 2, 4 and 5 instances on 4 partitions (load_balancing_interval=2)
write('balance.py', """\
import collections, logging, os, sys, threading, time
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
n = int(sys.argv[1]) # instances to start
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"lb-{n}")
clients = []
for i in range(n):
client = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], "$Default",
eventhub_name="clicks", checkpoint_store=store,
load_balancing_interval=2, # default: 30 s
load_balancing_strategy="greedy") # the default
threading.Thread(target=client.receive, kwargs=dict(
on_event=lambda pc, e: None)).start()
clients.append(client)
time.sleep(15 if n == 2 else 30)
blobs = store.list_ownership("localhost", "clicks", "$Default")
owners = collections.Counter(b["owner_id"] for b in blobs)
counts = list(owners.values()) + [0] * (n - len(owners))
print(n, "instances, 4 partitions, partitions per instance:",
sorted(counts))
for client in clients: client.close()
""")
run('python balance.py 2')
run('python balance.py 4')
run('python balance.py 5')
# Step 4: Checkpoint per event vs once per batch of 100
write('frequency.py', """\
import logging, os, sys, threading
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
mode = sys.argv[1] # "event" or "batch"
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], f"every-{mode}")
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], "$Default",
eventhub_name="payments", checkpoint_store=store)
stats = {"events": 0, "writes": 0}
def on_event_batch(partition_context, events):
for event in events:
stats["events"] += 1 # process the event
if mode == "event": # a blob write per event
partition_context.update_checkpoint(event)
stats["writes"] += 1
if mode == "batch" and events: # one write per batch
partition_context.update_checkpoint(events[-1])
stats["writes"] += 1
threading.Timer(12, consumer.close).start()
with consumer:
consumer.receive_batch(on_event_batch=on_event_batch,
max_batch_size=100, starting_position="-1")
cp = store.list_checkpoints("localhost", "payments", "$Default")
print(f"per {mode}: {stats['events']} events, {stats['writes']}",
"checkpoint writes, at sequence",
[c["sequence_number"] for c in cp])
""")
run('python send.py payments 400')
run('python frequency.py event')
run('python frequency.py batch')
# Step 5: Replay from a sequence number and from a point in time, with a separate consumer group
write('send_invoices.py', """\
import datetime, os, time
from azure.eventhub import EventHubProducerClient, EventData
producer = EventHubProducerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"],
eventhub_name="invoices")
with producer:
for i in [1, 2, 3]:
producer.send_event(EventData(f"inv-{i} ok"),
partition_id="0")
time.sleep(1)
deployed = datetime.datetime.now(datetime.timezone.utc)
open("bug_deployed_at.txt", "w").write(deployed.isoformat())
time.sleep(1) # the buggy release is live
for i in [4, 5, 6]:
producer.send_event(EventData(f"inv-{i} bad"),
partition_id="0")
print("sent inv-1 to inv-6; the bug went live before inv-4")
""")
write('replay.py', """\
import datetime, logging, os, threading
from azure.eventhub import EventHubConsumerClient
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
def replay(start, inclusive):
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"],
consumer_group="replay", eventhub_name="invoices")
got = []
threading.Timer(5, consumer.close).start()
with consumer:
consumer.receive(
on_event=lambda pc, e: got.append(e.body_as_str()),
partition_id="0", starting_position=start,
starting_position_inclusive=inclusive)
return got
print("from sequence number 3:", replay(3, True)) # an int
deployed = open("bug_deployed_at.txt").read()
start = datetime.datetime.fromisoformat(deployed) # a datetime
print("from the deploy time:", replay(start, False))
""")
run('python send_invoices.py')
run('python replay.py')
# Step 6: Owner level (epoch): a higher owner level takes the partition
write('epoch.py', 'import logging, os, threading, time\nfrom azure.eventhub import EventHubConsumerClient\nlogging.getLogger("azure.eventhub").setLevel(logging.ERROR)\nlog = set()\n\ndef reader(name, owner_level):\n client = EventHubConsumerClient.from_connection_string(\n os.environ["EVENTHUB_CONNECTION_STRING"],\n consumer_group="$Default", eventhub_name="orders")\n def on_error(pc, error):\n first = str(error).split(". ")[0] + "." # drop the run IDs\n log.add(f"{name}: {type(error).__name__}: {first}")\n def on_close(pc, reason):\n log.add(f"{name}: closed, {reason}")\n threading.Thread(target=client.receive, kwargs=dict(\n on_event=lambda pc, e: None, on_error=on_error,\n on_partition_close=on_close, partition_id="0",\n owner_level=owner_level, max_wait_time=1)).start()\n return client\n\na = reader("A owner_level=1", 1); time.sleep(4)\nb = reader("B owner_level=2", 2); time.sleep(4)\nc = reader("C no owner_level", None); time.sleep(4)\nprint(*sorted(log), sep="\\n")\nfor client in (a, b, c): client.close()\n')
run('python epoch.py')
# Step 7: A warehouse loader: idempotent write, then checkpoint; a crash and a restart
write('loader.py', """\
import logging, os, sqlite3, threading
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import (
BlobCheckpointStore)
logging.getLogger("azure.eventhub").setLevel(logging.ERROR)
crash_at = int(os.environ.get("CRASH_AT", -1)) # simulate a crash
db = sqlite3.connect("warehouse.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS orders"
" (order_id TEXT PRIMARY KEY, seq INT)")
store = BlobCheckpointStore.from_connection_string(
os.environ["STORAGE_CONNECTION_STRING"], "warehouse")
consumer = EventHubConsumerClient.from_connection_string(
os.environ["EVENTHUB_CONNECTION_STRING"], "warehouse",
eventhub_name="orders", checkpoint_store=store,
load_balancing_interval=2) # ownership expires after 12 s
def on_event(partition_context, event):
order_id, seq = event.body_as_str(), event.sequence_number
with db: # 1. idempotent write by order_id
cur = db.execute("INSERT INTO orders VALUES (?, ?)"
" ON CONFLICT (order_id) DO NOTHING",
(order_id, seq))
print(order_id, "written" if cur.rowcount else "already there")
if seq == crash_at:
print("crash: written, not checkpointed"); os._exit(1)
if seq % 2 == 1: # 2. then checkpoint, every 2 events
partition_context.update_checkpoint(event)
threading.Timer(25, consumer.close).start()
with consumer:
consumer.receive(on_event=on_event, starting_position="-1")
rows = db.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
print("rows in the warehouse:", rows)
""")
run('CRASH_AT=2 python loader.py', allow_error=True)
run('python loader.py', allow_error=True)
Part 5: Event Hubs for Apache Kafka
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.