Azure Functions Interview Questions and Answers Part 9 - Monitoring, Testing and Deployment

Azure Functions Interview Q&A · Part 9 of 10

In this post we are going to cover monitoring, testing and deployment 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: a function silently stopped processing files for two days and nobody noticed.

Monitoring is how you know the functions are healthy: what ran, what failed, and what is piling up. Testing and deployment are how a change gets from your laptop to production without breaking it, and how you get back when it does. Interviewers ask about it because a pipeline that fails quietly is worse than one that fails loudly, and every team has a story about it.

Part 9 of the Real Time Azure Functions Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

Watch executions, failures, exceptions, dependencies and backlog in Application Insights, and don't sample away requests. Log with the logging module and business keys, run locally with Core Tools and Azurite, unit test thin functions directly, deploy one artifact through a pipeline, roll back with a slot swap or a redeploy, and alert when runs stop.

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 storage. Each question that runs code has its own small Python function app, and client scripts call it, drop messages or upload files. What only Azure can show, such as Application Insights, slots and deployments, is shown as code.

Question 1: Your manager asks how you know the functions are healthy. What do you monitor in Application Insights?

I connect every function app to Application Insights with APPLICATIONINSIGHTS_CONNECTION_STRING; the instrumentation key setting is legacy. Then I track four signals: executions and failures, exceptions, dependencies, and the backlog in front of each function.

SignalWhereWatch for
Executionsrequests (Host.Results)runs per function, failure rate, duration
Exceptionsexceptionsnew error types after a deployment
Dependenciesdependenciesbinding calls: storage, Service Bus, Event Hubs
BacklogAzure Monitor metrics, queue length checkswork piling up, messages that never succeed

Executions land in the requests table, one row per run, with success or failure. Dependencies cover the host's binding calls to storage, Service Bus and Event Hubs; calls your own Python code makes need OpenTelemetry.

The pitfall is sampling. It is on by default, at about 20 items per second per host, so counts can lie. In host.json, exclude Request from sampling and every execution is kept. Keep the Function and Host.Results categories at Information, or the portal's monitor views go empty:

host.json (Azure: Application Insights)
{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Host.Results": "Information"
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  }
}

For a live view across instances I use Live Metrics; log streaming shows only one instance. Then the queries become alerts:

failures.kql (Application Insights, not run)
// runs and failures per function, last hour
requests
| where timestamp > ago(1h)
| summarize runs = count(),
            failed = countif(success == false)
            by operation_Name
| extend fail_pct = round(100.0 * failed / runs, 1)
| order by failed desc
  • Failure rate: per function, per hour
  • Poison queue length: above zero means lost work
  • No runs at all: the silent failure in the scenario below
Pitfall

Sampling on with default settings means your run counts are estimates. Exclude Request before you trust any number.

Question 2: Someone asks how to log properly from a Python function. What do you do?

Use the standard logging module, not print. It goes to Application Insights tied to the invocation, and the level becomes the severity you filter and alert on.

Write one line per event with the business keys, the batch, the status and the counts, as key=value pairs. Let's try it with an HTTP function, load_batch. We call it three times with calls.sh, for batches b-17, b-18 and b-99:

orders_app/function_app.py
import logging
import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
BATCHES = {"b-17": [25.5, None, 7.25, 12.0], "b-18": [None, None]}


@app.route(route="load_batch", methods=["POST"])
def load_batch(req: func.HttpRequest) -> func.HttpResponse:
    batch = req.params.get("batch", "")
    logging.debug("params %s", dict(req.params))   # not shown
    if batch not in BATCHES:
        logging.error("batch=%s status=not_found", batch)
        return func.HttpResponse("unknown batch", status_code=404)
    rows = [r for r in BATCHES[batch] if r is not None]
    rejected = len(BATCHES[batch]) - len(rows)
    if rejected:
        logging.warning("batch=%s rejected=%d reason=amount_missing",
                        batch, rejected)
    try:
        avg = sum(rows) / len(rows)
    except ZeroDivisionError:
        logging.exception("batch=%s status=failed", batch)
        return func.HttpResponse("load failed", status_code=500)
    logging.info("batch=%s status=loaded rows=%d avg_amount=%.2f",
                 batch, len(rows), avg)
    return func.HttpResponse(f"loaded {len(rows)} rows")
orders_app/host.json
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "extensions": {
    "queues": {"maxPollingInterval": "00:00:01"}
  },
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Azure.Core": "Error",
      "Host.Function.Console": "Information"
    }
  }
}
orders_app/local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}
orders_app/requirements.txt
azure-functions
calls.sh
for b in b-17 b-18 b-99; do
  curl -s -w " %{http_code}\n" -X POST \
    "http://localhost:7071/api/load_batch?batch=$b"
done
Terminal
$ cd orders_app && fhost start
host started, functions:
  load_batch: [POST] http://localhost:7071/api/load_batch
$ bash calls.sh
loaded 3 rows 200
load failed 500
unknown batch 404
$ cd orders_app && fhost wait "Executed 'Functions.load_batch'" 60 3 && fhost log
Executing 'Functions.load_batch' (Reason='This function was programmatically called via the host APIs.')
batch=b-17 rejected=1 reason=amount_missing
batch=b-17 status=loaded rows=3 avg_amount=14.92
Executed 'Functions.load_batch' (Succeeded)
Executing 'Functions.load_batch' (Reason='This function was programmatically called via the host APIs.')
batch=b-18 rejected=2 reason=amount_missing
batch=b-18 status=failed
Traceback (most recent call last):
  File "orders_app/function_app.py", line 21, in load_batch
    avg = sum(rows) / len(rows)
ZeroDivisionError: division by zero
Executed 'Functions.load_batch' (Succeeded)
Executing 'Functions.load_batch' (Reason='This function was programmatically called via the host APIs.')
batch=b-99 status=not_found
Executed 'Functions.load_batch' (Succeeded)
$ cd orders_app && fhost stop
host stopped

Let's read the output. b-17 logs a warning, rejected=1 reason=amount_missing, then status=loaded rows=3 avg_amount=14.92. b-18 has no valid rows, so the average fails with ZeroDivisionError, and logging.exception writes the traceback. b-99 logs an error: status=not_found.

There are two catches. The debug line never shows: host.json keeps the Function category at Information, and debug also needs the Python debug logging setting. And b-18 still says Succeeded, because we handled the error.

When a run must count as failed, or a queue message must be retried, log it and then raise again.

Threads

From a background thread, set thread_local_storage.invocation_id from the context, or those log lines lose their correlation.

Question 3: A teammate asks how to run and debug functions locally. What do you set up?

Core Tools version 4, the func command, plus Azurite, Microsoft's open-source storage emulator. local.settings.json sets the Python worker and points AzureWebJobsStorage at Azurite.

UseDevelopmentStorage=true means Azurite, on blob port 10000, queue 10001 and table 10002. Every trigger other than HTTP needs that storage.

func start runs the Functions runtime on your machine; fhost is our small wrapper that runs it in the background. Our shop_app has three functions: an HTTP route, a timer and a queue trigger. Let's check the version, start the host and fire each trigger with try_it.sh:

shop_app/function_app.py
import json
import logging
import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)


def clean_order(order: dict) -> dict:
    if order.get("amount") is None:
        raise ValueError("amount missing")
    amount = round(float(order["amount"]), 2)
    return {"id": order["id"], "amount": amount}


@app.route(route="orders", methods=["POST"])
def save_order(req: func.HttpRequest) -> func.HttpResponse:
    try:
        order = clean_order(req.get_json())
    except ValueError as e:
        return func.HttpResponse(str(e), status_code=400)
    return func.HttpResponse(json.dumps(order), status_code=201)


@app.queue_trigger(arg_name="msg", queue_name="orders",
                   connection="AzureWebJobsStorage")
def on_order(msg: func.QueueMessage) -> None:
    order = clean_order(msg.get_json())
    logging.info("order %s: amount %s", order["id"], order["amount"])


@app.timer_trigger(schedule="0 0 2 * * *", arg_name="timer",
                   run_on_startup=False)
def nightly_totals(timer: func.TimerRequest) -> None:
    logging.info("nightly_totals ran, past_due=%s", timer.past_due)
shop_app/host.json
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "extensions": {
    "queues": {"maxPollingInterval": "00:00:01"}
  },
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Azure.Core": "Error",
      "Host.Function.Console": "Information"
    }
  }
}
shop_app/local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}
shop_app/requirements.txt
azure-functions
send_order.py
import json, os, sys
from azure.storage.queue import QueueClient, TextBase64EncodePolicy

q = QueueClient.from_connection_string(
    os.environ["AZURE_STORAGE_CONNECTION_STRING"], "orders",
    message_encode_policy=TextBase64EncodePolicy())   # base64
try:
    q.create_queue()
except Exception:
    pass                                 # already there
q.send_message(json.dumps({"id": sys.argv[1], "amount": sys.argv[2]}))
print("queued", sys.argv[1])
try_it.sh
# HTTP trigger: post an order
curl -s -w " %{http_code}\n" -X POST \
  -d '{"id": "o-1001", "amount": "25.499"}' \
  http://localhost:7071/api/orders
# timer trigger: run it now through the admin endpoint
curl -s -w "%{http_code}\n" -X POST \
  -H "Content-Type: application/json" -d '{"input": ""}' \
  http://localhost:7071/admin/functions/nightly_totals
# queue trigger: drop a message
python send_order.py o-1002 7
Terminal
$ func --version
4.16.0
$ cd shop_app && fhost start
host started, functions:
  save_order: [POST] http://localhost:7071/api/orders
  nightly_totals: timerTrigger
  on_order: queueTrigger
$ bash try_it.sh
{"id": "o-1001", "amount": 25.5} 201
202
queued o-1002
$ cd shop_app && fhost wait "Executed 'Functions.on_order'" 60 && fhost log
Executing 'Functions.save_order' (Reason='This function was programmatically called via the host APIs.')
Executed 'Functions.save_order' (Succeeded)
Executing 'Functions.nightly_totals' (Reason='This function was programmatically called via the host
  APIs.')
nightly_totals ran, past_due=False
Executed 'Functions.nightly_totals' (Succeeded)
Executing 'Functions.on_order' (Reason='New queue message detected on 'orders'.')
order o-1002: amount 7.0
Executed 'Functions.on_order' (Succeeded)
$ cd shop_app && fhost stop
host stopped

func --version prints 4.16.0, and the host lists save_order, nightly_totals and on_order. Each trigger fires its own way. curl posts an order and gets 201 with the amount rounded to 25.5. The nightly timer runs now through the admin endpoint and returns 202; locally that needs no key, but in Azure it needs the master key. A script drops a queue message, and the log shows all three runs, with our own lines inside them, like order o-1002: amount 7.0.

For breakpoints, your editor starts this same host with the debugger attached.

My tips

Keep local.settings.json out of git, use func start --functions to load only what you are working on, and never point local runs at production storage.

Question 4: Someone asks how to unit test a Python function. How do you test it without Azure?

Keep the business logic in plain functions, keep the decorated function thin, and test both with unittest or pytest. No host, no storage and no Azure.

Let's look at the layers:

  • clean_order(): plain Python, test it first
  • save_order and on_order: thin decorated functions
  • Bindings: an integration run on the host and Azurite

The azure-functions package has real request and message classes. We build a func.HttpRequest or a func.QueueMessage in the test, call the decorated function directly, and check what comes back. There are four tests: the amount is rounded, a missing amount returns 400, a queue message is logged, and a bad message raises. Let's run them:

shop_app/tests/__init__.py
shop_app/tests/test_orders.py
import unittest

import azure.functions as func

from function_app import clean_order, on_order, save_order


def http_post(body: bytes) -> func.HttpRequest:
    return func.HttpRequest(method="POST", url="/api/orders",
                            body=body)


class OrderTests(unittest.TestCase):
    def test_amount_is_rounded(self):
        order = clean_order({"id": "o-1", "amount": "25.499"})
        self.assertEqual(order, {"id": "o-1", "amount": 25.5})

    def test_missing_amount_returns_400(self):
        resp = save_order(http_post(b'{"id": "o-2"}'))
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(resp.get_body(), b"amount missing")

    def test_queue_message_is_logged(self):
        msg = func.QueueMessage(body=b'{"id": "o-3", "amount": 7}')
        with self.assertLogs(level="INFO") as logs:
            on_order(msg)
        self.assertIn("order o-3: amount 7.0", logs.output[0])

    def test_bad_message_raises(self):     # so the host retries it
        msg = func.QueueMessage(body=b'{"id": "o-4"}')
        with self.assertRaises(ValueError):
            on_order(msg)
Terminal
$ cd shop_app && python -m unittest -v 2>&1 | sed -E 's/ in [0-9.]+s$//'
test_amount_is_rounded (tests.test_orders.OrderTests.test_amount_is_rounded) ... ok
test_bad_message_raises (tests.test_orders.OrderTests.test_bad_message_raises) ... ok
test_missing_amount_returns_400 (tests.test_orders.OrderTests.test_missing_amount_returns_400) ... ok
test_queue_message_is_logged (tests.test_orders.OrderTests.test_queue_message_is_logged) ... ok

----------------------------------------------------------------------
Ran 4 tests

OK

All four print ok, and the run ends with Ran 4 tests and OK, with no host running. Calling the decorated function directly works with azure-functions 1.21.0 or later; this project runs 2.3.0.

The bad-message test matters most. A queue function must raise, so the host retries and finally moves the message to the poison queue.

Real project

Unit tests do not prove the bindings. In CI/CD I add a short integration run on the local host and Azurite, like question 3, and a smoke test after every deployment.

Question 5: A teammate asks how to deploy a function app safely. What are the deployment options?

It depends on the plan, and safe means a pipeline, not a laptop.

PlanDeploymentNotes
Flex Consumptionone deploy (the CLI zip command uses it)package in a blob container; no slots
Premiumzip deploy; containers on Linuxrun from package; 3 deployment slots
Dedicated (App Service)zip deploy; containers on Linuxrun from package; 1 to 20 slots
Consumption (legacy)zip deployLinux: package URL only; 2 slots

Flex Consumption takes only its own package deployment, called one deploy: the zip goes to a blob container and the app runs from it, and the usual zip commands use it for you. Premium, Dedicated and legacy Consumption take zip deploy, and Linux Premium or Dedicated can run containers.

Run from package, WEBSITE_RUN_FROM_PACKAGE, mounts the zip read-only, which cuts cold starts; the limit is 1 GB. On Linux Consumption it must be a package URL.

Python dependencies must be built for Linux, so use a remote build. Core Tools always requests one for Python on Flex; with the CLI zip command, pass --build-remote true:

deploy.sh (Azure, not run)
# Core Tools: remote build, run from the package (default)
func azure functionapp publish func-orders-prod --build remote

# CI/CD, any plan (Flex: one deploy under the hood)
az functionapp deployment source config-zip \
  -g rg-data -n func-orders-prod \
  --src orders_app.zip --build-remote true

Then the pipeline, step by step:

  • Build once: one package per commit, in CI/CD
  • Same artifact: to test, then to prod
  • Smoke test: after every deployment
  • Keep the previous artifact: redeploy it to roll back
Pitfall

Assuming the settings came along. local.settings.json is not published unless you pass --publish-local-settings, so manage app settings as infrastructure as code.

Question 6: A deployment broke production. How do slots and rollbacks help?

On Premium, Dedicated and the legacy Consumption plan, deploy to a staging slot, test it there, then swap it into production. Rollback is the same swap again, so the last good version is one command away.

PlanSlots
Consumption (legacy)2
Premium3
Dedicated1 to 20
Flex Consumptionnone

Let's look at what a swap does, in order:

  • Settings: production settings are applied to staging first
  • Restart, then switch: routing moves after the restart
  • Not zero downtime: running executions can be cut off
  • Slot settings: sticky, they stay with their slot

Staging is a live app, so its timers and triggers fire too. Disable them there with a sticky AzureWebJobs.<function>.Disabled setting, or staging loads the data a second time:

slots.sh (Azure, not run)
az functionapp deployment slot create -g rg-data \
  -n func-orders-prod --slot staging
# sticky: the staging timer never fires
az functionapp config appsettings set -g rg-data \
  -n func-orders-prod --slot staging --slot-settings \
  AzureWebJobs.nightly_totals.Disabled=true
func azure functionapp publish func-orders-prod --slot staging
# smoke test staging, then swap; rollback = swap again
az functionapp deployment slot swap -g rg-data \
  -n func-orders-prod --slot staging --target-slot production

# Flex Consumption: no slots, rolling updates
az functionapp update-strategy config set -g rg-data \
  -n func-orders-flex --type RollingUpdate

Flex Consumption has no slots. Use rolling updates, GA since June 2026 and rolling out region by region, plus a separate staging app. There is no built-in revision history, so rollback means redeploying the last good build.

Remember

Keep every change backward compatible, because during a rolling update old and new code run side by side.

Scenario 7: A function silently stopped processing files for two days and nobody noticed. What do you put in place?

Monitor the outcome, not the process. First let's see why it was silent.

A settings cleanup removed the LakeStorage connection. We start files_app, check the health endpoint, have partners drop three files with partner_drop.py, and run the watchdog with watchdog.py:

files_app/function_app.py
import logging
import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)


@app.route(route="health")
def health(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse("ok")


@app.blob_trigger(arg_name="src", path="landing/{name}",
                  connection="LakeStorage")
@app.blob_output(arg_name="out", path="curated/{name}",
                 connection="LakeStorage")
def convert_file(src: func.InputStream, out: func.Out[str]) -> None:
    rows = src.read().decode().strip().splitlines()[1:]
    out.set("\n".join(rows))
    logging.info("converted %s rows=%d", src.name, len(rows))
files_app/host.json
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "extensions": {
    "queues": {"maxPollingInterval": "00:00:01"}
  },
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Azure.Core": "Error",
      "Host.Function.Console": "Information"
    }
  }
}
files_app/local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}
files_app/requirements.txt
azure-functions
partner_drop.py
import os
from azure.storage.blob import BlobServiceClient

svc = BlobServiceClient.from_connection_string(
    os.environ["AZURE_STORAGE_CONNECTION_STRING"])
for c in ["landing", "curated"]:
    if not svc.get_container_client(c).exists():
        svc.create_container(c)
files = {"acme_0901.csv": "id,amount\n1,20.5\n2,7\n",
         "globex_0901.csv": "id,amount\n7,12.5\n",
         "initech_0901.csv": "id,amount\n9,40\n10,3\n11,8\n"}
for name, text in files.items():
    svc.get_blob_client("landing", name).upload_blob(text,
                                                     overwrite=True)
print("partners dropped", len(files), "files into landing/")
watchdog.py
import os, sys
from datetime import datetime, timedelta, timezone
from azure.storage.blob import BlobServiceClient

svc = BlobServiceClient.from_connection_string(
    os.environ["AZURE_STORAGE_CONNECTION_STRING"])
limit = timedelta(minutes=int(sys.argv[1]))   # 30 in production
now = datetime.now(timezone.utc)
done = set(svc.get_container_client("curated").list_blob_names())
landing = list(svc.get_container_client("landing").list_blobs())
late = sorted(b.name for b in landing if b.name not in done
              and now - b.last_modified >= limit)
print(f"landing: {len(landing)} | curated: {len(done)}"
      f" | waiting too long: {len(late)}")
print(f"ALERT: {late}" if late else "OK: nothing waiting")
Terminal
$ cd files_app && fhost start
Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.convert_file'.
  Microsoft.Azure.WebJobs.Extensions.Storage.Blobs: Storage account connection string
    'AzureWebJobsLakeStorage' does not exist. Make sure that it is a defined App Setting.
Error indexing method 'Functions.convert_file'
Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.convert_file'.
  Microsoft.Azure.WebJobs.Extensions.Storage.Blobs: Storage account connection string
    'AzureWebJobsLakeStorage' does not exist. Make sure that it is a defined App Setting.
Function 'Functions.convert_file' failed indexing and will be disabled.
The 'convert_file' function is in error: Microsoft.Azure.WebJobs.Host: Error indexing method
  'Functions.convert_file'. Microsoft.Azure.WebJobs.Extensions.Storage.Blobs: Storage account
    connection string 'AzureWebJobsLakeStorage' does not exist. Make sure that it is a defined App
      Setting.
host started, functions:
  health:  http://localhost:7071/api/health
  convert_file: blobTrigger
$ curl -s -w ' %{http_code}\n' http://localhost:7071/api/health
ok 200
$ python partner_drop.py
partners dropped 3 files into landing/
$ python watchdog.py 0
landing: 3 | curated: 0 | waiting too long: 3
ALERT: ['acme_0901.csv', 'globex_0901.csv', 'initech_0901.csv']
$ cd files_app && fhost stop
host stopped

At startup the host says Function 'Functions.convert_file' failed indexing and will be disabled., but the app keeps running, and health still says ok 200. Nothing converts the files and nothing errors, because a disabled function never runs, so an alert on failures stays green.

The watchdog compares landing with curated and flags files waiting too long: landing: 3 | curated: 0 | waiting too long: 3, then an ALERT with all three names. Here the limit is 0 minutes; in production it runs on a schedule with a 30-minute limit. Now we put the setting back:

files_app/local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "LakeStorage": "UseDevelopmentStorage=true"
  }
}
Terminal
$ cd files_app && fhost start
host started, functions:
  health:  http://localhost:7071/api/health
  convert_file: blobTrigger
$ cd files_app && fhost wait "Executed 'Functions.convert_file'" 60 3 && fhost log | grep converted | sort
converted landing/acme_0901.csv rows=2
converted landing/globex_0901.csv rows=1
converted landing/initech_0901.csv rows=3
$ python watchdog.py 0
landing: 3 | curated: 3 | waiting too long: 0
OK: nothing waiting
$ cd files_app && fhost stop
host stopped

The host converts the three waiting files and the watchdog says OK: nothing waiting. In Azure I also alert when a function has zero executions in two hours:

alert.kql (Azure Monitor, not run)
// alert rule: convert_file has not run for two hours
requests
| where timestamp > ago(2h)
| where operation_Name == "convert_file"
| summarize runs = count()
| where runs == 0

On Flex, with the Event Grid source, failed events are dropped within 24 hours by default, so replay the watchdog's list. Then:

  • Alert on functions in error, and on AzureWebJobs.<function>.Disabled flags
  • Check Key Vault reference status after every settings change
  • Timers: log isPastDue
  • Sampling: exclude Request, keep every run
Real project

A health endpoint only proves the app is up. Measure the files that came out.

Key points to remember

  • Watch executions, failures, exceptions, dependencies and backlog; exclude Request from sampling
  • Log with the logging module, business keys and logging.exception; levels in host.json
  • Run locally with Core Tools and Azurite; fire timers through the admin endpoint
  • Unit test thin functions directly with func.HttpRequest and func.QueueMessage
  • Deploy one artifact from CI/CD; roll back with a slot swap or a redeploy on Flex; alert on no runs

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
Full script - writes the files and runs every step with Azure Functions Core Tools and Azurite (pip install azure-functions azure-functions-durable azure-storage-blob azure-storage-queue azure-data-tables), run it with Python
# ========================================================================
# Azure Functions Interview Q&A #9 - Monitoring, testing and deployment
# 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_09_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" ...

# Step 1: Log from a Python HTTP function: levels, business keys and logging.exception
write('orders_app/function_app.py', """\
import logging
import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
BATCHES = {"b-17": [25.5, None, 7.25, 12.0], "b-18": [None, None]}


@app.route(route="load_batch", methods=["POST"])
def load_batch(req: func.HttpRequest) -> func.HttpResponse:
    batch = req.params.get("batch", "")
    logging.debug("params %s", dict(req.params))   # not shown
    if batch not in BATCHES:
        logging.error("batch=%s status=not_found", batch)
        return func.HttpResponse("unknown batch", status_code=404)
    rows = [r for r in BATCHES[batch] if r is not None]
    rejected = len(BATCHES[batch]) - len(rows)
    if rejected:
        logging.warning("batch=%s rejected=%d reason=amount_missing",
                        batch, rejected)
    try:
        avg = sum(rows) / len(rows)
    except ZeroDivisionError:
        logging.exception("batch=%s status=failed", batch)
        return func.HttpResponse("load failed", status_code=500)
    logging.info("batch=%s status=loaded rows=%d avg_amount=%.2f",
                 batch, len(rows), avg)
    return func.HttpResponse(f"loaded {len(rows)} rows")
""")
write('orders_app/host.json', """\
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "extensions": {
    "queues": {"maxPollingInterval": "00:00:01"}
  },
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Azure.Core": "Error",
      "Host.Function.Console": "Information"
    }
  }
}
""")
write('orders_app/local.settings.json', """\
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}
""")
write('orders_app/requirements.txt', """\
azure-functions
""")
write('calls.sh', 'for b in b-17 b-18 b-99; do\n  curl -s -w " %{http_code}\\n" -X POST \\\n    "http://localhost:7071/api/load_batch?batch=$b"\ndone\n')
run('cd orders_app && python "$FHOST" start')
run('bash calls.sh')
run('cd orders_app && python "$FHOST" wait "Executed \'Functions.load_batch\'" 60 3 && python "$FHOST" log')
run('cd orders_app && python "$FHOST" stop')

# Step 2: Run an HTTP, a timer and a queue function locally with Core Tools and Azurite
write('shop_app/function_app.py', """\
import json
import logging
import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)


def clean_order(order: dict) -> dict:
    if order.get("amount") is None:
        raise ValueError("amount missing")
    amount = round(float(order["amount"]), 2)
    return {"id": order["id"], "amount": amount}


@app.route(route="orders", methods=["POST"])
def save_order(req: func.HttpRequest) -> func.HttpResponse:
    try:
        order = clean_order(req.get_json())
    except ValueError as e:
        return func.HttpResponse(str(e), status_code=400)
    return func.HttpResponse(json.dumps(order), status_code=201)


@app.queue_trigger(arg_name="msg", queue_name="orders",
                   connection="AzureWebJobsStorage")
def on_order(msg: func.QueueMessage) -> None:
    order = clean_order(msg.get_json())
    logging.info("order %s: amount %s", order["id"], order["amount"])


@app.timer_trigger(schedule="0 0 2 * * *", arg_name="timer",
                   run_on_startup=False)
def nightly_totals(timer: func.TimerRequest) -> None:
    logging.info("nightly_totals ran, past_due=%s", timer.past_due)
""")
write('shop_app/host.json', """\
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "extensions": {
    "queues": {"maxPollingInterval": "00:00:01"}
  },
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Azure.Core": "Error",
      "Host.Function.Console": "Information"
    }
  }
}
""")
write('shop_app/local.settings.json', """\
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}
""")
write('shop_app/requirements.txt', """\
azure-functions
""")
write('send_order.py', """\
import json, os, sys
from azure.storage.queue import QueueClient, TextBase64EncodePolicy

q = QueueClient.from_connection_string(
    os.environ["AZURE_STORAGE_CONNECTION_STRING"], "orders",
    message_encode_policy=TextBase64EncodePolicy())   # base64
try:
    q.create_queue()
except Exception:
    pass                                 # already there
q.send_message(json.dumps({"id": sys.argv[1], "amount": sys.argv[2]}))
print("queued", sys.argv[1])
""")
write('try_it.sh', '# HTTP trigger: post an order\ncurl -s -w " %{http_code}\\n" -X POST \\\n  -d \'{"id": "o-1001", "amount": "25.499"}\' \\\n  http://localhost:7071/api/orders\n# timer trigger: run it now through the admin endpoint\ncurl -s -w "%{http_code}\\n" -X POST \\\n  -H "Content-Type: application/json" -d \'{"input": ""}\' \\\n  http://localhost:7071/admin/functions/nightly_totals\n# queue trigger: drop a message\npython send_order.py o-1002 7\n')
run('func --version')
run('cd shop_app && python "$FHOST" start')
run('bash try_it.sh')
run('cd shop_app && python "$FHOST" wait "Executed \'Functions.on_order\'" 60 && python "$FHOST" log')
run('cd shop_app && python "$FHOST" stop')

# Step 3: Unit test the functions with unittest: no host, no storage, no Azure
write('shop_app/tests/__init__.py', """\

""")
write('shop_app/tests/test_orders.py', """\
import unittest

import azure.functions as func

from function_app import clean_order, on_order, save_order


def http_post(body: bytes) -> func.HttpRequest:
    return func.HttpRequest(method="POST", url="/api/orders",
                            body=body)


class OrderTests(unittest.TestCase):
    def test_amount_is_rounded(self):
        order = clean_order({"id": "o-1", "amount": "25.499"})
        self.assertEqual(order, {"id": "o-1", "amount": 25.5})

    def test_missing_amount_returns_400(self):
        resp = save_order(http_post(b'{"id": "o-2"}'))
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(resp.get_body(), b"amount missing")

    def test_queue_message_is_logged(self):
        msg = func.QueueMessage(body=b'{"id": "o-3", "amount": 7}')
        with self.assertLogs(level="INFO") as logs:
            on_order(msg)
        self.assertIn("order o-3: amount 7.0", logs.output[0])

    def test_bad_message_raises(self):     # so the host retries it
        msg = func.QueueMessage(body=b'{"id": "o-4"}')
        with self.assertRaises(ValueError):
            on_order(msg)
""")
run("cd shop_app && python -m unittest -v 2>&1 | sed -E 's/ in [0-9.]+s$//'")

# Step 4: The LakeStorage setting is gone: convert_file is disabled, health still says ok, files pile up
write('files_app/function_app.py', 'import logging\nimport azure.functions as func\n\napp = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)\n\n\n@app.route(route="health")\ndef health(req: func.HttpRequest) -> func.HttpResponse:\n    return func.HttpResponse("ok")\n\n\n@app.blob_trigger(arg_name="src", path="landing/{name}",\n                  connection="LakeStorage")\n@app.blob_output(arg_name="out", path="curated/{name}",\n                 connection="LakeStorage")\ndef convert_file(src: func.InputStream, out: func.Out[str]) -> None:\n    rows = src.read().decode().strip().splitlines()[1:]\n    out.set("\\n".join(rows))\n    logging.info("converted %s rows=%d", src.name, len(rows))\n')
write('files_app/host.json', """\
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "extensions": {
    "queues": {"maxPollingInterval": "00:00:01"}
  },
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Azure.Core": "Error",
      "Host.Function.Console": "Information"
    }
  }
}
""")
write('files_app/local.settings.json', """\
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}
""")
write('files_app/requirements.txt', """\
azure-functions
""")
write('partner_drop.py', 'import os\nfrom azure.storage.blob import BlobServiceClient\n\nsvc = BlobServiceClient.from_connection_string(\n    os.environ["AZURE_STORAGE_CONNECTION_STRING"])\nfor c in ["landing", "curated"]:\n    if not svc.get_container_client(c).exists():\n        svc.create_container(c)\nfiles = {"acme_0901.csv": "id,amount\\n1,20.5\\n2,7\\n",\n         "globex_0901.csv": "id,amount\\n7,12.5\\n",\n         "initech_0901.csv": "id,amount\\n9,40\\n10,3\\n11,8\\n"}\nfor name, text in files.items():\n    svc.get_blob_client("landing", name).upload_blob(text,\n                                                     overwrite=True)\nprint("partners dropped", len(files), "files into landing/")\n')
write('watchdog.py', """\
import os, sys
from datetime import datetime, timedelta, timezone
from azure.storage.blob import BlobServiceClient

svc = BlobServiceClient.from_connection_string(
    os.environ["AZURE_STORAGE_CONNECTION_STRING"])
limit = timedelta(minutes=int(sys.argv[1]))   # 30 in production
now = datetime.now(timezone.utc)
done = set(svc.get_container_client("curated").list_blob_names())
landing = list(svc.get_container_client("landing").list_blobs())
late = sorted(b.name for b in landing if b.name not in done
              and now - b.last_modified >= limit)
print(f"landing: {len(landing)} | curated: {len(done)}"
      f" | waiting too long: {len(late)}")
print(f"ALERT: {late}" if late else "OK: nothing waiting")
""")
run('cd files_app && python "$FHOST" start')
run("curl -s -w ' %{http_code}\\n' http://localhost:7071/api/health")
run('python partner_drop.py')
run('python watchdog.py 0')
run('cd files_app && python "$FHOST" stop')

# Step 5: Put the setting back: the waiting files are converted and the watchdog is quiet
write('files_app/local.settings.json', """\
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "LakeStorage": "UseDevelopmentStorage=true"
  }
}
""")
run('cd files_app && python "$FHOST" start')
run('cd files_app && python "$FHOST" wait "Executed \'Functions.convert_file\'" 60 3 && python "$FHOST" log | grep converted | sort')
run('python watchdog.py 0')
run('cd files_app && python "$FHOST" stop')
Next in this series

Part 10: Real-World Manager Scenarios

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.