MSBA-273 · Lesson 4 of 12 · 20 min

Azure Functions and Service Bus integration

▶ Video coming soon A video version of this lesson is on the way.

The fourth session returned to a design that Signe had recorded in the earlier developer series as decision D4, dated November 12, 2026: the building management alarm integration. The building management system in each campus raised alarms for boiler pressure, freezer temperatures in the science labs, failed exhaust fans and dozens of other conditions. Today a Facilities coordinator watched the alarm console and typed work orders by hand. The D4 design would bring the alarms into Dataverse automatically and raise work orders for the ones that mattered. The design was approved as an approach but had not been funded, so the session treated it as a worked example: how Azure Functions and Azure Service Bus fit together with Dataverse, and why each part of D4 was there.

The D4 plan as a left-to-right pipeline: building management gateway, Service Bus queue with a dead-letter queue beneath, an ingest Azure Function with a managed identity, an elastic table lcc_alarmevent with a 30-day expiry, a summarizing Azure Function on a timer, and a custom API that raises work orders in the standard work order table. A banner reads plan only, not funded.
Decision D4: the planned building management alarm integration.

Why put a queue in the middle

Alarms arrive in bursts. On a quiet day the three campuses produce a few hundred. During a power cut or a cold snap, one building can produce hundreds in a few minutes as every sensor reports at once. If the building management gateway posted each alarm straight into Dataverse, a burst would run into the service protection limits, the gateway would receive 429 responses it was never designed to handle, and alarms could be lost. A Service Bus queue absorbs the burst. The gateway sends messages to the queue as fast as it likes; the receiving function reads them at a pace Dataverse can accept; and if Dataverse or the function is unavailable for a while, the messages wait.

This is the core idea of queue-based load leveling, and it appears in almost every integration that crosses a boundary between systems with different speeds or availability. The queue decouples the sender from the receiver in time, in pace and in failure. Neither needs to be online when the other is, and neither needs to know how the other is built.

Azure Service Bus essentials

Service Bus is Azure's enterprise message broker. A namespace is the container; inside it are queues, which deliver each message to one receiver, and topics, which deliver a copy to each subscription. Messages carry a body and properties, including a message identifier, a correlation identifier, a content type and any custom application properties the sender adds.

Service Bus features and how the D4 design uses them.
FeatureWhat it doesUse in D4
Peek-lock receiveLocks a message while the receiver works; the receiver completes it on success or abandons it on failureThe ingest function completes a message only after the row is written
Maximum delivery countAfter this many failed attempts the message moves to the dead-letter queue (the default is 10)Malformed alarms end up in the dead-letter queue instead of blocking the queue
Dead-letter queueA sub-queue holding messages that could not be processed or expiredReviewed daily by the integration owner
Duplicate detectionDrops messages with a message identifier already seen within a time windowThe gateway sets the message identifier to its own alarm identifier
Time to liveMessages older than the limit expireAlarms older than a day are of no use and expire to the dead-letter queue
SessionsGroups related messages and delivers each group in order to one receiverNot needed; alarms are independent

Access to Service Bus can use shared access signature keys or Microsoft Entra ID with Azure role-based access control. The D4 design used Entra ID throughout: the gateway's own identity held the Azure Service Bus Data Sender role on the queue, and the ingest function's managed identity held the Azure Service Bus Data Receiver role. No connection string with a key appeared anywhere. The Dataverse service endpoints from Lesson 3 are the exception, because their registration uses a shared access signature; where Dataverse posts to Service Bus, the key is scoped to send to one queue or topic only.

Azure Functions essentials

Azure Functions runs small pieces of code in response to triggers: an HTTP request, a timer, a message on a queue or topic, a new blob in storage and many others. Bindings connect a function to other services declaratively, so a function triggered by Service Bus receives the message as a parameter without writing receive loops. Functions scale out automatically as messages build up, within limits that the hosting plan and the trigger settings control.

For .NET, new functions use the isolated worker model, in which the function runs in its own process with its own dependencies. Microsoft's documentation states that support for the older in-process model ended on November 10, 2026, so any in-process function still running at Lumenvale or elsewhere is overdue for migration. The hosting plan decides how the function scales, whether it can reach private networks, and how long it may run; Lumenvale's architects would choose a plan with virtual network integration, because the D4 design kept the queue reachable only from the college's network.

Listing 4.1: The ingest function in the D4 design (C#, not executable here).
// C# isolated worker: read alarms from the queue and write them to the elastic table.
public class IngestAlarm(ServiceClient dataverse, ILogger<IngestAlarm> log)
{
    [Function("IngestAlarm")]
    public async Task Run(
        [ServiceBusTrigger("bms-alarms", Connection = "AlarmBus")] ServiceBusReceivedMessage msg)
    {
        var alarm = JsonSerializer.Deserialize<AlarmDto>(msg.Body.ToString())
                    ?? throw new InvalidDataException("Empty alarm");

        var row = new Entity("lcc_alarmevent")
        {
            ["lcc_sourcealarmid"] = alarm.Id,          // the gateway's identifier
            ["lcc_buildingcode"]  = alarm.Building,
            ["lcc_point"]         = alarm.Point,
            ["lcc_severity"]      = alarm.Severity,
            ["lcc_raisedon"]      = alarm.RaisedUtc,
            ["ttlinseconds"]      = 30 * 24 * 60 * 60   // expire after 30 days
        };
        await dataverse.CreateAsync(row);
        log.LogInformation("Alarm {Id} stored, correlation {Cid}", alarm.Id, msg.CorrelationId);
    }   // returning normally completes the message; an exception abandons it for retry
}

Three details in Listing 4.1 matter. The ServiceClient is injected, created once at start-up with the managed identity token provider from Lesson 2, and reused for every message; creating a client per message would be slow and wasteful. The function completes the message only by returning normally, so a failure to write the row leaves the message on the queue to be retried, and after the maximum delivery count it moves to the dead-letter queue for a person to examine. And the log line records identifiers, not the alarm's contents or any personal data.

Why an elastic table

Alarm events are high in volume, short-lived and simple: no business process flows, no complex security, no need to be joined with dozens of other tables. That profile fits an elastic table, which stores rows in Azure Cosmos DB behind the Dataverse interface. Elastic tables scale to very high write volumes and support a time-to-live column, ttlinseconds, that deletes each row automatically when its time runs out. The D4 design set that column to 30 days on every row, so the alarm table would never grow beyond about a month of history and nobody would need to write a clean-up job.

Elastic tables have trade-offs, which Lesson 5 covers in detail: transactions are limited, some relationship and query features differ from standard tables, and bulk operations behave differently. For raw alarm events those trade-offs did not matter. The work orders themselves stay in the standard lcc_workorder table, with its full security, business rules and plug-ins.

The summarizing function and the custom API

Not every alarm deserves a work order. A freezer that warms for two minutes during a door opening and then recovers is normal; one that stays warm for twenty minutes is a problem. A boiler that reports the same fault forty times in an hour needs one work order, not forty. The D4 design therefore separated storing alarms from acting on them. A second function, triggered by a timer every five minutes, would read recent alarm events, group them by building and point, apply the rules Facilities agreed, and call a custom API to raise work orders for the groups that crossed a threshold.

Putting the final step behind a custom API, named lcc_RaiseAlarmWorkOrder in the design, kept the business rules for creating an alarm work order inside Dataverse, where the plug-ins and security from the earlier courses already applied. The custom API would check for an open work order for the same building and point before creating a new one, so that the summarizing function could be retried safely. Its execute privilege would be held only by the summarizing function's application user and the Facilities supervisors' role.

Listing 4.2: The planned call from the summarizing function to the custom API (not executable here).
POST https://lumenvale.crm3.dynamics.com/api/data/v9.2/lcc_RaiseAlarmWorkOrder
Content-Type: application/json

{
  "BuildingCode": "LSB",
  "Point": "BLR-2 supply pressure",
  "Severity": 1,
  "FirstRaised": "2026-11-18T06:10:00Z",
  "AlarmCount": 14
}

Handling failure at every step

Signe walked through what would happen when each part failed, because an integration design is only as good as its failure behavior.

Failure behavior in the D4 design.
FailureWhat happensWho notices
Gateway cannot reach Service BusThe gateway buffers locally and retries; the alarm console still worksFacilities, through the gateway's own alerts
Ingest function is stoppedMessages wait in the queue until it restartsAn alert on queue length
Dataverse returns 429The client waits for Retry-After; the message lock may be renewedNobody needs to; throughput simply slows
An alarm message is malformedRetried, then moved to the dead-letter queueThe integration owner's daily review
Summarizing function failsAlarms are stored; the next timer run catches upAn alert on function failures
Custom API rejects a requestNo work order is created for that group; the error is loggedAn alert on custom API errors

Worked problem

Sizing the queue for a storm

During a cold snap, the gateway might send 1,800 alarms in 10 minutes. The ingest function, limited deliberately to protect Dataverse, processes about 60 messages a minute. How long does the backlog take to clear, and what is the largest backlog?

Show solution
  1. Arrival rate during the burst: 1,800 divided by 10 is 180 messages a minute.
  2. Net growth during the burst: 180 minus 60 is 120 messages a minute, so after 10 minutes the backlog is 1,200 messages.
  3. After the burst, the backlog drains at 60 a minute: 1,200 divided by 60 is 20 minutes.

Answer: The backlog peaks at 1,200 messages and clears about 20 minutes after the burst ends, 30 minutes after it began. No alarm is lost, and the message time to live of a day is far longer than the delay.

The example showed why the design deliberately limited the function's concurrency. Letting the function scale out to many instances would clear the backlog faster but would push Dataverse into service protection limits and slow every other integration and app in the environment. The queue turns a burst into a delay, and a delay of a few minutes in raising a maintenance work order was acceptable to Facilities. For life-safety alarms such as fire, the building's own fire alarm system remains the system of record; D4 was never meant to replace it.

Outbound messages through Service Bus

The same pieces work in the other direction. A Dataverse service endpoint posts an event to a queue or topic, and an Azure Function triggered by that queue calls the external system. That pattern suits external systems that are slow, have their own rate limits or are sometimes unavailable, because the function can retry and the queue holds messages in the meantime. When the external system needs a different shape of message, the function transforms it, keeping the mapping in code that can be tested.

Durable Functions, an extension that lets a function orchestrate a sequence of steps with saved state between them, suits longer processes, for example waiting for an external approval and then continuing. Signe mentioned it for completeness; neither the dispatch nor the alarm scenario needed it.

What D4 still needed before funding

The session ended with the list of open items Rupert would carry to the funding discussion: the building management vendor's confirmation that the gateway could send to Service Bus using Entra ID, a cost estimate for the Functions plan and Service Bus tier, the Facilities rules for grouping alarms, an owner for the dead-letter review, and the privacy officer's confirmation that alarm data held no personal information. Until those were settled, D4 remained a plan.

Common mistakes

  • MistakeLetting an external system post bursts directly into Dataverse.

    InsteadPut a queue in between so bursts become delays instead of throttling errors.

  • MistakeCreating a new ServiceClient for every message.

    InsteadCreate one client at start-up and reuse it.

  • MistakeLetting the function scale without limit.

    InsteadLimit concurrency so the receiver stays within Dataverse service protection limits.

  • MistakeIgnoring the dead-letter queue.

    InsteadAssign an owner, alert on its length and review it regularly.

  • MistakeBuilding new .NET functions on the in-process model.

    InsteadUse the isolated worker model; in-process support ended on November 10, 2026.

  • MistakeStoring a Service Bus connection string with a key in the function settings.

    InsteadUse managed identity with the Data Sender or Data Receiver role.

Summary and key terms

  • A Service Bus queue between systems levels bursts, survives outages and decouples sender and receiver.
  • Peek-lock, maximum delivery count, dead-letter queues, duplicate detection and time to live give reliable delivery.
  • Azure Functions react to triggers such as Service Bus messages and timers; .NET functions use the isolated worker model.
  • D4 stores raw alarms in an elastic table with a 30-day time to live and raises work orders through a custom API.
  • Limiting function concurrency protects Dataverse; the queue turns a burst into a short delay.
  • Managed identities and role-based access replace keys between the function, Service Bus and Dataverse.
Queue-based load leveling
Placing a queue between a sender and a receiver so that bursts are absorbed and processed at a steady rate.
Peek-lock
A Service Bus receive mode in which a message is locked while processed and removed only when the receiver completes it.
Maximum delivery count
The number of delivery attempts after which Service Bus moves a message to the dead-letter queue.
Isolated worker model
The .NET hosting model for Azure Functions in which function code runs in its own process.
Binding
A declarative connection between an Azure Function and another service, such as a Service Bus trigger.
Time to live
A setting after which a message or row expires automatically.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why does D4 store alarms first and raise work orders in a separate step?

    Show answer

    So that grouping rules can combine repeated alarms and ignore brief ones, and so storing and acting can fail and retry independently.

  2. What happens to a message that fails processing ten times with default settings?

    Show answer

    It moves to the dead-letter queue.

  3. Why does the custom API check for an open work order before creating one?

    Show answer

    To make the call idempotent so that retries do not create duplicates.

  4. Which Azure role does the ingest function's managed identity need on the queue?

    Show answer

    Azure Service Bus Data Receiver.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz