In this post we are going to cover reliability, retries and idempotency in Azure Functions: 7 real Azure Functions interview questions for data engineers, asked the way they come up on a real project. The last one is a scenario: payment events must never be lost and never be applied twice.
Reliability is what happens when things go wrong: a function throws, a downstream API is down, or the same message arrives twice. Each trigger handles failure its own way, and Functions delivers at least once, never exactly once. Interviewers ask about it because duplicate rows and lost messages are the bugs that cost real money in a data pipeline.
Part 7 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 what happens when a function throws an exception. How do retries work for each trigger?
- Question 2: Someone asks how to configure retry policies, fixed delay versus exponential backoff. When do you use each?
- Question 3: Your manager asks if Functions guarantees exactly-once processing. What do you say?
- Question 4: A pipeline writes duplicate rows after retries. How do you make a function idempotent?
- Question 5: A downstream API is down for an hour. How do you stop your function from hammering it?
- Question 6: Someone asks how to handle a message that can never succeed. What do you do with it?
- Scenario 7: Payment events must never be lost and never be applied twice. How do you build the function?
- The full script
The short answer
Each trigger fails its own way: HTTP and timers don't retry by default, a queue tries five times and then uses a poison queue. Retry policies (fixed delay or exponential backoff) are for Timer, Event Hubs, Cosmos DB and Kafka. Delivery is at least once, so key every write on a business key, pause consumers during outages, and park messages that can never succeed.
Let's set up the project
We run the real Azure Functions host locally with Core Tools, with Azurite, Microsoft's open-source storage emulator, for queues, blobs and tables. The main app is a small Python function app, pay_app, plus a send.py client that puts messages on a queue. What only Azure can show, such as Service Bus and scale settings, is shown as code.
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"extensions": {
"queues": {"batchSize": 1, "newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:01"}
},
"logging": {
"logLevel": {"default": "Warning", "Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"}
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport os, sys
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())
try:
q.create_queue()
except Exception:
pass # already there
for body in sys.argv[2:]:
q.send_message(body)
print("sent to", sys.argv[1] + ":", ", ".join(sys.argv[2:]))Question 1: A teammate asks what happens when a function throws an exception. How do retries work for each trigger?
Each trigger has its own failure rules. Some retry, some do not, and one moves on without you.
Let's prove it with three functions that all raise: an HTTP trigger charge, a timer nightly, and a queue trigger apply on the payments queue. We start the host, post to /api/charge with post.py, run the timer on demand through the local admin API with fire.py, and send one message, p-1001:
import logging
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.route(route="charge", methods=["POST"])
def charge(req: func.HttpRequest) -> func.HttpResponse:
raise ConnectionError("card service down")
@app.timer_trigger(schedule="0 0 2 * * *", arg_name="t",
run_on_startup=False)
def nightly(t: func.TimerRequest) -> None:
raise ConnectionError("source not ready")
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
def apply(msg: func.QueueMessage) -> None:
logging.info("apply %s, attempt %s",
msg.get_body().decode(), msg.dequeue_count)
raise ConnectionError("ledger locked")import sys, requests
r = requests.post("http://localhost:7071" + sys.argv[1])
print("POST", sys.argv[1], "->", r.status_code, repr(r.text))import sys, requests
# run a timer now through the admin API (Azure: needs the master key)
URL = "http://localhost:7071/admin/functions/"
r = requests.post(URL + sys.argv[1], json={"input": ""})
print("run", sys.argv[1], "->", r.status_code)$ cd pay_app && fhost start
host started, functions:
charge: [POST] http://localhost:7071/api/charge
apply: queueTrigger
nightly: timerTrigger
$ python post.py /api/charge
POST /api/charge -> 500 ''
$ python fire.py nightly
run nightly -> 202
$ cd pay_app && fhost wait "Executed 'Functions.nightly'" 30
$ python send.py payments p-1001
sent to payments: p-1001
$ cd pay_app && fhost wait 'Moving message' 90 && fhost log && fhost stop
Executing 'Functions.charge' (Reason='This function was programmatically called via the host APIs.')
Executed 'Functions.charge' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.charge. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: card service down
Executing 'Functions.nightly' (Reason='This function was programmatically called via the host APIs.')
Executed 'Functions.nightly' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.nightly. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: source not ready
Executing 'Functions.apply' (Reason='New queue message detected on 'payments'.')
apply p-1001, attempt 1
Executed 'Functions.apply' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: ledger locked
Executing 'Functions.apply' (Reason='New queue message detected on 'payments'.')
apply p-1001, attempt 2
Executed 'Functions.apply' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: ledger locked
Executing 'Functions.apply' (Reason='New queue message detected on 'payments'.')
apply p-1001, attempt 3
Executed 'Functions.apply' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: ledger locked
Executing 'Functions.apply' (Reason='New queue message detected on 'payments'.')
apply p-1001, attempt 4
Executed 'Functions.apply' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: ledger locked
Executing 'Functions.apply' (Reason='New queue message detected on 'payments'.')
apply p-1001, attempt 5
Executed 'Functions.apply' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: ledger locked
Message has reached MaxDequeueCount of 5. Moving message to queue 'payments-poison'.
host stoppedHTTP does not retry: the caller gets 500 '', an empty body, and decides what to do. The timer does not retry either. It fails once with source not ready and waits for the next schedule. The queue trigger does retry. The message comes back, the attempt number goes from 1 to 5, and then the host logs MaxDequeueCount of 5 and moves it to payments-poison.
Here is every trigger side by side:
| Trigger | When the function throws | After that |
|---|---|---|
| HTTP | no retry: the caller gets a 500 | the caller decides |
| Timer | no retry by default | next scheduled run (or a retry policy) |
| Queue Storage | 5 attempts, including the first | moved to <queue>-poison |
| Blob | 5 tries | message in webjobs-blobtrigger-poison |
| Service Bus | abandoned, delivered again | dead-letter queue after max delivery count (10) |
| Event Hubs | checkpoint still moves on | event skipped; a retry policy only delays it |
Blob triggers also try five times. Service Bus dead-letters after the max delivery count, 10 by default. Event Hubs is the surprise: the checkpoint moves on even when the function throws, so the event is skipped.
The mistake I see is assuming everything retries. For every function, write down what happens on failure.
Question 2: Someone asks how to configure retry policies, fixed delay versus exponential backoff. When do you use each?
A retry policy is a decorator. Fixed delay waits the same interval before every retry. Exponential backoff starts at a minimum interval and grows up to a maximum.
max_retry_count sets the number of retries, and -1 means forever:
| Strategy | Settings | Use it for |
|---|---|---|
| fixed_delay | delay_interval, max_retry_count | a short, known blip: a lock that clears in seconds |
| exponential_backoff | minimum_interval, maximum_interval, max_retry_count | throttling and outages: back off |
| max_retry_count = -1 | retries forever | only with a circuit breaker: it never stops |
Microsoft supports retry policies only for Timer, Event Hubs, Cosmos DB and Kafka. Queues and blobs retry through the dequeue count and the poison queue, and Service Bus through the max delivery count.
Let's try it. nightly_pull is a timer with exponential backoff, and it reads its retry count from context.retry_context.retry_count. The source is busy on the first try and on retry 1. We also put a fixed delay policy on a queue function, apply_retry, to see what the host says. We start the host, look for the warning, then run the timer on demand:
import logging
import azure.functions as func
app = func.FunctionApp()
@app.timer_trigger(schedule="0 0 2 * * *", arg_name="t",
run_on_startup=False)
@app.retry(strategy="exponential_backoff", max_retry_count="4",
minimum_interval="00:00:01", maximum_interval="00:00:08")
def nightly_pull(t: func.TimerRequest,
context: func.Context) -> None:
n = context.retry_context.retry_count # 0 on the first try
if n < 2:
logging.info("pull sales: source busy, retry %s", n)
raise ConnectionError("source busy")
logging.info("pull sales: ok on retry %s", n)
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
@app.retry(strategy="fixed_delay", max_retry_count="2",
delay_interval="00:00:05") # not supported for queues
def apply_retry(msg: func.QueueMessage) -> None:
logging.info("apply %s", msg.get_body().decode())$ cd pay_app && fhost start
host started, functions:
apply_retry: queueTrigger
nightly_pull: timerTrigger
$ cd pay_app && grep -o "Soon retries.*apply_retry'" .fhost.log
Soon retries will not be supported for function 'Functions.apply_retry'
$ python fire.py nightly_pull
run nightly_pull -> 202
$ cd pay_app && fhost wait 'pull sales: ok' 60 && fhost log && fhost stop
Executing 'Functions.nightly_pull' (Reason='This function was programmatically called via the host
APIs.')
pull sales: source busy, retry 0
Executed 'Functions.nightly_pull' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.nightly_pull.
System.Private.CoreLib: Result: Failure
Exception: ConnectionError: source busy
Executing 'Functions.nightly_pull' (Reason='This function was programmatically called via the host
APIs.')
pull sales: source busy, retry 1
Executed 'Functions.nightly_pull' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.nightly_pull.
System.Private.CoreLib: Result: Failure
Exception: ConnectionError: source busy
Executing 'Functions.nightly_pull' (Reason='This function was programmatically called via the host
APIs.')
pull sales: ok on retry 2
Executed 'Functions.nightly_pull' (Succeeded)
host stoppedThe host warns: Soon retries will not be supported for function 'Functions.apply_retry'. The timer fails with source busy, retry 0 and retry 1, then logs ok on retry 2 and Succeeded.
Fixed delay fits a short, known blip, like a lock that clears in seconds. Exponential backoff fits throttling and outages, because every wait gives the other side more room to recover.
The retry count lives in instance memory, so it is best effort. If the instance fails, the count starts again, and a timer can retry fewer times than the max.
Question 3: Your manager asks if Functions guarantees exactly-once processing. What do you say?
No, and I say it plainly. Functions delivers at least once, so every function must be idempotent: a second delivery should change nothing.
The same message can arrive again for three reasons:
- A failure: the queue, blob or Service Bus message comes back
- A crash or timeout: before the message is deleted or the checkpoint saved
- A producer that sends twice: a resend looks like a brand-new message
Let's see what that means. apply_payment writes a ledger row with the table SDK, using a new GUID as the row key. Then we simulate the worker dying before the message is deleted, by raising on the first attempt. We send payment p-1001 with pay.py, then read the ledger with ledger.py:
import json, logging, os, uuid
import azure.functions as func
from azure.data.tables import TableServiceClient
app = func.FunctionApp()
logging.getLogger("azure").setLevel(logging.WARNING) # quiet SDK
ledger = TableServiceClient.from_connection_string( # one client
os.environ["LEDGER_STORAGE"]).create_table_if_not_exists("ledger")
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
def apply_payment(msg: func.QueueMessage) -> None:
p = json.loads(msg.get_body())
row = {"PartitionKey": p["account"], "payment_id": p["id"],
"amount": p["amount"]}
key = str(uuid.uuid4()) # a new key every run
ledger.create_entity({**row, "RowKey": key})
logging.info("applied %s, attempt %s", p["id"], msg.dequeue_count)
if msg.dequeue_count == 1: # the worker dies right here
raise TimeoutError("lost before the message was deleted"){
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"LEDGER_STORAGE": "UseDevelopmentStorage=true"
}
}import json, os, sys
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "payments",
message_encode_policy=TextBase64EncodePolicy())
try:
q.create_queue()
except Exception:
pass
for pid in sys.argv[1:]: # account a-7, 25.00 each
q.send_message(json.dumps({"id": pid, "account": "a-7",
"amount": 25.0}))
print("sent:", ", ".join(sys.argv[1:]))import os, sys
from collections import Counter
from azure.data.tables import TableServiceClient
svc = TableServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
if sys.argv[1:] == ["--reset"]:
svc.delete_table("ledger")
sys.exit(print("ledger table cleared"))
rows = list(svc.get_table_client("ledger").query_entities(
"PartitionKey eq 'a-7'"))
for pid, n in sorted(Counter(r["payment_id"] for r in rows).items()):
print(f"{pid}: {n} row(s)")
print("balance a-7:", sum(r["amount"] for r in rows))$ cd pay_app && fhost start
host started, functions:
apply_payment: queueTrigger
$ python pay.py p-1001
sent: p-1001
$ cd pay_app && fhost wait 'Succeeded' 60 && fhost log && fhost stop
Executing 'Functions.apply_payment' (Reason='New queue message detected on 'payments'.')
applied p-1001, attempt 1
Executed 'Functions.apply_payment' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply_payment.
System.Private.CoreLib: Result: Failure
Exception: TimeoutError: lost before the message was deleted
Executing 'Functions.apply_payment' (Reason='New queue message detected on 'payments'.')
applied p-1001, attempt 2
Executed 'Functions.apply_payment' (Succeeded)
host stopped
$ python ledger.py
p-1001: 2 row(s)
balance a-7: 50.0Attempt 1 writes the row and fails with lost before the message was deleted. The message comes back, attempt 2 writes the row again, and succeeds. The ledger shows p-1001: 2 row(s) and balance a-7: 50.0, for one payment of 25.
That is the real risk. Whatever your code already did through an SDK, a table write, an API call or an email, has happened, and the retry does it again.
At-least-once delivery, plus idempotent processing, plus a test that delivers every message twice.
Question 4: A pipeline writes duplicate rows after retries. How do you make a function idempotent?
Idempotent means running it twice leaves the same result as running it once. The trick is a business key that comes from the message, never a key you generate inside the function.
Let's fix the ledger. Now the row key is the payment ID, so the insert fails with ResourceExistsError when the row already exists, and we treat that as a no-op. The same crash still happens on attempt 1. We clear the ledger, send p-1001, then send it again as if the producer resent it:
import json, logging, os
import azure.functions as func
from azure.core.exceptions import ResourceExistsError
from azure.data.tables import TableServiceClient
app = func.FunctionApp()
logging.getLogger("azure").setLevel(logging.WARNING) # quiet SDK
ledger = TableServiceClient.from_connection_string( # one client
os.environ["LEDGER_STORAGE"]).create_table_if_not_exists("ledger")
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
def apply_payment(msg: func.QueueMessage) -> None:
p = json.loads(msg.get_body())
row = {"PartitionKey": p["account"], "payment_id": p["id"],
"amount": p["amount"]}
key = p["id"] # the business key
try:
ledger.create_entity({**row, "RowKey": key})
except ResourceExistsError: # seen before: a no-op
logging.info("skip %s: already applied", p["id"])
return
logging.info("applied %s, attempt %s", p["id"], msg.dequeue_count)
if msg.dequeue_count == 1: # the worker dies right here
raise TimeoutError("lost before the message was deleted")$ python ledger.py --reset
ledger table cleared
$ cd pay_app && fhost start
host started, functions:
apply_payment: queueTrigger
$ python pay.py p-1001
sent: p-1001
$ cd pay_app && fhost wait 'Succeeded' 60 && fhost log
Executing 'Functions.apply_payment' (Reason='New queue message detected on 'payments'.')
applied p-1001, attempt 1
Executed 'Functions.apply_payment' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.apply_payment.
System.Private.CoreLib: Result: Failure
Exception: TimeoutError: lost before the message was deleted
Executing 'Functions.apply_payment' (Reason='New queue message detected on 'payments'.')
skip p-1001: already applied
Executed 'Functions.apply_payment' (Succeeded)
$ python pay.py p-1001
sent: p-1001
$ cd pay_app && fhost wait 'Succeeded' 60 && fhost log && fhost stop
Executing 'Functions.apply_payment' (Reason='New queue message detected on 'payments'.')
skip p-1001: already applied
Executed 'Functions.apply_payment' (Succeeded)
host stopped
$ python ledger.py
p-1001: 1 row(s)
balance a-7: 25.0Attempt 2 logs skip p-1001: already applied. The resent message logs the same skip. The ledger shows p-1001: 1 row(s) and balance a-7: 25.0, no matter how often the message arrives.
In a warehouse or a lake, the same idea takes different shapes:
| Pattern | Where | How it stops the duplicate |
|---|---|---|
| MERGE / upsert on the business key | SQL, Delta | a second run updates the same row |
| Unique constraint on the event ID | SQL | the second insert fails: skip it |
| Processed-messages table | same transaction as the write | seen before: a no-op |
| Deterministic output names | files in the lake | a rerun overwrites its own file |
Check, then insert, as two separate steps. Two instances can both see no row and both insert. Let the database enforce the key.
Question 5: A downstream API is down for an hour. How do you stop your function from hammering it?
First, stop the retry storm: space the retries and cap the scale-out. For a long outage, pause the consumer and let the queue buffer.
Let's look at the knobs:
visibilityTimeout:00:00:00by default, so a failed message is back at once- Raise it to space the queue retries
- Maximum instance count: fewer instances, fewer calls
To pause the consumer, the app setting AzureWebJobs.call_partner.Disabled set to true stops the trigger. We start partner_app, send three orders, and check the queue depth with depth.py:
import logging
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.queue_trigger(arg_name="msg", queue_name="partner-calls",
connection="AzureWebJobsStorage")
def call_partner(msg: func.QueueMessage) -> None:
order = msg.get_body().decode()
logging.info("POST %s to the partner API", order)
@app.route(route="health")
def health(req: func.HttpRequest) -> func.HttpResponse:
return func.HttpResponse("ok"){
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"extensions": {
"queues": {"batchSize": 1, "newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:01"}
},
"logging": {
"logLevel": {"default": "Warning", "Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"}
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobs.call_partner.Disabled": "true"
}
}azure-functionsimport os, sys
from azure.storage.queue import QueueClient
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], sys.argv[1])
n = q.get_queue_properties().approximate_message_count
print(f"{sys.argv[1]}: {n} waiting")$ cd partner_app && fhost start
host started, functions:
health: http://localhost:7071/api/health
Function call_partner is disabled.
$ python send.py partner-calls o-1 o-2 o-3
sent to partner-calls: o-1, o-2, o-3
$ sleep 5 && python depth.py partner-calls
partner-calls: 3 waiting
$ cd partner_app && fhost stop
host stoppedThe host lists Function call_partner is disabled., and the queue shows partner-calls: 3 waiting. When the partner is back, we set the setting to false and start the host again:
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobs.call_partner.Disabled": "false"
}
}$ cd partner_app && fhost start
host started, functions:
health: http://localhost:7071/api/health
call_partner: queueTrigger
$ cd partner_app && fhost wait 'Executed' 30 3 && fhost log && fhost stop
Executing 'Functions.call_partner' (Reason='New queue message detected on 'partner-calls'.')
POST o-1 to the partner API
Executed 'Functions.call_partner' (Succeeded)
Executing 'Functions.call_partner' (Reason='New queue message detected on 'partner-calls'.')
POST o-2 to the partner API
Executed 'Functions.call_partner' (Succeeded)
Executing 'Functions.call_partner' (Reason='New queue message detected on 'partner-calls'.')
POST o-3 to the partner API
Executed 'Functions.call_partner' (Succeeded)
host stopped
$ python depth.py partner-calls
partner-calls: 0 waitingAll three orders are posted, and the queue is back to 0 waiting. Nothing lost, nobody hammered. In Azure, changing an app setting restarts the app. As code:
# pause the consumer: the trigger stops, messages wait in the queue
az functionapp config appsettings set -g rg-orders -n fn-orders \
--settings AzureWebJobs.call_partner.Disabled=true
# cap scale-out, so retries cannot multiply (Flex Consumption)
az functionapp scale config set -g rg-orders -n fn-orders \
--maximum-instance-count 10In a real project this becomes a circuit breaker: count failures, and past a threshold, disable the function and send an alert. Microsoft's reliable event processing guidance describes exactly that for Event Hubs.
On Linux, a function name with a hyphen cannot be disabled this way, so use underscores.
Question 6: Someone asks how to handle a message that can never succeed. What do you do with it?
First, separate permanent errors from transient ones. Park a permanent error with its reason and return normally; let a transient error raise, so the trigger retries.
A bad amount fails on every try, so five retries are wasted work. A partner returning 503 might work next time. Let's run refund_app with three refunds: r-1 is fine, r-2 has the amount abc, and r-3 hits a partner 503 every time. A second function, poison_alert, listens on the poison queue. We send the refunds with refunds.py and list the parked files with parked.py:
import json, logging
import azure.functions as func
app = func.FunctionApp()
C = "AzureWebJobsStorage"
PARK = "parked/{id}.json" # {id} from the message
@app.queue_trigger(arg_name="msg", queue_name="refunds", connection=C)
@app.blob_output(arg_name="parked", path=PARK, connection=C)
def refund(msg: func.QueueMessage, parked: func.Out[str]) -> None:
r = json.loads(msg.get_body())
if not r["amount"].replace(".", "", 1).isdigit(): # permanent
parked.set(json.dumps({**r, "reason": "bad amount"}))
logging.warning("parked %s: bad amount", r["id"])
return # success: no retries
if r["id"] == "r-3": # transient: raise, retry
logging.info("refund r-3, attempt %s", msg.dequeue_count)
raise ConnectionError("partner API 503")
logging.info("refunded %s: %s", r["id"], r["amount"])
@app.queue_trigger(arg_name="msg", queue_name="refunds-poison",
connection=C)
@app.blob_output(arg_name="parked", path=PARK, connection=C)
def poison_alert(msg: func.QueueMessage,
parked: func.Out[str]) -> None:
r = json.loads(msg.get_body())
parked.set(json.dumps({**r, "reason": "failed 5 times"}))
logging.error("ALERT: %s moved to refunds-poison", r["id"]){
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"extensions": {
"queues": {"batchSize": 1, "newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:01"}
},
"logging": {
"logLevel": {"default": "Warning", "Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"}
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport json, os
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "refunds",
message_encode_policy=TextBase64EncodePolicy())
q.create_queue()
for rid, amt in [("r-1", "19.90"), ("r-2", "abc"), ("r-3", "5.00")]:
q.send_message(json.dumps({"id": rid, "amount": amt}))
print("sent r-1 (19.90), r-2 (abc), r-3 (5.00)")import json, os
from azure.storage.blob import ContainerClient
c = ContainerClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "parked")
for name in sorted(c.list_blob_names()):
r = json.loads(c.download_blob(name).readall())
print(f"parked/{name}: {r['reason']} (amount {r['amount']})")$ cd refund_app && fhost start
host started, functions:
poison_alert: queueTrigger
refund: queueTrigger
$ python refunds.py
sent r-1 (19.90), r-2 (abc), r-3 (5.00)
$ cd refund_app && fhost wait 'Executed.*poison_alert' 90
$ cd refund_app && fhost log && fhost stop
Executing 'Functions.refund' (Reason='New queue message detected on 'refunds'.')
refunded r-1: 19.90
Executed 'Functions.refund' (Succeeded)
Executing 'Functions.refund' (Reason='New queue message detected on 'refunds'.')
parked r-2: bad amount
Executed 'Functions.refund' (Succeeded)
Executing 'Functions.refund' (Reason='New queue message detected on 'refunds'.')
refund r-3, attempt 1
Executed 'Functions.refund' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.refund. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: partner API 503
Executing 'Functions.refund' (Reason='New queue message detected on 'refunds'.')
refund r-3, attempt 2
Executed 'Functions.refund' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.refund. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: partner API 503
Executing 'Functions.refund' (Reason='New queue message detected on 'refunds'.')
refund r-3, attempt 3
Executed 'Functions.refund' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.refund. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: partner API 503
Executing 'Functions.refund' (Reason='New queue message detected on 'refunds'.')
refund r-3, attempt 4
Executed 'Functions.refund' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.refund. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: partner API 503
Executing 'Functions.refund' (Reason='New queue message detected on 'refunds'.')
refund r-3, attempt 5
Executed 'Functions.refund' (Failed)
System.Private.CoreLib: Exception while executing function: Functions.refund. System.Private.CoreLib:
Result: Failure
Exception: ConnectionError: partner API 503
Message has reached MaxDequeueCount of 5. Moving message to queue 'refunds-poison'.
Executing 'Functions.poison_alert' (Reason='New queue message detected on 'refunds-poison'.')
ALERT: r-3 moved to refunds-poison
Executed 'Functions.poison_alert' (Succeeded)
host stopped
$ python parked.py
parked/r-2.json: bad amount (amount abc)
parked/r-3.json: failed 5 times (amount 5.00)r-1 is refunded. r-2 is parked at once with bad amount and the function succeeds, so there are no retries. r-3 fails five times, moves to refunds-poison, and poison_alert parks it and logs ALERT: r-3 moved to refunds-poison. The parked container now holds r-2.json with bad amount and r-3.json with failed 5 times, ready to fix and replay.
On Service Bus the same idea is the dead-letter queue, after the max delivery count, and it never cleans itself up.
A poison queue nobody checks. Its messages expire after seven days by default, so alert on its length and make someone own every replay.
Scenario 7: Payment events must never be lost and never be applied twice. How do you build the function?
Never lost and never twice are two separate promises, and I build each one on purpose.
Let's walk the flow: the payment API publishes events to a Service Bus queue with peek-lock, apply_payment processes them idempotently into a SQL ledger with a unique payment_id, failures go to the dead-letter queue after 10 deliveries, and an alert tells someone to replay.
- Never lost: a durable queue, complete only on success
- Dead-letter and alert: after the max delivery count
- Never twice: the payment ID is the idempotency key
- One transaction: marker and ledger, with a unique constraint
- Sessions: order per account; not on Basic
- No swallowed errors: let it raise, the message comes back
For never lost, payments go on a durable queue, Service Bus here, not straight into an HTTP call that can time out. The runtime completes the message when the function succeeds and abandons it when it throws. For never twice, the processed marker and the ledger entry go into one database transaction, the same pattern we just ran on the table:
@app.service_bus_queue_trigger(arg_name="msg", queue_name="payments",
connection="PaymentsBus", is_sessions_enabled=True)
def apply_payment(msg: func.ServiceBusMessage) -> None:
p = json.loads(msg.get_body())
with sql.transaction() as tx: # one transaction
if not tx.mark_processed(p["payment_id"]): # unique key
logging.info("skip %s: already applied", p["payment_id"])
return
tx.post_ledger(p["account"], p["amount"])
# returns: the runtime completes the message
# raises: abandoned, redelivered, then dead-letteredIf order per account matters, use sessions with the account as the session ID; the Basic tier has no sessions:
az servicebus queue create -g rg-pay --namespace-name sb-pay \
--name payments --max-delivery-count 10 \
--enable-session true # order per account; not on Basic
# the trigger matches it: is_sessions_enabled=TrueDeliver every event twice, kill the worker mid-run, and check that the balances still match.
Key points to remember
- Each trigger fails its own way: HTTP and timers don't retry by default, queues try 5 times, then -poison
- Retry policies (fixed delay, exponential backoff) only for Timer, Event Hubs, Cosmos DB, Kafka
- Delivery is at least once: never promise exactly once
- Make writes idempotent on a business key: unique constraint, MERGE, processed-messages table
- Outage: pause the consumer, cap scale-out; park permanent errors, alert on poison and dead-letter queues
The full script
This Python script 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 #7 - Reliability, retries and idempotency
# 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_07_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('pay_app/host.json', """\
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"extensions": {
"queues": {"batchSize": 1, "newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:01"}
},
"logging": {
"logLevel": {"default": "Warning", "Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"}
}
}
""")
write('pay_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('pay_app/requirements.txt', """\
azure-functions
""")
write('send.py', """\
import os, sys
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())
try:
q.create_queue()
except Exception:
pass # already there
for body in sys.argv[2:]:
q.send_message(body)
print("sent to", sys.argv[1] + ":", ", ".join(sys.argv[2:]))
""")
# Step 1: An HTTP, a timer and a queue function all raise: what does each trigger do?
write('pay_app/function_app.py', """\
import logging
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.route(route="charge", methods=["POST"])
def charge(req: func.HttpRequest) -> func.HttpResponse:
raise ConnectionError("card service down")
@app.timer_trigger(schedule="0 0 2 * * *", arg_name="t",
run_on_startup=False)
def nightly(t: func.TimerRequest) -> None:
raise ConnectionError("source not ready")
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
def apply(msg: func.QueueMessage) -> None:
logging.info("apply %s, attempt %s",
msg.get_body().decode(), msg.dequeue_count)
raise ConnectionError("ledger locked")
""")
write('post.py', """\
import sys, requests
r = requests.post("http://localhost:7071" + sys.argv[1])
print("POST", sys.argv[1], "->", r.status_code, repr(r.text))
""")
write('fire.py', """\
import sys, requests
# run a timer now through the admin API (Azure: needs the master key)
URL = "http://localhost:7071/admin/functions/"
r = requests.post(URL + sys.argv[1], json={"input": ""})
print("run", sys.argv[1], "->", r.status_code)
""")
run('cd pay_app && python "$FHOST" start')
run('python post.py /api/charge')
run('python fire.py nightly')
run('cd pay_app && python "$FHOST" wait "Executed \'Functions.nightly\'" 30')
run('python send.py payments p-1001')
run('cd pay_app && python "$FHOST" wait \'Moving message\' 90 && python "$FHOST" log && python "$FHOST" stop')
# Step 2: A timer with an exponential backoff retry policy, and a queue function the host warns about
write('pay_app/function_app.py', """\
import logging
import azure.functions as func
app = func.FunctionApp()
@app.timer_trigger(schedule="0 0 2 * * *", arg_name="t",
run_on_startup=False)
@app.retry(strategy="exponential_backoff", max_retry_count="4",
minimum_interval="00:00:01", maximum_interval="00:00:08")
def nightly_pull(t: func.TimerRequest,
context: func.Context) -> None:
n = context.retry_context.retry_count # 0 on the first try
if n < 2:
logging.info("pull sales: source busy, retry %s", n)
raise ConnectionError("source busy")
logging.info("pull sales: ok on retry %s", n)
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
@app.retry(strategy="fixed_delay", max_retry_count="2",
delay_interval="00:00:05") # not supported for queues
def apply_retry(msg: func.QueueMessage) -> None:
logging.info("apply %s", msg.get_body().decode())
""")
run('cd pay_app && python "$FHOST" start')
run('cd pay_app && grep -o "Soon retries.*apply_retry\'" .fhost.log')
run('python fire.py nightly_pull')
run('cd pay_app && python "$FHOST" wait \'pull sales: ok\' 60 && python "$FHOST" log && python "$FHOST" stop')
# Step 3: At least once: the worker dies after the ledger write, the retry writes it again
write('pay_app/function_app.py', """\
import json, logging, os, uuid
import azure.functions as func
from azure.data.tables import TableServiceClient
app = func.FunctionApp()
logging.getLogger("azure").setLevel(logging.WARNING) # quiet SDK
ledger = TableServiceClient.from_connection_string( # one client
os.environ["LEDGER_STORAGE"]).create_table_if_not_exists("ledger")
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
def apply_payment(msg: func.QueueMessage) -> None:
p = json.loads(msg.get_body())
row = {"PartitionKey": p["account"], "payment_id": p["id"],
"amount": p["amount"]}
key = str(uuid.uuid4()) # a new key every run
ledger.create_entity({**row, "RowKey": key})
logging.info("applied %s, attempt %s", p["id"], msg.dequeue_count)
if msg.dequeue_count == 1: # the worker dies right here
raise TimeoutError("lost before the message was deleted")
""")
write('pay_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"LEDGER_STORAGE": "UseDevelopmentStorage=true"
}
}
""")
write('pay.py', """\
import json, os, sys
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "payments",
message_encode_policy=TextBase64EncodePolicy())
try:
q.create_queue()
except Exception:
pass
for pid in sys.argv[1:]: # account a-7, 25.00 each
q.send_message(json.dumps({"id": pid, "account": "a-7",
"amount": 25.0}))
print("sent:", ", ".join(sys.argv[1:]))
""")
write('ledger.py', """\
import os, sys
from collections import Counter
from azure.data.tables import TableServiceClient
svc = TableServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
if sys.argv[1:] == ["--reset"]:
svc.delete_table("ledger")
sys.exit(print("ledger table cleared"))
rows = list(svc.get_table_client("ledger").query_entities(
"PartitionKey eq 'a-7'"))
for pid, n in sorted(Counter(r["payment_id"] for r in rows).items()):
print(f"{pid}: {n} row(s)")
print("balance a-7:", sum(r["amount"] for r in rows))
""")
run('cd pay_app && python "$FHOST" start')
run('python pay.py p-1001')
run('cd pay_app && python "$FHOST" wait \'Succeeded\' 60 && python "$FHOST" log && python "$FHOST" stop')
run('python ledger.py')
# Step 4: Idempotent: the payment id is the row key, so a retry and a resend are no-ops
write('pay_app/function_app.py', """\
import json, logging, os
import azure.functions as func
from azure.core.exceptions import ResourceExistsError
from azure.data.tables import TableServiceClient
app = func.FunctionApp()
logging.getLogger("azure").setLevel(logging.WARNING) # quiet SDK
ledger = TableServiceClient.from_connection_string( # one client
os.environ["LEDGER_STORAGE"]).create_table_if_not_exists("ledger")
@app.queue_trigger(arg_name="msg", queue_name="payments",
connection="AzureWebJobsStorage")
def apply_payment(msg: func.QueueMessage) -> None:
p = json.loads(msg.get_body())
row = {"PartitionKey": p["account"], "payment_id": p["id"],
"amount": p["amount"]}
key = p["id"] # the business key
try:
ledger.create_entity({**row, "RowKey": key})
except ResourceExistsError: # seen before: a no-op
logging.info("skip %s: already applied", p["id"])
return
logging.info("applied %s, attempt %s", p["id"], msg.dequeue_count)
if msg.dequeue_count == 1: # the worker dies right here
raise TimeoutError("lost before the message was deleted")
""")
run('python ledger.py --reset')
run('cd pay_app && python "$FHOST" start')
run('python pay.py p-1001')
run('cd pay_app && python "$FHOST" wait \'Succeeded\' 60 && python "$FHOST" log')
run('python pay.py p-1001')
run('cd pay_app && python "$FHOST" wait \'Succeeded\' 60 && python "$FHOST" log && python "$FHOST" stop')
run('python ledger.py')
# Step 5: The partner API is down: disable the consumer and let the queue buffer
write('partner_app/function_app.py', """\
import logging
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.queue_trigger(arg_name="msg", queue_name="partner-calls",
connection="AzureWebJobsStorage")
def call_partner(msg: func.QueueMessage) -> None:
order = msg.get_body().decode()
logging.info("POST %s to the partner API", order)
@app.route(route="health")
def health(req: func.HttpRequest) -> func.HttpResponse:
return func.HttpResponse("ok")
""")
write('partner_app/host.json', """\
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"extensions": {
"queues": {"batchSize": 1, "newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:01"}
},
"logging": {
"logLevel": {"default": "Warning", "Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"}
}
}
""")
write('partner_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobs.call_partner.Disabled": "true"
}
}
""")
write('partner_app/requirements.txt', """\
azure-functions
""")
write('depth.py', """\
import os, sys
from azure.storage.queue import QueueClient
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], sys.argv[1])
n = q.get_queue_properties().approximate_message_count
print(f"{sys.argv[1]}: {n} waiting")
""")
run('cd partner_app && python "$FHOST" start')
run('python send.py partner-calls o-1 o-2 o-3')
run('sleep 5 && python depth.py partner-calls')
run('cd partner_app && python "$FHOST" stop')
# Step 6: The partner is back: enable the function again, the backlog drains
write('partner_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobs.call_partner.Disabled": "false"
}
}
""")
run('cd partner_app && python "$FHOST" start')
run('cd partner_app && python "$FHOST" wait \'Executed\' 30 3 && python "$FHOST" log && python "$FHOST" stop')
run('python depth.py partner-calls')
# Step 7: Never succeeds: park permanent errors at once, poison-queue the rest and alert
write('refund_app/function_app.py', """\
import json, logging
import azure.functions as func
app = func.FunctionApp()
C = "AzureWebJobsStorage"
PARK = "parked/{id}.json" # {id} from the message
@app.queue_trigger(arg_name="msg", queue_name="refunds", connection=C)
@app.blob_output(arg_name="parked", path=PARK, connection=C)
def refund(msg: func.QueueMessage, parked: func.Out[str]) -> None:
r = json.loads(msg.get_body())
if not r["amount"].replace(".", "", 1).isdigit(): # permanent
parked.set(json.dumps({**r, "reason": "bad amount"}))
logging.warning("parked %s: bad amount", r["id"])
return # success: no retries
if r["id"] == "r-3": # transient: raise, retry
logging.info("refund r-3, attempt %s", msg.dequeue_count)
raise ConnectionError("partner API 503")
logging.info("refunded %s: %s", r["id"], r["amount"])
@app.queue_trigger(arg_name="msg", queue_name="refunds-poison",
connection=C)
@app.blob_output(arg_name="parked", path=PARK, connection=C)
def poison_alert(msg: func.QueueMessage,
parked: func.Out[str]) -> None:
r = json.loads(msg.get_body())
parked.set(json.dumps({**r, "reason": "failed 5 times"}))
logging.error("ALERT: %s moved to refunds-poison", r["id"])
""")
write('refund_app/host.json', """\
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
},
"extensions": {
"queues": {"batchSize": 1, "newBatchThreshold": 0,
"maxPollingInterval": "00:00:01",
"visibilityTimeout": "00:00:01"}
},
"logging": {
"logLevel": {"default": "Warning", "Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"}
}
}
""")
write('refund_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('refund_app/requirements.txt', """\
azure-functions
""")
write('refunds.py', """\
import json, os
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
q = QueueClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "refunds",
message_encode_policy=TextBase64EncodePolicy())
q.create_queue()
for rid, amt in [("r-1", "19.90"), ("r-2", "abc"), ("r-3", "5.00")]:
q.send_message(json.dumps({"id": rid, "amount": amt}))
print("sent r-1 (19.90), r-2 (abc), r-3 (5.00)")
""")
write('parked.py', """\
import json, os
from azure.storage.blob import ContainerClient
c = ContainerClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "parked")
for name in sorted(c.list_blob_names()):
r = json.loads(c.download_blob(name).readall())
print(f"parked/{name}: {r['reason']} (amount {r['amount']})")
""")
run('cd refund_app && python "$FHOST" start')
run('python refunds.py')
run('cd refund_app && python "$FHOST" wait \'Executed.*poison_alert\' 90')
run('cd refund_app && python "$FHOST" log && python "$FHOST" stop')
run('python parked.py')
Part 8: Security and Configuration
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.