In this post we are going to cover queues, Event Hubs and Service Bus triggers. These are 7 real Azure Functions interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: ten thousand IoT events per second must be cleaned and written to the lake.
Message triggers are how most data pipelines on Functions move work from one step to the next. A storage queue, an event hub or a Service Bus queue hands the function a message or a batch, and the function does its part. Interviewers ask about them because the hard parts are not in the happy path: retries, poison messages, checkpoints, ordering and what happens when a batch fails halfway.
Part 4 of the Real Time Azure Functions Interview Questions and Answers series on TechBrothersIT.
- The short answer
- Let's set up the project
- Question 1: A teammate asks how a queue trigger retries a message, and what a poison queue is. How do you explain it?
- Question 2: Someone asks how the Event Hubs trigger reads events and saves its position. How do checkpoints work?
- Question 3: Events must be processed in order per device. How do you keep ordering with Functions?
- Question 4: A teammate asks about batch size and prefetch settings for message triggers. How do you tune them?
- Question 5: Someone asks the difference between a storage queue and a Service Bus queue trigger. When do you use each?
- Question 6: A function crashes halfway through a batch of events. What happens to the rest of the batch?
- Scenario 7: Ten thousand IoT events per second must be cleaned and written to the lake. How do you design it?
- The full script
The short answer
A storage queue message gets five attempts, then goes to <queue>-poison. Event Hubs checkpoints per partition and moves on even when the function throws. Ordering comes from partition keys or Service Bus sessions, batch settings are per instance, and every handler must be safe to replay.
Let's set up the project
Everything below runs on the real Azure Functions host running locally with Core Tools, with Azurite, Microsoft's open-source storage emulator, for queues, blobs and tables. fhost runs func start in the background and prints the cleaned host log. There is no Event Hubs or Service Bus service locally, so those parts, and anything about scaling, are shown as code. Here are the starting files: the app's local settings and requirements, and small client scripts, such as send.py to send base64 messages and peek.py to look into a queue.
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functions
azure-data-tablesimport os, sys
from azure.core.exceptions import ResourceExistsError
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], sys.argv[1],
message_encode_policy=TextBase64EncodePolicy()) # base64, as expected
try:
q.create_queue()
except ResourceExistsError:
pass
for body in sys.argv[2:]:
q.send_message(body)
print(f"sent {len(sys.argv) - 2} message(s) to {sys.argv[1]}")import os, sys
from azure.storage.queue import QueueClient, TextBase64DecodePolicy
for name in sys.argv[1:]:
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], name,
message_decode_policy=TextBase64DecodePolicy())
bodies = [m.content for m in q.peek_messages(max_messages=32)]
print(f"{name}: {len(bodies)} message(s)", bodies)import subprocess, sys
n = int(sys.argv[1])
subprocess.run([sys.executable, "send.py", "clicks"]
+ [f"c{i:02d}" for i in range(1, n + 1)], check=True)import json, os
from azure.core.exceptions import HttpResponseError
from azure.storage.blob import BlobServiceClient
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
conn = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
q = QueueClient.from_connection_string(
conn, "orders-in", message_encode_policy=TextBase64EncodePolicy())
q.create_queue()
order = {"id": 5001, "lines": [{"sku": f"sku-{i:04d}", "qty": 1,
"price": 9.99} for i in range(1200)]}
body = json.dumps(order)
print("order 5001:", len(order["lines"]), "lines,", len(body), "bytes")
try:
q.send_message(body) # the whole order
except HttpResponseError as e:
print("send the order itself:", e.status_code, e.error_code.value)
blobs = BlobServiceClient.from_connection_string(conn)
blobs.create_container("payloads")
blobs.get_blob_client("payloads", "order_5001.json").upload_blob(body)
ref = json.dumps({"blob": "order_5001.json"}) # the claim check
q.send_message(ref)
print("sent the claim check instead:", len(ref), "bytes")import json, subprocess, sys
temps = {"e1": 21.5, "e2": 21.7, "e3": "n/a", "e4": 22.0, "e5": 22.1}
batch = {"batch": sys.argv[1], "device": "dev-17",
"events": [{"id": k, "temp": v} for k, v in temps.items()]}
subprocess.run([sys.executable, "send.py", "event-batches",
json.dumps(batch)], check=True)import json, os, sys
from azure.data.tables import TableClient
from azure.storage.queue import QueueClient, TextBase64DecodePolicy
conn = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
rows = TableClient.from_connection_string(conn, "readings").query_entities(
f"PartitionKey eq '{sys.argv[1]}'")
print(f"readings for {sys.argv[1]}:", sorted(r["RowKey"] for r in rows))
for name in sys.argv[2:]:
q = QueueClient.from_connection_string(
conn, name, message_decode_policy=TextBase64DecodePolicy())
msgs = [json.loads(m.content) for m in q.peek_messages(max_messages=32)]
print(f"{name}:", [f"{m['batch']} ({len(m['events'])} events)"
if "events" in m else json.dumps(m) for m in msgs])Question 1: A teammate asks how a queue trigger retries a message, and what a poison queue is. How do you explain it?
When the function succeeds, the host deletes the message. When it throws, the message becomes visible again after the visibility timeout, 0 by default. After five attempts, counting the first, it moves to a queue named after it plus -poison.
Let's see it. In host.json, batchSize 1 keeps our log in order, and maxDequeueCount 5 is the default, written out. The function rejects a quantity of zero. We send two orders with python send.py orders, then peek at both queues.
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:00",
"maxDequeueCount": 5
}
}
}import logging
import azure.functions as func
app = func.FunctionApp()
@app.queue_trigger(arg_name="msg", queue_name="orders",
connection="AzureWebJobsStorage")
def process_order(msg: func.QueueMessage) -> None:
order = msg.get_json()
logging.info("order %s, attempt %d", order["id"], msg.dequeue_count)
if order["qty"] <= 0:
raise ValueError(f"order {order['id']}: qty must be positive")
logging.info("order %s saved", order["id"])$ cd queue_app && fhost start
host started, functions:
process_order: queueTrigger
$ python send.py orders '{"id": 1001, "qty": 2}' '{"id": 1002, "qty": 0}'
sent 2 message(s) to orders
$ cd queue_app && fhost wait 'Moving message to queue' 60 && fhost log
Executing 'Functions.process_order' (Reason='New queue message detected on 'orders'.')
order 1001, attempt 1
order 1001 saved
Executed 'Functions.process_order' (Succeeded)
Executing 'Functions.process_order' (Reason='New queue message detected on 'orders'.')
order 1002, attempt 1
Executed 'Functions.process_order' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.process_order.
System.Private.CoreLib: Result: Failure
Exception: ValueError: order 1002: qty must be positive
Executing 'Functions.process_order' (Reason='New queue message detected on 'orders'.')
order 1002, attempt 2
Executed 'Functions.process_order' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.process_order.
System.Private.CoreLib: Result: Failure
Exception: ValueError: order 1002: qty must be positive
Executing 'Functions.process_order' (Reason='New queue message detected on 'orders'.')
order 1002, attempt 3
Executed 'Functions.process_order' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.process_order.
System.Private.CoreLib: Result: Failure
Exception: ValueError: order 1002: qty must be positive
Executing 'Functions.process_order' (Reason='New queue message detected on 'orders'.')
order 1002, attempt 4
Executed 'Functions.process_order' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.process_order.
System.Private.CoreLib: Result: Failure
Exception: ValueError: order 1002: qty must be positive
Executing 'Functions.process_order' (Reason='New queue message detected on 'orders'.')
order 1002, attempt 5
Executed 'Functions.process_order' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.process_order.
System.Private.CoreLib: Result: Failure
Exception: ValueError: order 1002: qty must be positive
Message has reached MaxDequeueCount of 5. Moving message to queue 'orders-poison'.
$ python peek.py orders orders-poison
orders: 0 message(s) []
orders-poison: 1 message(s) ['{"id": 1002, "qty": 0}']Order 1001 is saved on attempt 1. Order 1002 fails five times with ValueError: order 1002: qty must be positive, attempts 1 to 5, then Moving message to queue 'orders-poison'. At the end, orders has 0 message(s) and orders-poison holds {"id": 1002, "qty": 0}.
If the host crashes mid-run, the message is not lost. It reappears after the storage service's default 10-minute timeout. So delivery is at least once, and the function must be safe to run twice.
Nothing reads the poison queue by default, so alert on its length and keep a replay script. And no retry decorator here: retry policies only cover Timer, Event Hubs, Cosmos DB and Kafka triggers.
Question 2: Someone asks how the Event Hubs trigger reads events and saves its position. How do checkpoints work?
An event hub is split into partitions, and each partition is an append-only log. The position is a checkpoint: a pointer per partition, saved in the host storage account.
Let's walk through it. Devices send events into, say, four partitions. Per consumer group, one function instance holds the lease on a partition, so instance A might lease partitions 0 and 1 and instance B partitions 2 and 3. Each reads its partitions in batches, 100 events by default.
When the function finishes, with or without an exception, the trigger moves the pointer past the batch. By default it checkpoints after every batch. Here is what that means in each case:
| What happens | Checkpoint | Result |
|---|---|---|
| the function throws | moves past the batch | those events are skipped |
| throws, with a retry policy | waits for the retries | the partition pauses, then moves on |
| crash or timeout | does not move | the batch is read again: duplicates |
| no checkpoint yet | none | starts from the beginning (fromStart) |
So an exception doesn't stop the stream: those events are skipped. A retry policy holds the checkpoint until the retries finish. A crash or timeout doesn't move the pointer, so the batch is read again: at least once. There's no Event Hubs service locally, so this one is code:
from typing import List
import azure.functions as func
app = func.FunctionApp()
@app.event_hub_message_trigger(arg_name="events",
event_hub_name="telemetry",
connection="EventHubConnection",
consumer_group="lake-writer",
cardinality=func.Cardinality.MANY)
@app.retry(strategy="exponential_backoff", max_retry_count="5",
minimum_interval="00:00:02", maximum_interval="00:01:00")
def to_lake(events: List[func.EventHubEvent]) -> None:
for e in events: # one partition, in order
...
# returns or raises: the checkpoint moves past this batchAnd these are the defaults in host.json:
"extensions": {
"eventHubs": {
"maxEventBatchSize": 100,
"batchCheckpointFrequency": 1,
"prefetchCount": 300,
"initialOffsetOptions": { "type": "fromStart" }
}
}Give the app its own storage account, because checkpoints add a lot of transactions. And if you point AzureWebJobsStorage at another account, the checkpoints stay behind and events are processed again.
Question 3: Events must be processed in order per device. How do you keep ordering with Functions?
Ordering comes from the source. With Event Hubs, use the device ID as the partition key: same key, same partition, and a partition is read in order, by one instance per consumer group.
Here is the sender side:
import json
from azure.eventhub import EventData, EventHubProducerClient
producer = EventHubProducerClient.from_connection_string(
CONN, eventhub_name="telemetry")
batch = producer.create_batch(partition_key="dev-17")
for reading in readings: # same key: same partition
batch.add(EventData(json.dumps(reading)))
producer.send_batch(batch)Then don't break the order inside the function:
- Loop: not parallel, inside a batch
- Checkpoint: every batch (frequency 1)
- Retry policy: pauses the partition while it retries, instead of skipping a failed batch at once
With Service Bus, use sessions. Set the session ID to the device, and enable sessions on both the queue and the trigger. Sessions give ordered processing per session ID, and they need the Standard or Premium tier.
# sender: ServiceBusMessage(body, session_id="dev-17")
@app.service_bus_queue_trigger(arg_name="msg",
queue_name="device-events",
connection="ServiceBusConnection",
is_sessions_enabled=True)
def per_device(msg: func.ServiceBusMessage) -> None:
logging.info("%s #%s", msg.session_id, msg.sequence_number)
# the queue itself must be session-enabled (Standard or Premium)
az servicebus queue create -g rg-data --namespace-name sb-shop \
-n device-events --enable-session true --max-delivery-count 10Storage queues have no ordering guarantee: messages run in parallel, and batch size 1 only helps until the app scales out. Let's compare the three:
| Source | Order kept by | Parallelism |
|---|---|---|
| Event Hubs | partition key, one reader per partition | up to the partition count |
| Service Bus | sessions (Standard or Premium tier) | 8 sessions at once per instance (default) |
| Storage queue | no ordering guarantee | batch size per instance |
Ordering limits parallelism. Each partition has one reader, so the partition count caps it. Size partitions for the parallelism you need.
Question 4: A teammate asks about batch size and prefetch settings for message triggers. How do you tune them?
They live in host.json, and they apply per instance. Bigger batches give throughput, and smaller ones protect a downstream database.
Let's look at the settings for each trigger:
| Trigger | Settings (host.json) | Defaults |
|---|---|---|
| Storage queue | batchSize, newBatchThreshold | 16 (max 32) + 8 = 24 at once (Consumption) |
| Event Hubs | maxEventBatchSize, prefetchCount | 100 events, prefetch 300 |
| Service Bus | maxConcurrentCalls, prefetchCount | 16 x cores per instance, prefetch 0 |
A storage queue function fetches 16 messages and fetches more at the new batch threshold, so on Consumption up to 24 run at once. Event Hubs has maxEventBatchSize, 100 by default, and prefetchCount, 300. Service Bus has maxConcurrentCalls, 16 times the cores, and prefetchCount, 0 by default.
"extensions": {
"eventHubs": {
"maxEventBatchSize": 100,
"prefetchCount": 300
},
"serviceBus": {
"maxConcurrentCalls": 16,
"prefetchCount": 0,
"maxMessageBatchSize": 1000
}
}Now let's see the queue settings work. Our host.json has batchSize 4 and newBatchThreshold 0. We send twelve messages with python send_clicks.py 12, each taking one second, and the function tracks how many run at once.
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 4,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
}
}import logging, threading, time
import azure.functions as func
app = func.FunctionApp()
lock = threading.Lock()
state = {"running": 0, "peak": 0, "done": 0}
@app.queue_trigger(arg_name="msg", queue_name="clicks",
connection="AzureWebJobsStorage")
def count_click(msg: func.QueueMessage) -> None:
with lock:
state["running"] += 1
state["peak"] = max(state["peak"], state["running"])
time.sleep(1) # one second of work
with lock:
state["running"] -= 1
state["done"] += 1
if state["done"] == 12:
logging.info("12 clicks done, peak in flight: %d",
state["peak"])$ cd queue_app && fhost start
host started, functions:
count_click: queueTrigger
$ python send_clicks.py 12
sent 12 message(s) to clicks
$ cd queue_app && fhost wait "Executed 'Functions.count_click'" 60 12 && fhost log | grep peak
12 clicks done, peak in flight: 4The log says 12 clicks done, peak in flight: 4. Never more than one batch.
Remember the multiplication: 10 instances at 24 queue messages is 240 at once. These values are also the targets for target-based scaling. For sync Python, the worker's thread pool also caps how many run at once, so tune PYTHON_THREADPOOL_THREAD_COUNT with it.
Change one knob at a time, then measure.
Question 5: Someone asks the difference between a storage queue and a Service Bus queue trigger. When do you use each?
A storage queue is simple and lives in a storage account you already have. Service Bus is a full broker, with sessions, a dead-letter queue, topics and transactions.
Let's compare them side by side:
| Storage queue | Service Bus queue | |
|---|---|---|
| lives in | the storage account you have (64 KB messages) | a Service Bus namespace |
| ordering | no guarantee | sessions |
| failed messages | 5 attempts, then <queue>-poison | max delivery count (10), then dead-letter queue |
| locking | visibility timeout | peek-lock, auto-renewed up to 5 min |
| fan-out | one consumer per message | topics and subscriptions |
| transactions | no | yes, across entities |
The size limit bites: 64 KB per message, and base64 makes the usable payload smaller. Our test order has 1,200 lines. We run python big_order.py, which tries to send it, then sends a claim check instead: the payload goes in a blob, and the message carries only its name. The function binds the blob from {blob} in the message.
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:00",
"maxDequeueCount": 5
}
}
}import json, logging
import azure.functions as func
app = func.FunctionApp()
@app.queue_trigger(arg_name="msg", queue_name="orders-in",
connection="AzureWebJobsStorage")
@app.blob_input(arg_name="payload", path="payloads/{blob}",
connection="AzureWebJobsStorage")
def load_order(msg: func.QueueMessage, payload: str) -> None:
order = json.loads(payload) # {blob} from the message
logging.info("order %s: %d lines read from payloads/%s",
order["id"], len(order["lines"]), msg.get_json()["blob"])$ cd queue_app && fhost start
host started, functions:
load_order: queueTrigger
$ python big_order.py
order 5001: 1200 lines, 55223 bytes
send the order itself: 413 RequestBodyTooLarge
sent the claim check instead: 27 bytes
$ cd queue_app && fhost wait "Executed 'Functions.load_order'" 60 && fhost log
Executing 'Functions.load_order' (Reason='New queue message detected on 'orders-in'.')
order 5001: 1200 lines read from payloads/order_5001.json
Executed 'Functions.load_order' (Succeeded)The order is 1200 lines, 55223 bytes, and the queue rejects it with 413 RequestBodyTooLarge. The claim check is 27 bytes, and the function logs order 5001: 1200 lines read from payloads/order_5001.json.
Storage queues for simple background work between functions. Service Bus when you need ordering, a dead-letter queue to inspect, or several subscribers.
Question 6: A function crashes halfway through a batch of events. What happens to the rest of the batch?
It depends on the trigger, and on throw versus crash. Let's go through each:
| Trigger | The function throws | Crash or timeout |
|---|---|---|
| Event Hubs | checkpoint moves: the rest is skipped | no checkpoint: the whole batch again |
| Service Bus | whole batch redelivered, up to max delivery count | back after the lock expires |
| Storage queue | retried, then <queue>-poison | reappears after about 10 minutes |
With Event Hubs, an exception still checkpoints the batch, so the rest is skipped. A crash or timeout means no checkpoint, so the whole batch comes back, including events already written. Service Bus abandons the whole batch, and a storage queue message is retried, then poisoned.
Let's see a batch loop on a queue message, since Event Hubs needs the real service. The batch has five events, and e3 has the temperature "n/a". Here maxDequeueCount is 2. We run python send_batch.py b-1.
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"maxDequeueCount": 2
}
}
}import logging, os
import azure.functions as func
from azure.data.tables import TableServiceClient
logging.getLogger("azure").setLevel(logging.WARNING)
app = func.FunctionApp()
readings = TableServiceClient.from_connection_string(
os.environ["AzureWebJobsStorage"]
).create_table_if_not_exists("readings")
@app.queue_trigger(arg_name="msg", queue_name="event-batches",
connection="AzureWebJobsStorage")
def apply_batch(msg: func.QueueMessage) -> None:
batch = msg.get_json()
for e in batch["events"]:
temp = float(e["temp"]) # e3 is "n/a"
readings.upsert_entity({"PartitionKey": batch["batch"],
"RowKey": e["id"], "temp": temp})
logging.info("%s wrote %s (attempt %d)", batch["batch"], e["id"],
msg.dequeue_count)$ cd queue_app && fhost start
host started, functions:
apply_batch: queueTrigger
$ python send_batch.py b-1
sent 1 message(s) to event-batches
$ cd queue_app && fhost wait 'Moving message to queue' 60 && fhost log
Executing 'Functions.apply_batch' (Reason='New queue message detected on 'event-batches'.')
b-1 wrote e1 (attempt 1)
b-1 wrote e2 (attempt 1)
Executed 'Functions.apply_batch' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply_batch.
System.Private.CoreLib: Result: Failure
Exception: ValueError: could not convert string to float: 'n/a'
Executing 'Functions.apply_batch' (Reason='New queue message detected on 'event-batches'.')
b-1 wrote e1 (attempt 2)
b-1 wrote e2 (attempt 2)
Executed 'Functions.apply_batch' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply_batch.
System.Private.CoreLib: Result: Failure
Exception: ValueError: could not convert string to float: 'n/a'
Message has reached MaxDequeueCount of 2. Moving message to queue 'event-batches-poison'.
$ python rows.py b-1 event-batches-poison
readings for b-1: ['e1', 'e2']
event-batches-poison: ['b-1 (5 events)']e1 and e2 are written, e3 throws could not convert string to float: 'n/a', and e4 and e5 never run. The retry writes e1 and e2 again, on attempt 2, then the batch moves to event-batches-poison. The table has only ['e1', 'e2'].
The fix: catch the errors that can never succeed, per event, and park those events on an events-failed queue. We send batch b-2.
import json, logging, os
from typing import List
import azure.functions as func
from azure.data.tables import TableServiceClient
logging.getLogger("azure").setLevel(logging.WARNING)
app = func.FunctionApp()
readings = TableServiceClient.from_connection_string(
os.environ["AzureWebJobsStorage"]
).create_table_if_not_exists("readings")
@app.queue_trigger(arg_name="msg", queue_name="event-batches",
connection="AzureWebJobsStorage")
@app.queue_output(arg_name="failed", queue_name="events-failed",
connection="AzureWebJobsStorage")
def apply_batch(msg: func.QueueMessage, failed: func.Out[List[str]]):
batch, parked = msg.get_json(), []
for e in batch["events"]:
try:
temp = float(e["temp"]) # can never succeed
except (KeyError, TypeError, ValueError) as err:
parked.append(json.dumps({"id": e["id"], "error": str(err)}))
continue
readings.upsert_entity({"PartitionKey": batch["batch"],
"RowKey": e["id"], "temp": temp})
failed.set(parked) # one message each
logging.info("%s: wrote %d, parked %d", batch["batch"],
len(batch["events"]) - len(parked), len(parked))$ cd queue_app && fhost start
host started, functions:
apply_batch: queueTrigger
$ python send_batch.py b-2
sent 1 message(s) to event-batches
$ cd queue_app && fhost wait "Executed 'Functions.apply_batch'" 60 && fhost log
Executing 'Functions.apply_batch' (Reason='New queue message detected on 'event-batches'.')
b-2: wrote 4, parked 1
Executed 'Functions.apply_batch' (Succeeded)
$ python rows.py b-2 events-failed
readings for b-2: ['e1', 'e2', 'e4', 'e5']
events-failed: ['{"id": "e3", "error": "could not convert string to float: \'n/a\'"}']
$ cd queue_app && fhost stop
host stoppedNow we get b-2: wrote 4, parked 1. The table has e1, e2, e4 and e5, and events-failed holds e3 with its error.
Catch only what can never succeed. Let transient errors, like a database timeout, throw so the batch retries (on Event Hubs, only with a retry policy), and write with upserts so a replay is harmless.
Scenario 7: Ten thousand IoT events per second must be cleaned and written to the lake. How do you design it?
Event Hubs in front, the device ID as the partition key, and a function that cleans big batches and writes one file per batch to the lake.
First, size the hub. A Standard throughput unit takes up to 1,000 events a second, so we need at least ten. Partitions cap parallelism, one reader each, and on Standard the count is fixed at creation, so we pick 32.
az eventhubs namespace create -g rg-iot -n eh-iot --sku Standard \
--capacity 10 --enable-auto-inflate true \
--maximum-throughput-units 20 # 1 TU: up to 1,000 events/s in
az eventhubs eventhub create -g rg-iot --namespace-name eh-iot \
-n iot-telemetry --partition-count 32 # fixed on StandardThen the function. It takes batches, 100 events by default. That is about a hundred files a second, so we raise maxEventBatchSize and compact small files in the lake. Each batch is cleaned in memory and written as one file. Bad events are parked one by one, so the stream keeps moving.
import json
from typing import List
import azure.functions as func
# app, clean(), write_file(), park(): defined elsewhere in the app
@app.event_hub_message_trigger(arg_name="events",
event_hub_name="iot-telemetry", connection="EventHubConnection",
consumer_group="lake-writer", cardinality=func.Cardinality.MANY)
def to_lake(events: List[func.EventHubEvent],
context: func.Context) -> None:
good, bad = [], []
for e in events: # in partition order
try:
good.append(clean(json.loads(e.get_body())))
except (ValueError, KeyError) as err:
bad.append({"seq": e.sequence_number, "error": str(err)})
write_file(f"telemetry/{context.invocation_id}.jsonl", good)
park(bad) # a queue or blob: the stream keeps movingWe host it on Flex Consumption, with per-function scaling and a maximum instance count (default 100), or on Premium for always-warm instances. Checkpoints go to their own storage account.
Before go-live:
- Load test: at real volume, watch the consumer lag
- Alert: on parked events
- Joins, aggregations: a streaming engine like Databricks fits better
A crash replays a whole batch, so the lake job must dedupe on event ID. Never assume each event lands exactly once.
Key points to remember
- Storage queues: five attempts counting the first, then <queue>-poison; at-least-once
- Event Hubs checkpoints per partition, and moves on even when the function throws
- Order per device: partition key or Service Bus sessions, then a sequential loop
- Batch and concurrency settings are per instance: multiply by the instance count
- Inside a batch: park what can never succeed, let transient errors retry, write with upserts
The full script
Here is a Python script that writes every file and runs every command in order with Core Tools and Azurite; run pip install azure-functions azure-functions-durable azure-storage-blob azure-storage-queue azure-data-tables first.
Show the full script that writes the files and runs every step
# ========================================================================
# Azure Functions Interview Q&A #4 - Queues, Event Hubs and Service Bus triggers
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run with Azure Functions Core Tools 4.16.0 (Functions host 4.x, Python 3.13 worker,
# programming model v2, extension bundle 4.x) and Azurite 3.37.0; the outputs in the video and the blog post are the real outputs.
# To run it yourself (Linux or macOS shell, or WSL on Windows):
# 1. Install Azure Functions Core Tools 4 and Azurite (npm install -g azurite), then start Azurite:
# azurite --skipApiVersionCheck --location ./azurite-data (blob 10000, queue 10001, table 10002)
# 2. pip install azure-functions azure-functions-durable azure-storage-blob azure-storage-queue azure-data-tables
# 3. Set AZURE_STORAGE_CONNECTION_STRING to "UseDevelopmentStorage=true", then run python Functions_Interview_QA_04_Code.py.
# "fhost" in the commands is a small helper written by Step 0 (fhost.py): it runs `func start` in the background,
# waits until the functions are loaded, and prints the host log lines without timestamps and invocation ids.
# Run it in an empty folder and on a freshly started emulator: it creates its files (and any local data
# files) there, and a second run on old data gives different output.
# 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 fhost helper and the starting files
write("fhost.py", '"""fhost: run the Azure Functions host (func start) in the background of the current folder, for scripted demos.\n fhost start [port] [-- extra func args] start `func start`, wait until the functions are indexed, print them\n (and any indexing errors)\n fhost wait PATTERN [secs] [count] wait until `count` (default 1) NEW host log lines (not yet shown by\n `fhost log`) match the regex PATTERN (default timeout 60 s)\n fhost log [--all] [--details] [--since-start]\n print the host log lines written since the last `fhost log` (function logs,\n Executing / Executed lines, exceptions); --details also keeps the\n "Trigger Details" lines, --all keeps every line, --since-start starts at the\n first line after the function list. Timestamps, invocation ids, durations and\n other per-run values are removed.\n fhost stop stop the host\nThe log is kept in .fhost.log in the current folder (one host per folder)."""\nimport os, re, signal, subprocess, sys, time\nLOG, PID, OFF, START = \'.fhost.log\', \'.fhost.pid\', \'.fhost.off\', \'.fhost.start\'\nTS = re.compile(r\'\\[\\d{4}-\\d\\d-\\d\\dT[\\d:.]+Z\\] \')\n# host messages to hide (anchored at the start of the cleaned line, so user log lines that merely contain these words stay)\nNOISE = re.compile(r\'^(Worker process started|Host lock lease|Found Python version|Azure Functions Core Tools|Core Tools Version|\'\n r\'Function Runtime Version|For detailed output|Using cached version|When you have network connectivity|\'\n r\'Warning: Unable to download extension|Host started|Job host started|Host initialized|Loading functions metadata|\'\n r\'Reading functions metadata|Starting Host|Initializing Warmup|Generating \\d+ job function|Functions:$|\'\n r\'Debugger listening|Host Status|Starting worker process|Worker failed to load|Retrieving function|\'\n r\'\\d+ functions? (found|loaded)|Successfully (found|loaded|registered)|Application Insights|WARNING: )\')\nDETAILS = re.compile(r\'^Trigger Details:\')\n\ndef clean(l):\n l = TS.sub(\'\', l.rstrip(\'\\n\'))\n l = re.sub(r\', Id=[0-9a-f-]{36}\', \'\', l)\n l = re.sub(r\'Id=[0-9a-f-]{36}\', \'\', l)\n l = re.sub(r\', Duration=\\d+ms\', \'\', l)\n l = re.sub(r\'\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b\', \'<id>\', l)\n l = re.sub(r\'\\b[0-9a-f]{32}\\b\', \'<instance-id>\', l)\n l = re.sub(r\'\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(\\.\\d+)?(Z|[+-]\\d\\d:\\d\\d)?\', \'<time>\', l)\n l = re.sub(r\'"?0x[0-9A-F]{15,16}"?\', \'<etag>\', l)\n l = re.sub(r\'([?&]code=)[^&\\s"]+\', r\'\\1<key>\', l)\n l = re.sub(r\'Threadpool id: \\d+\', \'Threadpool id: <n>\', l)\n l = re.sub(r\'(processUptime\\W+)\\d+\', r\'\\1<n>\', l)\n return l.replace(\' ()\', \'\').rstrip()\n\ndef read_from(off):\n """complete lines from byte offset `off`; returns (lines, new_offset). A glued line ([ts] a [ts] b) is split."""\n if not os.path.exists(LOG): return [], off\n with open(LOG, \'rb\') as f:\n f.seek(off); data = f.read()\n end = data.rfind(b\'\\n\')\n if end < 0: return [], off\n chunk = data[:end + 1].decode(\'utf-8\', \'replace\')\n out = []\n for l in chunk.split(\'\\n\')[:-1]:\n parts = [p for p in re.split(r\'(?=\\[\\d{4}-\\d\\d-\\d\\dT[\\d:.]+Z\\] )\', l) if p.strip()] or [\'\']\n out += parts\n return out, off + end + 1\n\ndef get(f, d=0):\n return int(open(f).read()) if os.path.exists(f) else d\n\ndef filtered(lines, all_=False, details=False):\n out, in_stack, last_exc = [], False, None\n for l in lines:\n raw = TS.sub(\'\', l)\n if in_stack:\n if raw.startswith((\' \', \'\\t\')): continue\n in_stack = False\n c = clean(l)\n if not c: continue\n if c.startswith(\'Stack:\') and not all_: in_stack = True; continue\n if not all_ and (c in (\'Type:\', \'.\') or c == last_exc): continue\n if c.startswith(\'Exception: \'): last_exc = c[len(\'Exception: \'):]\n if all_ or (details and DETAILS.search(c)): out.append(c); continue\n if NOISE.search(c) or DETAILS.search(c): continue\n out.append(c)\n return out\n\ndef start(*args):\n port, extra = \'7071\', []\n if args and args[0] != \'--\': port = args[0]; args = args[1:]\n if args and args[0] == \'--\': extra = list(args[1:])\n if os.path.exists(PID): stop(quiet=True)\n for f in (LOG, OFF, START):\n if os.path.exists(f): os.remove(f)\n out = open(LOG, \'w\')\n p = subprocess.Popen([\'func\', \'start\', \'--port\', port] + extra, stdout=out, stderr=subprocess.STDOUT,\n stdin=subprocess.DEVNULL, start_new_session=True)\n open(PID, \'w\').write(str(p.pid))\n t0 = time.time()\n while time.time() - t0 < 120:\n txt = open(LOG, encoding=\'utf-8\', errors=\'replace\').read()\n if p.poll() is not None:\n print(\'\\n\'.join(filtered(txt.split(\'\\n\'), all_=True)[-30:])); sys.exit(\'host exited\')\n m = re.search(r\'\\nFunctions:\\n(.*?)\\n(For detailed output[^\\n]*\\n)\', txt, re.S)\n if m and \'Worker process started and initialized\' in txt:\n errs = [clean(l) for l in txt[:m.start()].split(\'\\n\')\n if re.search(r\'in error|failed indexing|Error indexing|will be disabled\', l)]\n names = [clean(l).strip() for l in m.group(1).split(\'\\n\') if l.strip()]\n boundary = len(txt[:m.end()].encode(\'utf-8\'))\n open(START, \'w\').write(str(boundary)); open(OFF, \'w\').write(str(boundary))\n time.sleep(1.5) # let triggers start listening\n for e in errs: print(e)\n print(\'host started, functions:\')\n for n in names: print(\' \' + re.sub(r\'http://localhost:\\d+\', \'http://localhost:\' + port, n))\n return\n if not m and re.search(r\'\\n\\[[^\\]]*\\] (Job host started|Host started)\', txt) and \'Worker process started and initialized\' in txt:\n time.sleep(1.5)\n boundary = len(txt.encode(\'utf-8\')); open(START, \'w\').write(str(boundary)); open(OFF, \'w\').write(str(boundary))\n for l in txt.split(\'\\n\'):\n if re.search(r\'in error|failed indexing|is disabled\', l): print(clean(l))\n print(\'host started, no enabled functions listed\'); return\n if re.search(r\'No job functions found|A host error has occurred\', txt):\n time.sleep(1); print(\'\\n\'.join(filtered(txt.split(\'\\n\'), all_=True)[-30:])); stop(quiet=True); sys.exit(\'host error\')\n time.sleep(0.3)\n print(\'\\n\'.join(filtered(open(LOG).read().split(\'\\n\'), all_=True)[-30:])); stop(quiet=True)\n sys.exit(\'host did not start in 120 s\')\n\ndef wait(pat, secs=\'60\', count=\'1\'):\n rx, t0, need = re.compile(pat), time.time(), int(count)\n while time.time() - t0 < float(secs):\n lines, _ = read_from(get(OFF))\n if sum(1 for l in lines if rx.search(clean(l))) >= need: return\n time.sleep(0.2)\n lines, _ = read_from(get(OFF))\n print(\'\\n\'.join(filtered(lines)[-20:])); sys.exit(\'timed out waiting for %r\' % pat)\n\ndef log(all_=False, details=False, since_start=False):\n off = get(START) if since_start else get(OFF)\n lines, new = read_from(off)\n if not since_start or new > get(OFF): open(OFF, \'w\').write(str(new))\n for c in filtered(lines, all_, details): print(c)\n\ndef stop(quiet=False):\n if not os.path.exists(PID): return\n pid = int(open(PID).read())\n for sig in (signal.SIGTERM, signal.SIGKILL):\n try: os.killpg(pid, sig)\n except Exception: break\n for _ in range(50):\n try: os.killpg(pid, 0); time.sleep(0.1)\n except Exception: break\n os.remove(PID)\n if not quiet: print(\'host stopped\')\n\nif __name__ == \'__main__\':\n a = sys.argv[1:] or [\'help\']\n if a[0] == \'start\': start(*a[1:])\n elif a[0] == \'wait\': wait(*a[1:])\n elif a[0] == \'log\': log(\'--all\' in a, \'--details\' in a, \'--since-start\' in a)\n elif a[0] == \'stop\': stop()\n else: print(__doc__)\n')
os.environ["FHOST"] = os.path.abspath("fhost.py") # commands below run it as: python "$FHOST" ...
write('queue_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('queue_app/requirements.txt', """\
azure-functions
azure-data-tables
""")
write('send.py', """\
import os, sys
from azure.core.exceptions import ResourceExistsError
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], sys.argv[1],
message_encode_policy=TextBase64EncodePolicy()) # base64, as expected
try:
q.create_queue()
except ResourceExistsError:
pass
for body in sys.argv[2:]:
q.send_message(body)
print(f"sent {len(sys.argv) - 2} message(s) to {sys.argv[1]}")
""")
write('peek.py', """\
import os, sys
from azure.storage.queue import QueueClient, TextBase64DecodePolicy
for name in sys.argv[1:]:
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], name,
message_decode_policy=TextBase64DecodePolicy())
bodies = [m.content for m in q.peek_messages(max_messages=32)]
print(f"{name}: {len(bodies)} message(s)", bodies)
""")
write('send_clicks.py', """\
import subprocess, sys
n = int(sys.argv[1])
subprocess.run([sys.executable, "send.py", "clicks"]
+ [f"c{i:02d}" for i in range(1, n + 1)], check=True)
""")
write('big_order.py', """\
import json, os
from azure.core.exceptions import HttpResponseError
from azure.storage.blob import BlobServiceClient
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
conn = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
q = QueueClient.from_connection_string(
conn, "orders-in", message_encode_policy=TextBase64EncodePolicy())
q.create_queue()
order = {"id": 5001, "lines": [{"sku": f"sku-{i:04d}", "qty": 1,
"price": 9.99} for i in range(1200)]}
body = json.dumps(order)
print("order 5001:", len(order["lines"]), "lines,", len(body), "bytes")
try:
q.send_message(body) # the whole order
except HttpResponseError as e:
print("send the order itself:", e.status_code, e.error_code.value)
blobs = BlobServiceClient.from_connection_string(conn)
blobs.create_container("payloads")
blobs.get_blob_client("payloads", "order_5001.json").upload_blob(body)
ref = json.dumps({"blob": "order_5001.json"}) # the claim check
q.send_message(ref)
print("sent the claim check instead:", len(ref), "bytes")
""")
write('send_batch.py', """\
import json, subprocess, sys
temps = {"e1": 21.5, "e2": 21.7, "e3": "n/a", "e4": 22.0, "e5": 22.1}
batch = {"batch": sys.argv[1], "device": "dev-17",
"events": [{"id": k, "temp": v} for k, v in temps.items()]}
subprocess.run([sys.executable, "send.py", "event-batches",
json.dumps(batch)], check=True)
""")
write('rows.py', """\
import json, os, sys
from azure.data.tables import TableClient
from azure.storage.queue import QueueClient, TextBase64DecodePolicy
conn = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
rows = TableClient.from_connection_string(conn, "readings").query_entities(
f"PartitionKey eq '{sys.argv[1]}'")
print(f"readings for {sys.argv[1]}:", sorted(r["RowKey"] for r in rows))
for name in sys.argv[2:]:
q = QueueClient.from_connection_string(
conn, name, message_decode_policy=TextBase64DecodePolicy())
msgs = [json.loads(m.content) for m in q.peek_messages(max_messages=32)]
print(f"{name}:", [f"{m['batch']} ({len(m['events'])} events)"
if "events" in m else json.dumps(m) for m in msgs])
""")
# Step 1: Queue retries: a good order saves once, a bad order fails five times and moves to orders-poison
write('queue_app/host.json', """\
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:00",
"maxDequeueCount": 5
}
}
}
""")
write('queue_app/function_app.py', """\
import logging
import azure.functions as func
app = func.FunctionApp()
@app.queue_trigger(arg_name="msg", queue_name="orders",
connection="AzureWebJobsStorage")
def process_order(msg: func.QueueMessage) -> None:
order = msg.get_json()
logging.info("order %s, attempt %d", order["id"], msg.dequeue_count)
if order["qty"] <= 0:
raise ValueError(f"order {order['id']}: qty must be positive")
logging.info("order %s saved", order["id"])
""")
run('cd queue_app && python "$FHOST" start')
run('python send.py orders \'{"id": 1001, "qty": 2}\' \'{"id": 1002, "qty": 0}\'')
run('cd queue_app && python "$FHOST" wait \'Moving message to queue\' 60 && python "$FHOST" log')
run('python peek.py orders orders-poison')
# Step 2: batchSize 4 and newBatchThreshold 0: twelve one-second messages, at most four in flight
write('queue_app/host.json', """\
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 4,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
}
}
""")
write('queue_app/function_app.py', """\
import logging, threading, time
import azure.functions as func
app = func.FunctionApp()
lock = threading.Lock()
state = {"running": 0, "peak": 0, "done": 0}
@app.queue_trigger(arg_name="msg", queue_name="clicks",
connection="AzureWebJobsStorage")
def count_click(msg: func.QueueMessage) -> None:
with lock:
state["running"] += 1
state["peak"] = max(state["peak"], state["running"])
time.sleep(1) # one second of work
with lock:
state["running"] -= 1
state["done"] += 1
if state["done"] == 12:
logging.info("12 clicks done, peak in flight: %d",
state["peak"])
""")
run('cd queue_app && python "$FHOST" start')
run('python send_clicks.py 12')
run('cd queue_app && python "$FHOST" wait "Executed \'Functions.count_click\'" 60 12 && python "$FHOST" log | grep peak')
# Step 3: A 1,200-line order is too large for a storage queue message; send a claim check instead
write('queue_app/host.json', """\
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:00",
"maxDequeueCount": 5
}
}
}
""")
write('queue_app/function_app.py', """\
import json, logging
import azure.functions as func
app = func.FunctionApp()
@app.queue_trigger(arg_name="msg", queue_name="orders-in",
connection="AzureWebJobsStorage")
@app.blob_input(arg_name="payload", path="payloads/{blob}",
connection="AzureWebJobsStorage")
def load_order(msg: func.QueueMessage, payload: str) -> None:
order = json.loads(payload) # {blob} from the message
logging.info("order %s: %d lines read from payloads/%s",
order["id"], len(order["lines"]), msg.get_json()["blob"])
""")
run('cd queue_app && python "$FHOST" start')
run('python big_order.py')
run('cd queue_app && python "$FHOST" wait "Executed \'Functions.load_order\'" 60 && python "$FHOST" log')
# Step 4: A batch of five events, the third one bad: the loop stops there, the retry writes e1 and e2 again
write('queue_app/host.json', """\
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"maxDequeueCount": 2
}
}
}
""")
write('queue_app/function_app.py', """\
import logging, os
import azure.functions as func
from azure.data.tables import TableServiceClient
logging.getLogger("azure").setLevel(logging.WARNING)
app = func.FunctionApp()
readings = TableServiceClient.from_connection_string(
os.environ["AzureWebJobsStorage"]
).create_table_if_not_exists("readings")
@app.queue_trigger(arg_name="msg", queue_name="event-batches",
connection="AzureWebJobsStorage")
def apply_batch(msg: func.QueueMessage) -> None:
batch = msg.get_json()
for e in batch["events"]:
temp = float(e["temp"]) # e3 is "n/a"
readings.upsert_entity({"PartitionKey": batch["batch"],
"RowKey": e["id"], "temp": temp})
logging.info("%s wrote %s (attempt %d)", batch["batch"], e["id"],
msg.dequeue_count)
""")
run('cd queue_app && python "$FHOST" start')
run('python send_batch.py b-1')
run('cd queue_app && python "$FHOST" wait \'Moving message to queue\' 60 && python "$FHOST" log')
run('python rows.py b-1 event-batches-poison')
# Step 5: Per-event handling: the bad event is parked on events-failed, the other four are written
write('queue_app/function_app.py', """\
import json, logging, os
from typing import List
import azure.functions as func
from azure.data.tables import TableServiceClient
logging.getLogger("azure").setLevel(logging.WARNING)
app = func.FunctionApp()
readings = TableServiceClient.from_connection_string(
os.environ["AzureWebJobsStorage"]
).create_table_if_not_exists("readings")
@app.queue_trigger(arg_name="msg", queue_name="event-batches",
connection="AzureWebJobsStorage")
@app.queue_output(arg_name="failed", queue_name="events-failed",
connection="AzureWebJobsStorage")
def apply_batch(msg: func.QueueMessage, failed: func.Out[List[str]]):
batch, parked = msg.get_json(), []
for e in batch["events"]:
try:
temp = float(e["temp"]) # can never succeed
except (KeyError, TypeError, ValueError) as err:
parked.append(json.dumps({"id": e["id"], "error": str(err)}))
continue
readings.upsert_entity({"PartitionKey": batch["batch"],
"RowKey": e["id"], "temp": temp})
failed.set(parked) # one message each
logging.info("%s: wrote %d, parked %d", batch["batch"],
len(batch["events"]) - len(parked), len(parked))
""")
run('cd queue_app && python "$FHOST" start')
run('python send_batch.py b-2')
run('cd queue_app && python "$FHOST" wait "Executed \'Functions.apply_batch\'" 60 && python "$FHOST" log')
run('python rows.py b-2 events-failed')
run('cd queue_app && python "$FHOST" stop')
Part 5: Durable Functions
The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run with Azure Functions Core Tools 4.16.0 (the real Functions host, Python 3.13 worker) and Azurite 3.37.0 for storage. Features the local host cannot show truthfully are shown as code. Part of the Real Time Azure Functions Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of November 2026; check the official Azure Functions documentation (learn.microsoft.com/azure/azure-functions) for anything you quote in an interview.



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