Correlation IDs and OpenTelemetry on Azure: One Request, Two Identities

A customer calls. Their order went through, the confirmation email never came, and the money left their account. The service desk has an order number. The on-call engineer has Application Insights. Between those two people sits a question I have watched teams get wrong for years: which identifier connects what the customer knows to what the platform recorded?

Most teams answer “the correlation ID” and then build one thing, when they need two. Correlation IDs and OpenTelemetry traces solve different problems, for different readers, with different lifetimes. The trace ID is the platform’s: minted per request, read by an engineer in a waterfall, gone from the conversation after a few seconds. The correlation ID is the business’s: it belongs to a workflow that may span days, it is what the customer can quote, and it must survive hops that no tracing SDK knows about. You need both; they must travel together, and they are not the same field.

So I built an order flow on Azure that carries both and measured where each one survives: through API Management, into an API on App Service, out to a payment provider over HTTP, across a Service Bus topic into two Function workers, and back into Application Insights. The code is in the companion repo, azd up away.

Four things that get called the correlation ID

Before the code, the vocabulary, because the confusion starts there.

The trace ID is the 32-hex W3C identifier in the traceparent header. The span ID is the 16-hex identifier of one operation inside that trace. OpenTelemetry owns both, every SDK forwards them, and nobody should ever type one into a customer email. The message ID belongs to the broker; Service Bus uses it for duplicate detection and nothing else. The correlation ID is the one the business owns. It is minted at the edge or supplied by the caller; it lives as long as the workflow, and it is what the service desk searches for.

Once you separate them, the design follows: the trace rides on the platform’s carriers, and you write no code for it; the correlation ID rides on carriers you choose, and you write a little code for it, exactly once per kind of hop.

What the sample does

An order comes in through API Management (Consumption tier). A policy keeps the caller’s X-Correlation-ID if there is one and mints gw-<12 hex> if there is not, then echoes it on the response so the caller can quote it. The gateway runs in W3C correlation mode, so its own span is the root of the trace and the traceparent it forwards is the one everything downstream continues.

The Order API on App Service runs the Azure Monitor OpenTelemetry distro. A small middleware reads the header, puts the value into OpenTelemetry baggage, tags the current span with correlation.id, and opens a logging scope with the same value. A processor copies the baggage value onto every span that starts afterwards, so one Kusto filter on customDimensions["correlation.id"] finds all of them. The API writes the order to Table Storage, calls the payment provider over HTTP, and publishes OrderPlaced to a Service Bus topic.

Two Function workers on Flex Consumption consume the topic: PaymentWorker captures the payment through the provider, NotificationWorker pretends to send an email. A third function plays the external payment provider and reports, on its own span, which of the three carriers reached it: traceparent, baggage, X-Correlation-ID.

Every component writes to one workspace-based Application Insights resource. Managed identities everywhere; local auth is off on Service Bus and shared keys are off on storage. The same stance as in the Azure Functions MCP server post: the role list is the authority.

The console makes the thesis visible without a query. Three orders placed with X-Correlation-ID: ticket-4813 show the same correlation ID and three different trace IDs. One business identity, three platform traces. The row placed without a header carries a gateway-minted gw- id instead.

Where each identity survives

HTTP hops: both travel, for free and almost free

Gateway to API, API to provider, worker to provider. On every HTTP hop the SDK writes traceparent and the baggage header, and the receiving side restores both. The trace continues without a line of code. The correlation ID also travels, in baggage, which is why the middleware puts it there.

Almost free, because of the receiver that is not yours. The payment provider is a stand-in for a system that has never heard of OpenTelemetry. It gets the X-Correlation-ID header too, added by a DelegatingHandler that reads baggage. That header is the fallback for every integration partner, legacy service, and log file in the chain. Baggage is for your own services; the header is for everyone else.

The provider logs which of the three arrived on every call. Over 661 calls in the measured runs, 331 authorize and 330 capture, all three were present every time: traceparent, baggage and X-Correlation-ID. The capture leg matters more than it looks, because it comes from the worker, after the message hop. It proves the correlation ID that was restored from the Service Bus property made it back into baggage and out onto the next HTTP call.

The message hop: the trace travels, the correlation ID does not

Service Bus is where the two identities part ways. The Azure SDK stamps Diagnostic-Id on every message with the current traceparent, and the Functions trigger reads it back, so PaymentWorker and NotificationWorker run inside the API’s trace. The paymentTraceId and notificationTraceId columns in the Orders table exist to prove it per order, and on every normal order in the measured run both matched the API’s trace ID.

Baggage does not cross Service Bus. There is no baggage property on the message and the SDK does not invent one. If the correlation ID lives only in baggage, it dies at the topic. The fix is one line on the sending side, message.ApplicationProperties["CorrelationId"] = correlationId, and one on the receiving side to restore it into baggage before any downstream call. The sample also sets the AMQP CorrelationId property, because Service Bus Explorer and most tooling display that one.

Redelivery: new span, same trace

FAIL-ONCE makes the payment worker throw on its first delivery. Service Bus redelivers; the second attempt is a new request span with the same operation id and messaging.message.delivery_count = 2. In the measured run, the order was captured 0.7 seconds after acceptance, so the abandon and the redelivery fit inside the first poll interval. Query 4 in measure/queries.kql lists orders with more than one delivery and confirms they sit in a single trace. Retries are not a new story; they are the second chapter of the same one.

The slow dependency: the waterfall answers the question

SLOW-PAY makes the provider sleep five seconds. The POST through the gateway took 5,803 ms, and nothing inside the API explains it until you open the dependency span. The same order shows the two branches of one message behaving independently: the notification worker reported Sent at 0.9 seconds while payment stayed Pending until 6.5 seconds, because capture hits the same delay. Query 5 sorts the dependencies of one trace by duration; the provider call is the first row and everything else is double digits. That is the whole promise of distributed tracing, and it only works because the trace survived the HTTP hop.

Sampling: three samplers, three answers

The last measurement is the one people skip, and it produced the most useful numbers in this post. I sent a burst of 100 orders three times and counted, per trace, how many of the six expected request spans arrived: gateway, API, provider authorize, PaymentWorker, provider capture, NotificationWorker.

RunGateway samplingAPI ratioTraces with any spanCompletePartialGateway keptAPI keptWorkers kept
1100 %1.01001000100100100
2100 %0.11001000100100100
310 %0.1100793715100

The second run

Run 2 is the first lesson. I set the API’s sampler to ten percent and nothing changed, because the API is no longer the root of the trace. The gateway is; it keeps everything, and it forwards traceparent with the sampled flag set. A parent-respecting sampler downstream does what the parent says. Once a gateway sits in front, the sampling decision moves to the gateway, whether anyone intended it or not.

The Third Run

Run 3 is the second lesson, and it splits three ways. API Management kept 7 of 100, its own ten percent. The API kept 15: the 7 the gateway marked as sampled, plus 8 of its own on traces the gateway had dropped. The Azure Monitor sampler honors a positive decision from the parent and makes its own on a negative one. And the Function workers kept all 100. In the isolated worker’s OpenTelemetry mode, the request spans are emitted by the Functions host, not by my code, and the host recorded every trigger regardless of the flag that arrived in Diagnostic-Id. The ParentBasedSampler I configured governs only the spans the worker itself starts.

So 93 of 100 traces were partial, and the smallest ones were exactly four spans: the workers, and nobody else. If your plan is “sample at the edge to save cost”, on this stack the edge saves cost at the edge, and the back end keeps paying full price, while every dropped trace turns into an orphaned tail that no waterfall will ever show you.

The honest recommendation is narrower than the usual advice. Either do not head-sample at all and control cost with ingestion caps and retention, or sample at the first component you fully control and verify, with exactly this query, that every downstream hop follows. On this stack today, the Functions host does not.

Where this is the wrong answer

A correlation ID per request. If the gateway mints a new value on every call, you have a second trace ID with a worse format. The value only earns its name when the client can supply one for the whole workflow: the order number, the support ticket, the batch run. The gateway mints a value for callers who do not, and the response header tells them what it was.

Baggage as a data bus. Baggage is sent on every outgoing request, to every destination, including the payment provider you do not own. Put one identifier in it, never a customer ID, never an email address, never a token. The processor in the sample copies exactly one key for exactly that reason.

Correlation ID in the message body. It works until a consumer deserializes into a type that does not have the field, or a dead-letter viewer shows you properties and not payloads. Application properties are visible to the broker, to tooling, and to subscription filters. The body is for the business event.

Sampling anywhere but the root. Run 3 is the proof. If three components make three decisions, the only traces you can rely on are the ones all three happened to keep.

What the first run against Azure taught me

The measured run

python measure/drive.py all through the API Management endpoint in swedencentral:

  • POST through the gateway: 783 to 1,021 ms warm; 8,986 ms on the very first order, which is Flex Consumption cold-starting the payment provider.
  • Happy path: both workers reported the API’s trace id and had finished before the first poll at 0.8 s.
  • Client-supplied X-Correlation-ID: ticket-34d199: kept by the gateway, echoed on the response, present on every span.
  • SLOW-PAY: POST 5,803 ms; notification Sent at 0.9 s, payment Captured at 6.5 s.
  • FAIL-ONCE: Captured at 0.7 s after one redelivery.
  • DECLINE: 402, nothing published, both worker trace columns empty.
  • Sampling: the three-run table above.

What broke first

  1. A binary mismatch inside the Functions worker. Pinning Microsoft.Azure.Functions.Worker 2.0.0 next to Microsoft.Azure.Functions.Worker.OpenTelemetry 1.1.0 pulled a newer Worker.Core than Worker.Grpc, and every invocation died with MissingMethodException: DefaultTraceContext..ctor. The three functions listed fine; they just could not be invoked. Letting NuGet take the latest of Worker, Worker.Sdk and Worker.OpenTelemetry together fixed it. [TODO: the versions that NuGet picked]
  2. Resource names. My environment name was 19 characters; the Bicep took the first 12, and the cut landed on a hyphen. Service Bus refuses a double hyphen; eight other resource types accepted it. Strip the hyphens before you cut.
  3. The console called /api/orders as an absolute path and got a 404 from the gateway, because behind API Management the app lives under /orders/. Every path in a page served through a gateway has to be resolved relative to the page, and location.pathname plus a slash is not enough once someone opens /orders/index.html. new URL('api/orders', location.href) is.
  4. Telemetry from a brand-new workspace took close to ten minutes to show up on the first run, long enough to suspect the exporters. They were fine.
  5. On Windows arm64, ten Python threads creating the default SSL context at once produced ssl.SSLError: malloc failure. One warm-up request before the thread pool fixed it. Not Azure’s fault, but it cost a run.

None of these is about correlation or tracing. All of them are the kind of thing that stands between a diagram and a measurement, which is why I keep deploying before I write. The same held for [the scalable solutions reference architecture](INTERNAL-LINK: scalable-solutions post URL) a few days earlier.

Closing

Correlation IDs and OpenTelemetry are not competitors and not synonyms. OpenTelemetry gives the engineer a trace that crosses HTTP and Service Bus without any code, as long as nobody breaks the parent chain. The correlation ID gives the service desk, the customer and the auditor a handle on the workflow, and it needs one header for HTTP, one application property for messaging, and one processor to make it searchable. Build both, keep them apart, decide sampling once at the root, and the phone call at the top of this post takes one query instead of an afternoon.

The repo is at github.com/steefjan1/correlation-tracing-azure. azd up, run measure/drive.py, flip the sampling ratios, and azd down --purge when you are done.

Sources

Circuit Breaker Pattern on Azure

Your payment service is down. A customer has just pressed “Place order”. What happens next?

The textbook answer is the circuit breaker pattern. Detect the failures, stop calling the broken service, and give it time to recover. Three states: closed, open, half-open. Every explanation of the pattern ends there, and so does most code I review.

But the breaker answers only one question: when do we stop calling? It says nothing about the order. The customer does not care that your circuit is open. They care whether their order went through.

So I built it. One order API, one payment provider that fails on command, and four ways to connect them on Azure. Then I broke the provider and counted. The sample is on GitHub: circuit-breaker-azure. One azd up deploys it.

The setup

The Orders API is an Azure Function App on Flex Consumption. It saves every order to Table Storage first and then tries to charge. The payment provider is a second Function App, a stub with five modes: healthy, down, slow, slow-success, and flaky. The stub counts every call it receives. That count proves what a breaker stopped.

A query parameter selects the path:

  1. naive: a plain HttpClient. No breaker.
  2. breaker: a Polly circuit breaker inside the Function App process.
  3. gateway: Azure API Management holds the breaker. The app has none.
  4. fallback: the breaker from path 2, plus a Service Bus queue for payments that could not be made.

Paths 1 to 3 fail the order when the payment fails. Only path 4 answers the opening question.

Without a breaker, slow is worse than down

First, the baseline. A provider that is down answers quickly with an error. That is annoying, but cheap. The expensive failure is a slow provider. Every caller waits, holds a connection, and holds memory. Then the error arrives anyway.

I set the stub to answer after eight seconds with a 503 and sent 40 orders, eight at a time, through the naive path.

Naive path, provider answers 503 after 8 sMeasured
Orders failed40 of 40
Latency per order, p50 / p958,240 ms / 8,273 ms
Time to work through 40 orders41.3 s
Calls that reached the provider40

A healthy order in the same setup takes 232 ms at p50. During the slow outage, every order held its connection 35 times longer, only to fail.

Every one of those calls reached a provider that was already in trouble. This is how one failing service takes its callers down with it. The callers are not broken. They are waiting.

The circuit breaker pattern in the process

In .NET, the circuit breaker pattern is a few lines. Microsoft.Extensions.Http.Resilience puts a Polly pipeline on an HttpClient:

services.AddHttpClient(PaymentClient.Breaker, client =>
{
client.BaseAddress = new Uri(settings.PaymentUrl);
})
.AddResilienceHandler("payment", (pipeline, context) =>
{
pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.5,
MinimumThroughput = 10,
SamplingDuration = TimeSpan.FromSeconds(10),
BreakDuration = TimeSpan.FromSeconds(15)
});
pipeline.AddTimeout(TimeSpan.FromSeconds(2));
});

Two details matter more than the three states.

The timeout is half of the pattern. A breaker counts failures. A call that hangs for eight seconds is not a failure until something says so. The two-second attempt timeout sits inside the breaker, so every timed-out call counts in the sampling window. Without it, the breaker watches slow calls and does nothing.

The threshold is not a count. “Failures greater than threshold” is the usual phrasing. A real breaker opens on a failure ratio, over a sampling window, and only after a minimum number of calls. Three failures out of three calls at 03:00 should not open a circuit. The defaults of the standard resilience handler show the intent: a 10 percent failure ratio, a minimum throughput of 100 calls, a 30-second sampling window, and a 5-second break. My demo values are much smaller, so the circuit trips within seconds.

It also matters what counts. The HTTP breaker counts 5xx, 408, 429, timeouts, and connection errors. A 400 or a 404 is the caller’s problem. It should never open a circuit.

Same slow provider, 200 orders, through the breaker path:

Breaker path, same slow providerMeasured
Orders sent200
Calls that reached the provider30
Rejected by an open circuit170
Latency per order, p50 / p95199 ms / 2,215 ms
Time to work through 200 orders13.3 s
Function App instances that answered4

The breaker stopped 85 percent of the calls. A rejected order came back in 199 ms, as fast as a healthy one. Five times the orders took a third of the time of the naive run. The p95 of 2.2 seconds is the price of learning: the 30 calls that ran into the attempt timeout before the circuits opened.

One breaker per instance

Look at the last row. The breaker lives in one process’s memory. Flex Consumption scales out under load, and every new instance starts with a closed circuit. Each instance has to learn about the outage on its own. In my run, four instances answered, and together they let 30 calls through before all four circuits were open.

Every response from the sample carries an instance id and the breaker state of that instance. Under load, you see both change from call to call. With N instances, the provider receives up to N times the calls you planned for, and N probes when the break ends. That is fine for most systems. Still, you should know it before you promise the payment team that “the breaker protects you”.

The circuit breaker pattern at the gateway

API Management moves the breaker out of the app. A backend resource carries the rule:

circuitBreaker: {
rules: [
{
name: 'paymentBreaker'
failureCondition: {
count: 5
interval: 'PT10S'
statusCodeRanges: [ { min: 500, max: 599 } ]
}
tripDuration: 'PT15S'
acceptRetryAfter: false
}
]
}

While the circuit is tripped, the gateway answers 503 itself, and the backend receives nothing. Every consumer of the API gets the protection, in any language, without a library. That is the appeal.

The limits are worth reading before you rely on it:

  • There is no half-open state. After the trip duration, the full load returns at once. If the provider is still down, failures must add up again before the circuit trips again.
  • A backend takes one rule.
  • Gateway instances do not synchronize. Each applies the rule to what it has seen, so tripping is approximate.
  • The Consumption tier does not support it.
  • A 503 from the gateway looks like a 503 from the backend. The sample tells them apart with a marker header on the stub’s responses.
Gateway path, provider downMeasured
Orders sent200
Calls that reached the provider8
Answered by the gateway with 503192
Latency per order, p50 / p95198 ms / 227 ms

The rule says five failures. Eight calls got through because eight were in flight when the fifth failure was counted. That is what approximate means in practice. The burst took 5.1 seconds, shorter than the trip duration, so the circuit tripped once.

In-process or gateway? I use both for different reasons. The in-process breaker protects the caller: its threads, its memory, its latency. The gateway breaker protects the backend and every client you do not control. Neither one protects the order.

The breaker opens, the order still exists

At this point the provider is safe and the callers fail fast. The customer still gets an error. In paths 1 to 3 the order ends as PaymentFailed, and the best the API can do is a 503 with a Retry-After header.

For a payment, there is a better answer. Accept the order. Park the payment. Tell the customer the truth.

[DIAGRAM 3: images/fallback-flow.png] Alt text: The fallback flow of the circuit breaker pattern when the payment service is down Caption: The breaker decides when to stop calling. The fallback decides what happens to the order.

In the fallback path, a rejected or failed charge puts a message on a Service Bus queue. The order becomes PaymentPending and the API answers 202. A Service Bus triggered function settles the payment later, through the same breaker.

I took the provider down, placed 100 orders, and brought the provider back.

Fallback pathMeasured
Orders accepted with 202 during the outage100 of 100
Latency per order, p50 / p95209 ms / 575 ms
Orders PaymentPending during the outage100
All 100 orders Paid after recovery11.3 s
Charges at the provider100, no duplicates

No order lost. No customer waiting. The provider received 29 failed calls before the four circuits opened, then nothing until it was healthy again. But the fallback brings three problems of its own, and the breaker makes one of them worse.

Fast failure burns the delivery count

A queue consumer that fails throws an exception. Service Bus then redelivers the message. During an outage, that normally takes a while, because each attempt waits for a timeout.

With an open breaker, each attempt fails without a single network call. The message returns at once, fails at once, and uses up the queue’s MaxDeliveryCount of 10 in about a second. The breaker that protects the provider drains the queue into the dead-letter queue. The provider recovers a minute later, and every parked payment is already dead.

20 parked payments, provider downConsumer throwsConsumer reschedules
Dead-lettered20 of 20, within 1.5 s0
Waiting in the queue during the outage020, scheduled
Orders after recovery20 still PaymentPending, forever20 Paid after 20.1 s

The fix is to stop treating “circuit open” as a failure of the message. The consumer sends a copy that becomes visible after the break duration, plus jitter, and completes the original:

var delay = wait + TimeSpan.FromMilliseconds(Random.Shared.Next(500, 3000));
// Send first, complete second. A crash in between produces a duplicate
// message, never a lost one.
await _sender.SendMessageAsync(NewPendingMessage(order, attempt + 1, "reschedule", delay), ct);
await actions.CompleteMessageAsync(message, ct);

After 20 attempts the function dead-letters the message on purpose, with a reason a human can read.

A timeout is not a failure

The two-second timeout tells you that you stopped waiting. It does not tell you what the provider did. In slow-success mode the stub charges the card after four seconds. The caller gave up after two.

So the order is PaymentPending and the money has already moved. When the settlement runs, it charges again. Unless every call carries an idempotency key. In the sample, the key is the order id, on the first attempt and on every later one.

Provider charges after 4 s, caller gives up after 2 sMeasured
Orders PaymentPending after the timeout8 of 8
Charges already made at that moment8
Later settlement attempts that found the charge16
Charges in the end8

Sixteen times the settlement tried to charge an order that was already paid. Sixteen times the key said no.

Without the key, the fallback turns an outage into double charges. I would rather have the outage. I covered the consumer side of this in Idempotent Consumers on Azure.

Two writes, one gap

The API saves the order as pending and then sends the queue message. Those are two operations. A crash between them leaves a pending order with no message behind it. The sample marks the spot in a comment and leaves it open. Production code closes it with a transactional outbox.

Recovery is slower than the outage

One more measurement. After the provider is healthy again, how long does a caller keep getting errors?

After the provider recoveredMeasured
First paid order14.8 s later
Orders rejected while the provider was healthy12
Break duration15 s

A breaker cannot see recovery. It can only wait and probe. The break duration is a trade-off: short means more probes against a struggling service; long means rejected customers after it is fine. Pick the number with the team that owns the dependency, and alert on every transition. The sample logs one line each time a circuit opens, half-opens, or closes, with the instance id. The KQL is in docs/queries.kql.

Where this is the wrong answer

The circuit breaker pattern isn’t free, and it doesn’t fit everywhere.

  • Low traffic. A ratio over ten calls is noise. If the dependency sees a handful of calls a minute, a timeout and a retry with backoff do the job.
  • A fallback that lies. Parking a payment works because a payment can happen later. A stock check, a fraud decision, or a price cannot. If there is no honest “later”, fail fast and say so.
  • One breaker for everything. A breaker per dependency, and per tenant or region where they fail apart. A shared breaker lets one bad endpoint cut off the healthy ones.
  • Retries on top. A retry inside the breaker multiplies load at the worst moment. Three retries on every call turn a struggling provider into a dead one before the circuit opens. Keep retry counts low and budgets tight.
  • Non-transient errors. A wrong API key fails every call. The breaker opens, half-opens, opens again, forever. That needs an alert, not a pattern.

Wrapping up

The three states are the easy part of the circuit breaker pattern. A library gives you them in ten lines, and API Management gives you two of them in a Bicep block.

The work is around the breaker. A timeout, so slow counts as failed. A threshold that is a ratio. The knowledge that every instance has its own circuit. And above all, a decision about the thing the customer asked for. In my sample, that decision is a queue, a delayed retry, and an idempotency key.

The breaker opens. The order still exists. Decide what happens to it before the outage does.

The code, the Bicep, and the test script are in the circuit-breaker-azure repository.

Building Scalable Solutions on Azure: The Services Are the Easy Part

Modern applications need more than good code. They need scalability, security, reliability, and efficient service communication. Building scalable solutions on Azure starts with a familiar list of services: Front Door at the edge, App Service and Functions for compute, Service Bus between them, Azure SQL, PostgreSQL, and Blob Storage underneath, with Monitor and Application Insights watching.

I draw that architecture often. Five columns, a dozen icons, arrows pointing right. It is a good starting point, and I would pick most of those services again for a mid-sized transactional system. But the drawing has a problem I only see once I build it: every arrow is a happy path. Nothing on it fails, nothing retries, nothing arrives twice, and nothing explains who may talk to whom.

So this time I built it, with the official Azure icons for the pictures and azd up for the rest, and then added the parts the drawing leaves out. Choosing the services is the easy part. Designing reliable communication, handling failures, monitoring performance, and securing every layer is where the work is. The code is in the companion repo.

The services are the easy part of scalable solutions on Azure

One concrete workload sits behind the picture. A client posts an order. The API on App Service stores it in Azure SQL. A message goes over Service Bus. A Function writes a metering row to PostgreSQL. Another Function writes a CSV report to Blob Storage. Front Door sits in front, Application Insights collects telemetry.

The sample does exactly that, a reference implementation of scalable solutions on Azure in one repo: a .NET 8 minimal API on App Service, a .NET 8 isolated Functions app on Flex Consumption, Service Bus Standard, Azure SQL serverless, PostgreSQL Flexible Server, one storage account. Nothing exotic, and all of it deploys from one Bicep file.

What the picture cannot show is what sits between the boxes. That is where “reliable communication” and “handling failures” live, and that is what the rest of this post is about.

What the arrows hide in scalable solutions on Azure

The API never talks to Service Bus

The obvious implementation of “App Service, then Service Bus, then Functions” is: API saves the order, API sends a message. Two writes, two systems, no transaction across them. If the message send fails after the SQL commit, you have an order nobody processes. A crash between the two gives the same result. And when the SQL commit fails after the send, you have a message for an order that does not exist.

The sample uses a transactional outbox instead. POST /api/orders writes the order row and an outbox row in one SQL transaction and returns 202. A timer-triggered Function, OutboxRelay, claims pending outbox rows every ten seconds with UPDLOCK, READPAST and publishes them. The API has no role assignment on Service Bus at all. A messaging outage costs latency, not orders. You can see it in the Bicep: the API identity gets Key Vault Secrets User and nothing else.

The price is ten seconds of lag and a second hop in the trace, which brings me to the next point. If you are still choosing between Service Bus, Event Grid and Event Hubs for this hop, covers that decision.

A timer breaks the trace

Application Insights correlates an HTTP request with the Service Bus send and the triggered Function through the W3C traceparent, carried in the message as Diagnostic-Id. That works when the API sends the message. With an outbox and a timer, the message is sent from a different process with a different operation id, and the order’s story splits in two.

The fix is small. The outbox row stores Activity.Current?.Id from the HTTP request. The relay copies it into the message’s Diagnostic-Id application property. One operation id then spans the POST, the relay, the queue, and ProcessOrder. Query 1 in measure/queries.kql shows the whole chain.

At-least-once means duplicates

Service Bus delivers a message at least once. A handler that times out, a lock that expires, a scale-out at the wrong moment: all of them produce a second delivery. “Reliable asynchronous communication” means repeated, not exactly once.

The sample catches duplicates in three places, each for a different reason:

  • At the API, an Idempotency-Key header is required and backed by a unique index. A client that retries a POST gets the same order back with HTTP 200 instead of a second order with 202.
  • On the queue, duplicate detection is on with a ten-minute window, and the relay sets MessageId to the outbox id. If the relay crashes between sending and marking the row as published, the resend is dropped by Service Bus.
  • In PostgreSQL, the table has a primary key on order_id and the insert uses ON CONFLICT DO NOTHING. A redelivered message writes nothing and logs a warning.

None of the three covers the other two. Remove any one of them, and there is a path to a duplicate metering row.

Failures need a destination and a reader

Two SKUs in the sample exist only to fail. FLAKY-1 throws on the first two deliveries and succeeds on the third. POISON-1 throws every time. The queue has MaxDeliveryCount set to three, so the poison order lands in the dead-letter queue after three attempts.

A dead-letter queue that nobody reads is a failure that nobody sees. So the sample has two readers. DeadLetterMonitor is a Function on orders/$DeadLetterQueue that writes a FailedOrders row in SQL and flips the order status to Failed, so the console shows it. And a metric alert on DeadletteredMessages > 0 for the orders entity emails the action group. The Function gives you the record; the alert gives you the interrupt. You want both.

The queue overview after the run makes the point for me: the dead-letter count reads zero, because the Function drained it within seconds. Without the alert, the only evidence would be the FailedOrders row. The same blade shows 111 incoming messages against 124 outgoing; the 13 extra deliveries are the retries, the flaky and poison orders and the dead-letter receive, visible in a platform metric before you write a line of KQL.

Front Door is only a shield if the origin refuses everything else

Front Door brings global load balancing, DDoS protection, and a WAF. All true, and all irrelevant if app-xyz.azurewebsites.net still answers directly. Then the WAF rules, the rate limit, and the TLS policy are optional for anyone who finds the origin hostname, which takes one DNS lookup.

The sample locks the origin: the App Service access restriction admits the AzureFrontDoor.Backend service tag only when the request carries the X-Azure-FDID header of this specific Front Door profile, and the default action is Deny. The API checks the header a second time in middleware, because an access restriction that someone relaxes during an incident is the kind of mistake that surfaces months later.

Front Door Standard carries custom WAF rules and rate limiting. The sample has two: 300 requests per minute per client on /api/, and a block on POSTs that are not application/json. The managed OWASP rule set and bot protection need Premium, which costs roughly ten times the Standard base price. For a demo, Standard. For a public API, do the Premium maths before you decide.

Secrets in scalable solutions on Azure: zero, except one

Service Bus has local auth disabled. The storage account has shared key access disabled. Azure SQL is Entra-only, with the API’s managed identity as the server administrator; the API creates the Worker’s contained database user at startup, so no human ever holds a SQL login. The API runs on a system-assigned identity, the Worker on a user-assigned one (the reason is in the first-run section below), and the role assignments in infra/modules/roles.bicep are the complete list of who may touch what. It is the same stance I took in the Azure Functions MCP server post: access is not authority, and the role list is the authority.

The one exception is PostgreSQL. Flexible Server supports Entra authentication, but creating the managed identity’s role requires a pgaadauth_create_principal call from a session that is already authenticated as the Entra admin, which means a psql round trip in the deployment. I did not want a deployment step that depends on a local psql. So the sample generates a password once in the preprovision hook, Bicep stores it in Key Vault, and both apps read it through a Key Vault reference. It is a secret, it is stored once, and it never appears in an app setting in clear text. It is also the one line in this repo I would change first in a real system.

Where this is the wrong answer

Not every workload needs this much machinery, and three parts of these scalable solutions on Azure deserve a second look before you copy them.

Two databases. The architecture puts relational data in Azure SQL and metering data in PostgreSQL, and the sample follows it so you can see the cost. Two engines means two connection patterns, two auth models, two sets of backups and, in this sample, two schema bootstrap paths. If there is no reason for the split other than habit, use one. The sample would lose nothing by putting metering_events in Azure SQL.

Front Door for a single-region app. The sample runs in one region. Front Door adds a global anycast edge, a WAF, and a fixed monthly fee of around 35 dollars before traffic. If the users are in one country and the app is in one region, Application Gateway or even App Service’s own access restrictions plus a WAF-less setup may be the better trade. Front Door earns its place when you have more than one origin or more than one continent.

An outbox when the write is not valuable. The outbox buys you “no accepted order is ever lost” at the cost of a relay and a ten-second delay. For a telemetry ping or a cache invalidation, send the message directly and accept the occasional loss.

What the first run against Azure taught me

The measured run

The measured run, python measure/drive.py all against swedencentral through the Front Door endpoint:

  • POST /api/orders through Front Door: 955 to 1,234 ms p50 and 1,712 ms p95 once warm. The very first call took 6.8 s, which is Azure SQL serverless resuming from auto-pause. The free offer pays for itself with that one number.
  • Happy path: Accepted to Metered in 9.0 s, one delivery. Roughly half of that is waiting for the ten-second relay timer.
  • Duplicate submit: first POST 202, second POST with the same Idempotency-Key 200, same order id. One row, one message.
  • Flaky order: Metered on delivery 3 after 6.4 s. Service Bus redelivers an abandoned message immediately, so two failures and a success fit inside one lock duration.
  • Poison order: Failed after 10.2 s. The dead-letter message reports DeliveryCount 4 against a MaxDeliveryCount of 3, because the count includes the receive from the dead-letter queue itself. If you alert on that number, know what it counts.
  • Burst of 50: all accepted in 6.8 s, 48 Metered after 50 s, all 50 after 97 s. The relay claims 50 rows every ten seconds, and the handler runs eight at a time; both are settings, not ceilings.
  • Report: one CSV in Blob Storage with two SKU rows, the run recorded in PostgreSQL.

Four things that broke first

Four things broke before any of that worked, and each one is a sentence an architecture drawing has no room for:

  1. InvariantGlobalization=true in the API project. It shrinks the container image and Microsoft.Data.SqlClient refuses to open a connection under it. The first deploy failed at the first SQL call.
  2. CREATE USER ... FROM EXTERNAL PROVIDER for the Worker’s identity. Azure SQL can only resolve that name if the server has its own managed identity with Directory Readers in Entra, a tenant-admin step I did not want inside azd up. The way around is to create the user by SID: CREATE USER [name] WITH SID = 0x<clientId as 16 bytes>, TYPE = E. That needs the identity’s client id, which Bicep only exposes for a user-assigned identity. So the Worker got one.
  3. Key Vault references on a user-assigned identity. After the switch, the Worker still received the literal @Microsoft.KeyVault(...) string as its PostgreSQL password and failed every order with 28P01. App Service resolves references with the system identity unless keyVaultReferenceIdentity points at the user-assigned one. The API, still on a system identity, never noticed.
  4. The azd environment name went into every resource name, and my own Bicep capped it at twelve characters. Resource names have limits; take the first twelve and move on.

Closing

The services on the drawing are the right ones, and picking them took five minutes. Reliability is an outbox, an idempotency key, a dead-letter reader, and an alert. Security is an origin that refuses direct traffic and role assignments short enough to read. Monitoring is one operation id that survives a timer. None of those are services you pick from a catalog. They are decisions you make between the boxes, and they are the part of “scalable solutions on Azure” that no icon set can draw for you.

The repo is at github.com/steefjan1/scalable-solutions-azure. azd up, run measure/drive.py, break it in your own way, and azd down before the Front Door line shows up on the invoice.

Sources

Zero Trust on Azure

Your network can be hardened end to end and still sit one compromised account away from a breach. That sentence is the whole case for Zero Trust, and it explains why the generic Zero Trust architecture picture keeps circulating. Users and devices at the top, an identity provider, MFA, a policy engine, a policy enforcement point, segmentation, protected resources, and a monitoring column on the side. Never trust, always verify, least privilege. This post is about Zero Trust on Azure: which Microsoft service does each job, and where the neat boxes stop matching how the platform behaves.

I like the generic picture. It is the NIST SP 800-207 model with icons, and it summarizes a modern access path fairly. It does not tell you what to switch on in an Azure tenant, though. So I redrew it with Azure icons, one service per box, and wrote down what I had to change to make it accurate.

Zero Trust on Azure: the generic architecture mapped to Microsoft Entra, Intune, Global Secure Access, Azure networking, and Microsoft Sentinel.

Zero Trust on Azure: the same spine, with names on it

The generic flow has eleven steps. Here is what each one is called in a Microsoft tenant.

Steps 1 to 6: identity and policy

  1. Verify users. Employees, admins, vendors and workloads are all Microsoft Entra ID identities. Vendors come in through External ID (B2B), and workloads through app registrations and managed identities. That last group matters more than the picture suggests, and I will come back to it.
  2. Check devices. Device trust is an Intune compliance policy plus a Defender for Endpoint risk score, which Entra receives as a device claim. Patch status, encryption, OS health and firewall state are compliance checks, not network checks.
  3. Verify identity. One identity provider: Entra ID. In a hybrid tenant, Connect Sync or Cloud Sync brings in the on-premises accounts, and the Active Directory authority boundary stays where it was.
  4. Strengthen authentication. MFA, authentication strengths, passkeys and FIDO2 are Entra features. The policy that demands them lives in the next box.
  5. Evaluate access. Conditional Access takes the signals: user, group, device compliance, location, sign-in risk and user risk, client app, and the sensitivity of the target app.
  6. Make policy decisions. Also, Conditional Access. Grant, block, require MFA, require a compliant device, require an authentication strength, or apply session controls.

Steps 7 to 11: enforcement, isolation and visibility

  1. Enforce access. This is where the picture and the platform part ways. More below. The candidates are Global Secure Access, Front Door and Application Gateway with WAF, API Management validate-jwt, the application itself, and Bastion.
  2. Isolate workloads. Virtual networks, network security groups, application security groups, Azure Firewall, private endpoints, and private DNS.
  3. Protect resources. App Service, Functions, API Management, Azure SQL, Storage, Key Vault, and for the Active Directory box, Entra Domain Services or domain controllers behind Entra Private Access.
  4. Monitor continuously. Microsoft Sentinel for SIEM and SOAR, Defender for Cloud for posture and workload protection, ID Protection for risky sign-ins and users, Log Analytics for everything the rest emits.
  5. Build the foundation. Key Vault and customer managed keys, Purview labels and DLP, managed identities, Azure Policy, PIM, backup, and a landing zone you segment before the first workload lands.

That mapping is useful on its own. Architecture reviews ask me for it regularly, usually from someone with the generic picture, asking, “so what do we actually buy?” But three of the boxes hide something, and that’s why I’m writing this post.

Policy engine and policy administrator share one box

NIST 800-207 separates the policy engine (decides) from the policy administrator (tells the enforcement point what it decided). The generic picture keeps them apart and gives the administrator its own job list: create a secure session, issue an access token, enforce policy decisions, monitor the session, log and audit.

Zero Trust on Azure does not split them into two services. Conditional Access is Microsoft’s policy engine, and the token service that acts on its verdict is the same Entra ID. The decision and the administration happen in one evaluation at token issuance. There is no separate component you can point at and call the PA.

That collapse is convenient, and it has a cost. Because the decision binds to token issuance, the decision also binds to token lifetime. Which brings me to the enforcement point.

The enforcement point in Zero Trust on Azure is not one gateway

The picture draws a single Policy Enforcement Point, a ZTNA gateway or reverse proxy, and lists four jobs for it: verify every request, decrypt and inspect traffic, enforce least privilege, block unauthorized access.

On Azure, I count at least six places that do some of that for some traffic, and none of them does all of it for all traffic.

  • Entra ID itself, at token issuance. Conditional Access enforces here, and for most SaaS and Microsoft 365 traffic this is the only enforcement point there is.
  • Global Secure Access, the ZTNA layer. Private Access fronts internal apps and, since January 2026, domain controllers, so Kerberos traffic can finally sit behind a Conditional Access policy. Internet Access is the secure web gateway. TLS inspection for it is still in preview as I write this, so “decrypt and inspect traffic” is a roadmap item for part of the stack, not a given.
  • Front Door and Application Gateway, with WAF policies, for public web entry points.
  • API Management, where validate-jwt checks the token the app will later trust.
  • The application, which validates the token again and applies its own authorization. Microsoft’s own guidance says Conditional Access “doesn’t prevent the app from blocking access on its own”. The app is an enforcement point whether you designed it that way or not.
  • Bastion, for the administrative sessions that never pass through any of the above.

The generic picture is not wrong to draw one box. It is wrong if you read it as one product. Every Zero Trust review I have done ended with a table of enforcement points and the traffic each one does not see. The gaps in that table are the architecture.

“Verify every request” means “verify every token issuance”

This is the part I most wanted to write down, because it surprises people when they measure it.

Entra evaluates Conditional Access when it issues a token. Access tokens live 60 to 90 minutes by default. Between issuances, the resource trusts the token, and a policy change, a password reset, a disabled account, or a risk event does nothing to a token already in use. “Verify every request” at the resource means “check the signature and expiry of a token that Entra verified up to an hour and a half ago”.

Continuous Access Evaluation closes that gap, but only for resources and clients that support it. In my earlier post, Microsoft Entra ID under the hood, I measured this on a test tenant. A CAE-aware client received a 1439-minute token, and the resource rejected it four seconds after I revoked its sessions. The non-CAE client next to it kept a 65-minute token and kept receiving 200 responses until it expired. Same tenant, same policy, same user. The only difference was whether the client and resource spoke CAE.

So the “Revoke” decision in the picture’s policy engine box is real, but it depends on the plumbing. For your own APIs on App Service, Functions, or API Management, CAE does nothing unless you build the claims challenge handling yourself. The honest version of the diagram puts a footnote under Revoke, and that is what mine does.

Where this Zero Trust on Azure mapping is the wrong answer

  • If most of your estate is not on Azure. Conditional Access and Global Secure Access still apply to a mixed estate, but the segmentation and protected resources rows are Azure-specific. For AWS or on-premises workloads, Entra Private Access gives you an enforcement point in front of them, not segmentation behind them.
  • If you have no Intune. Device compliance is the second strongest signal Conditional Access has. Without a device management platform feeding it, “check devices” collapses to “is the device Entra joined”, a weaker test than the picture implies.
  • If you are on Entra ID Free or P1 only. Sign-in risk and user risk conditions need P2. Global Secure Access needs the Entra Suite or standalone licenses. The mapping above assumes you have them, and many tenants do not.
  • If your apps cannot validate tokens. Legacy applications behind an App Proxy or Private Access get an enforcement point in front of them and nothing inside them. That is still better than nothing, and it is not Zero Trust at the application layer.
  • If nobody reads Sentinel. The monitoring column feeds risk back into policy only if someone tunes analytics rules and acts on the incidents. A workspace that ingests everything and alerts no one is a cost, not a control.

The question at the bottom of the picture

The generic post ends with a good question: if an attacker compromised one employee’s account today, how much of your network could they reach?

On Azure, the answer comes from five smaller questions. Does the compromised identity hold standing privileged roles, or does PIM activate them with a window? Does Conditional Access require a compliant device, so a stolen credential on an unmanaged laptop stops at step five? Do the resources sit on private endpoints, behind network security groups that only admit the subnet that should talk to them? Do the workloads that matter speak CAE, so a revoke lands in seconds rather than at the next token expiry? And can Sentinel tell you any of this happened before the attacker finishes?

I have not yet met a tenant where all five answers were yes. The mapping in this post is how I find out which ones are no.

Zero Trust is not a product you install. Zero Trust on Azure is about fifteen services configured to agree with each other, and the diagram only becomes true once they do. If you want the same treatment for the identity layer alone, Microsoft Entra ID goes deeper under the hood, and the API Management for AI workloads series covers the validate-jwt enforcement point in detail.

API Design Patterns with Azure

Your API works on the happy path. The interesting part starts when a request times out, a client retries, or a dependency goes down. So I looked at various common API design patterns: RESTful resources, versioning, pagination, consistent errors, idempotency keys, conditional requests, rate limiting, async request-reply, API gateway, webhooks, circuit breaker, and aggregation. Moreover, I wanted to see how they behave on Azure, so I built all in one repo and wrote four implementations of idempotency keys. Three of them pass the test most teams write. One of them is correct. Then I ran all four against the deployed app and counted the charges.

The code is on GitHub: steefjan1/api-design-patterns-azure.

Twelve patterns, three kinds of decision

The sample runs Azure API Management (BasicV2) in front of one Azure Functions app on Flex Consumption (.NET 8 isolated), with Table Storage and Storage queues behind it. Managed identity everywhere, no storage keys.

Placing each pattern on the diagram sorts the list into three groups:

GroupPatternsThe question it answers
Contract01 resources, 02 versioning, 03 pagination, 04 errors, 06 conditional requestsWhat can the client rely on?
Retries and time05 idempotency, 08 async request-reply, 10 webhooksWhat happens when one request outlives one round trip?
Capacity and failure07 rate limiting, 09 gateway, 11 circuit breaker, 12 aggregationWhere do we say no, or answer with less?

The gateway commenter is right. In the repo, rate limiting (07) is one rate-limit-by-key policy on the gateway (09), keyed on the APIM subscription. The same policy file renders the gateway’s 429 as application/problem+json (04), so a client parses a throttled request exactly like a validation error from the function. A pattern list draws these as separate boxes. In a deployment, they are one policy.

One measured caveat: 70 simultaneous calls against a limit of 60 per minute let 69 through and throttled one, with Retry-After: 9. The gateway’s counters are synchronized asynchronously, so a burst overshoots before the limit bites. Treat a gateway rate limit as capacity protection, not as an exact quota.

The behavior-first commenter is right too, and the repo shows why. Look at what the “retries and time” patterns do underneath. The idempotency store claims a key with an insert that fails if the row exists. The webhook inbox dedups webhook-id with the same insert. The PATCH handler rejects lost updates with a compare-and-swap on the ETag, and so does the idempotency store when it completes a claim. Twelve names, two primitives: insert-if-absent and compare-and-swap. Table Storage gives you both (AddEntity, and UpdateEntity with an ETag). So do Cosmos DB, SQL Server, and Redis.

The timeout that tells you nothing

A payment call times out. Did it succeed? As one commenter wrote, a timeout tells you almost nothing. You retry because you think it failed, and later you find out the first payment went through too.

Idempotency keys fix this by turning “do it again” into “give me the result of the first one”. The client sends Idempotency-Key: K and reuses K on every retry of that operation. The server remembers K and replays the stored response. That description fits on a slide. The bugs live in the three things it does not say.

Three ways to implement idempotency keys without the semantics

The check is racy. The handler reads the store (“have I seen K?”), finds nothing, charges, then saves K. Two retries that arrive within the same 400 milliseconds both read nothing and both charge. Both callers get a 201.

The key is scoped to the endpoint. The sample exposes the same payment through POST /payments and POST /orders/{id}/pay. If the key is stored as route plus K, a retry through the second route is new work. This is what you get from middleware that keys on the request path, or from one key table per service.

The result is not durable. The claim sits in Table Storage; the response sits in process memory or in a cache with eviction. After a restart, or when the retry lands on another instance, the key exists, and the response does not. The handler answers “already processed” without a payment id. The client is back to the timeout problem, and its likely next move is a new key.

The fourth implementation does three things differently:

// 1. Claim the key atomically. Exactly one concurrent caller gets an ETag back.
var claim = new IdempotencyRecord(scope, key, Pending, fingerprint, now.Add(lease));
var etag = await store.TryInsertAsync(claim, ct); // AddEntity: 409 if it exists
// 2. Pass the key downstream. Every retry asks the provider for the same charge.
var receipt = await provider.ChargeAsync(command, ChargeIdFor(scope, key), ct);
// 3. Store the response durably, only if we still own the claim.
await store.TryReplaceAsync(claim with { Status = Completed, ResponseBody = body }, etag, ct);

When the insert fails, the handler reads the row and decides. A different payload under the same key is a 422. A completed claim is a replay with Idempotent-Replayed: true. A pending claim within its lease is a 409 with Retry-After: 1. An expired lease is taken over with a conditional update. The scope is the caller plus the key, and behind the gateway the caller comes from the APIM subscription, not from a header the client picked.

Step 2 is the one most write-ups skip. If the provider charged the card and the answer got lost, the handler releases its claim and returns 503. The client retries with the same key, the handler runs again, and the provider recognizes the charge id. Without a key that travels downstream, the most careful upstream store still double charges on that path. The racy version fails it for exactly that reason.

Why the tests stay green

The usual test sends the same request three times, one after another, and asserts one charge. All four implementations pass it. Each broken one fails a condition the sequential test never creates: concurrency, a second route, a restart, a lost reply. The xUnit project asserts those failures on purpose, so the evidence stays in the build.

scripts/race.ps1 runs the same twenty cells against the deployed app and reads the ledger. On Azure, the matrix came out exactly as predicted. The one number worth quoting: a burst of twenty identical requests with one key made the racy version charge the card 16 times, and all twenty callers received a 201.

Building the race script produced its own example. Windows PowerShell 5.1 runs on .NET Framework, which allows two connections per host by default. A burst of twenty requests quietly becomes ten pairs, the race window never opens, and the racy implementation looks fine. One line, ServicePointManager.DefaultConnectionLimit = 64, separates a passing test from a real one. In-process tests have the same trap in another form: a lock around a dictionary works on one instance, and Flex Consumption can run the app on forty.

What idempotency keys do not solve

Idempotency keys make retries safe for one operation. They leave three gaps; the sample names in code comments:

  • The response must fit. A table property holds 64 KiB. Large responses go to Blob Storage with a pointer in the row.
  • Side effects after the claim are still two writes. The sample enqueues a payment. captured webhook after storing the response. A crash between those writes loses the event. A transactional outbox closes that gap.
  • Per-instance state stays per instance. The in-code circuit breaker learns about an outage once per instance. In the demo it rejected calls in about 40 ms once open, against about 150 ms per failing call before. The APIM backend breaker sees the whole app but trips for every route. Neither is wrong; pick per dependency.

Where this is the wrong answer

Not every write needs an Idempotency-Key header.

  • PUT and DELETE are idempotent by definition. The sample’s DELETE answers 204 twice. Use conditional requests (If-Match) for lost updates instead.
  • If the business already has a natural unique id, use it. A unique constraint on “one payment per order” is simpler and stronger than a generic key store.
  • For long-running, multi-step work, Durable Functions already gives you instance ids, replay and the 202 status shape of pattern 08.
  • If your payment provider does not accept an idempotency key, no upstream design gives you exactly-once charging. Reconcile against the provider’s ledger and make that part of the design.

Try it

azd up # Functions, Storage, APIM BasicV2 in swedencentral; postdeploy seeds data
dotnet test # the failure matrix, no Azure needed
./scripts/race.ps1 # the same matrix against Azure, counted on the ledger
./scripts/demo.ps1 # all twelve patterns: status codes and headers
azd down --purge # APIM BasicV2 bills by the hour

One deploy lesson for free: the seed function first lived on admin/seed. The Functions host reserves routes that start with admin for its own API. The function still appears in az functionapp function list, and every call returns an empty 404. It now lives on ops/seed.

Conclusion

The list was right that idempotency keys matter. The comment was right about why: the key is the easy part. The atomic claim, the scope, the durable result and the key that travels downstream are the pattern. Test those under concurrency, or the green build is telling you about a different system than the one in production.

When Agentic Workloads Break the PaaS Assumptions

This series started with a map and grew into seven pieces. Five layers came first: compute, where load shape picks the service; messaging and orchestration, where two questions replace four product choices; data patterns, where idempotency and the outbox keep a platform correct; governance and identity, where policy and audit become the compliance posture; and observability and FinOps, where behaviour and cost become visible. Then came the lens: from design to demonstrable operation, the shift from “is it built?” to “can we operate it responsibly?”

Every one of those pieces rests on a shared assumption. The system does what you told it to do. You wrote the workflow, you defined the routes, you set the policies, and the platform executes them. That assumption has held for every integration platform I’ve built. Agentic workloads break it. So this capstone asks what changes when the thing making decisions inside your platform is a model, not your code, and why each layer, plus the readiness lens itself, deserves a second look because of it.

The assumption agentic workloads break

Conventional integration is deterministic. A message arrives, a workflow runs its defined steps, a router sends it where the rules say. You can read the code and know what will happen. You can test every path. When something fails, you trace it to a step you wrote.

Agentic workloads replace part of that determinism with a model that decides at runtime. The agent reads context, picks a tool, interprets the result, and chooses the next action. Moreover, it does so differently depending on inputs you didn’t fully anticipate. That’s the point of it: the flexibility is the feature. But it means you can no longer read the code and know what will happen. So the ground under every layer shifts: behavior is no longer exactly what you specified.

None of this argues against agentic workloads. It argues for revisiting each layer with the shift named explicitly. Let’s do that.

Compute: the loop changes the shape of the work

The compute layer sorted workloads by load shape: steady request traffic to App Service, event-driven bursts to Functions or Container Apps. Agentic workloads add a shape that sorting didn’t account for: the loop.

An agent doesn’t process a request and return. It reasons, calls a tool, waits, observes, and reasons again, sometimes for many cycles, before it finishes. That’s neither a clean request-response nor a discrete event. Instead, it’s a long-running loop of unpredictable duration with external calls in the middle. So the compute question changes. You’re no longer asking “steady or bursty” alone. You’re asking how to host something that runs for seconds or minutes, holds state across tool calls, and scales on a dimension concurrent reasoning loops that CPU-and-memory autoscale captures poorly. Container Apps with event-driven scaling often fit better here than App Service, and the orchestration frequently belongs in a workflow engine rather than raw compute.

Messaging and orchestration: the agent is a non-deterministic router

The messaging layer drew a clean line. Deterministic routing rules sent messages where the logic dictated. An agent orchestrating tool calls is, in effect, a router too, but a non-deterministic one. It decides which tool to call from its reading of the context, not from a rule you wrote.

The reliability consequences are real. Delivery guarantees still matter; an agent that triggers a business action still needs that action to occur exactly once, so Service Bus and the idempotency store in the data layer remain as relevant as ever. What changes is predictability. You can’t fully anticipate which actions the agent will trigger, or in what order. Therefore, the orchestration has to stay correct under sequences you didn’t design for. One practical lesson from building these loops applies directly: agent outputs rarely arrive as the clean structures a deterministic step would emit, so you build explicit bridges between agent actions rather than assuming shape.

Data: state and correctness under non-determinism

The data patterns held a platform correct when systems it didn’t control misbehaved. Agentic workloads make those patterns more necessary, not less, and they add one more.

Idempotency matters more because an agent may retry a tool call or repeat an action as it reasons, so the dedup store carries a heavier load. The outbox matters just as much, because an agent-triggered write still has to propagate reliably. Workflow state matters more too, since the reasoning loop is exactly the kind of long-running, restart-surviving process that needs durable state and a correlation ID. And then the new one: conversation and context state. An agent carries context across turns, and that context has to live somewhere durable and queryable, which explains why a flexible document store keeps showing up as the default for agentic conversation state. The access pattern points at the store. Same principle as the map, applied to a new kind of state.

Governance and identity: where the assumptions break hardest

This layer changes most, and I’d insist any integration architect think it through before shipping an agentic workload.

The governance layer secured a deterministic platform. Identity answered who the caller was; policy constrained what the platform could be. Both still matter. However, agentic workloads open a gap that neither fully closes. Identity secures who the agent is. It does not touch what a poisoned tool result or a manipulated retrieved document makes the agent do. Prompt injection rides in through the data the agent requested inside the reasoning loop, downstream of the perimeter check everyone assumes protects them.

So the governance layer needs additions a deterministic platform never required:

  • Authorization moves per-action: A validated identity at the edge isn’t enough. Each tool call the agent makes needs its own check: is this specific action allowed for this tenant right now? The perimeter check happens once; the risk recurs on every call inside the loop.
  • Recovery means compensation, not retry: Agent actions have side effects across systems. A failed sequence three actions deep can’t restart from the top; it needs compensating actions to undo what already happened. That’s saga-style thinking, and you design it; it doesn’t emerge.
  • Containment has to be possible: When an agent misbehaves, you stop it fast, and at more than one layer. Layered containment, from a single configuration flip-up to a full block, turns “contain the agent” from an incident-call debate into a seconds-long operation.
  • Evaluation becomes a first-class layer: Operational observability tells you the agent is running. It doesn’t tell you the agent’s outputs are quietly degrading. Under the EU AI Act’s oversight and transparency duties, that stops being optional polish and becomes evidence you’re meeting an obligation.

The readiness lens, asked again

The design-to-operation post posed the question that decides go-live: not “is it built?” but “can we operate it safely, recoverably, auditably, and predictably?” Agentic workloads sharpen every word of that sentence.

Safely now includes per-action authorization and containment, because the threat walks in as data. Recoverably now means compensation and sagas, because retry alone can’t undo side effects. Auditably now covers what the agent accessed, which tool it called, why it acted, and what policy constrained it evidence the EU AI Act increasingly expects. And predictably is precisely the property the agent gave up, which is why the surrounding architecture has to supply it instead. The production baseline, the demonstrable-versus-designed test, the three moments of readiness all of it still applies. Each bar sits higher.

The revised framework

The map closes with five questions. For agentic workloads, they hold, and each gains a harder edge. Before an agentic workload goes near a real system, I’d add these:

Can I host a long-running reasoning loop, not just a request or an event? Can my orchestration stay correct when I can’t predict the action sequence? Does my data layer hold conversation state as well as business state, with idempotency doing heavier duty? Is authorisation per-action, not just per-identity? Can I contain a misbehaving agent in seconds? And can I evidence what the agent did, why, and whether its quality held?

Those aren’t different questions from the series. They’re the same layers, asked again under non-determinism, and then held up against the readiness lens one more time.

The shape of it

Agentic workloads don’t replace the Azure PaaS foundation an integration architect builds on. They stress it. Every layer in this series still includes compute, messaging, data, governance, and observability, but each one now supports a workload that decides for itself at runtime. The compute layer meets the loop. The messaging layer meets a non-deterministic router. The data layer meets conversation state and heavier idempotency. The governance layer meets a threat that walks in through the front door as data. And the readiness lens meets a workload that surrendered predictability, so the architecture has to supply it.

The through-line of the whole series holds here too. The model is the least differentiated part of a production agent. What separates a demo from something you can run against real systems in a regulated industry is the architecture around it: the same layers, asked harder, and proven in operation rather than promised in design. So the foundation was never wasted. It’s exactly what agentic workloads need, applied with the assumptions made explicit.

That’s the series. Start at the Azure PaaS map for the layer-by-layer foundation, take the design-to-operation lens with you as the test, and come back here for what changes when the workload thinks for itself.

Production Readiness: Closing the Execution Gap

Every post in this series so far has covered a layer: compute, messaging and orchestration, data patterns, governance and identity, observability and FinOps. This one isn’t a layer. It’s a question that cuts across all of them: when is the platform actually ready for production?

That question is harder than it looks, because “we built it” and “we can run it” are different claims. I’ve watched more than one integration platform pass every technical checkpoint and still fall short of production-ready, not because the design missed anything, but because nobody had turned that design into something enforceable, operable, and provable. So this post is about the gap between those two states, and how you close it. It’s the through-line under every layer, and it’s the thing that turns a strong architecture into a platform you can responsibly put load on.

The shift: from “is it built?” to “can we operate it?”

Here’s the single most useful reframe I know for this stage. Stop asking “is the platform technically built?” and start asking “can we operate it safely, recoverably, auditably, and predictably?”

Those are not the same question. The first is about whether the components exist and connect. The second is about whether, when something goes wrong at 2 am, someone can see what happened, understand it, recover from it, and prove afterward that they handled it correctly. A platform can pass the first test comfortably and fail the second completely. And the second test is the one that actually determines whether you should go live. So the moment you catch yourself saying “it works,” push on: does it work in a demo, or does it work under a failure you didn’t plan for?

The core move: make the implicit explicit

Most integration platforms at this stage share the same shape. The design is good, and someone has largely written it down. But a lot of what matters lives in documentation, in code that’s still evolving, or in the heads of the people who built it. That works fine while a small team builds the foundation. It stops working the moment the first real production use case lands, because implicit choices become whatever the first team happens to decide.

The fix is a production baseline: an explicit, enforceable statement of what production use demands. It names the mandatory components and patterns, pins down the environment profiles, fixes the security controls and monitoring standards, and settles the recovery agreements and release criteria. Its job is to pull those decisions out of documents and habits and into something the platform enforces, so the first production use case inherits the decisions rather than reinventing them.

Without that baseline, every early integration is free to make its own choices, and you accumulate inconsistency, technical debt, and a future re-platforming you didn’t budget for.

Design versus demonstrable: the recurring gap

The same gap shows up in every layer, and once you see it, you can’t unsee it. On security, the design names Zero Trust, least privilege, and pipeline-driven change, yet permanent broad access rights sit in the environment, quietly contradicting it. Observability design specifies OpenTelemetry and required fields, but the alert rules and dashboards never make it into the infrastructure. And the CI/CD design describes a full release chain with quality gates, while the pipelines really only cover the dev environment.

In each case the design is right and the demonstrable working is missing. That’s the pattern to hunt for when you assess readiness: not “did someone design this?” but “does the platform actually enforce this design somewhere it can prove?” Anything that lives only as intent is a gap, however good the intent.

What operational readiness actually covers

Technical function is necessary but not sufficient. Operational readiness asks a distinct set of questions, and that set decides go-live. In practice, it comes down to whether you can demonstrably answer these:

Can you see what’s happening: monitoring, chain-level tracing, message-level insight? When an incident hits, does someone triage it, and do they have the information they need to do so? For recovery, can the platform handle errors, replay from a known point, and fall back on a real Business Continuity and Disaster Recovery plan rather than an RTO written in a document? Afterward, can you prove what happened through an audit trail, an access log, and change history? On access control, do you separate permanent from elevated rights, and dev from production? For cost, can you attribute it, budget against it, and tier retention? And finally, can you hand it over — have you defined operational ownership, or does every incident route back to the people who built it?

If any of those answers is “only in the design,” please fix it before go-live, not after the first incident teaches you the hard way.

The boundary that decides scale: central versus decentral

The other thing production-readiness has to settle is a boundary, not just a checklist. Most modern integration platforms want value-stream teams to deliver independently within central guardrails. That’s the right ambition. But it only works when you draw the line between central platform ownership and team autonomy deliberately, because that line runs through every layer: API governance, messaging configuration, RBAC, pipeline use, monitoring, error handling, lifecycle, support.

Get the line wrong and you recreate the exact problem the platform set out to solve. The platform team becomes the bottleneck again — the single point through which every change, approval, and incident has to pass. So team autonomy isn’t just a tooling question. It needs explicit ownership agreements, release paths, access models, quality controls, and operational responsibilities. The tooling enables autonomy; the agreements make it safe.

Shared components are where this bites hardest. A shared API gateway, a shared message broker, a shared logging workspace these touch technology, security, governance, operations, cost, and autonomy all at once. They make the platform economical, and they carry the biggest scaling risk. For each one, decide deliberately: why does it stay shared rather than isolated, who owns it, who may change it, how do you monitor it, and how do you attribute its cost? Leave those implicit and the shared component quietly becomes everyone’s dependency and no one’s responsibility.

Readiness isn’t one moment — it’s three

The last reframe worth making: “ready” isn’t a single bar. It’s three different bars at three different moments, and conflating them is how platforms either over-build early or under-prepare for scale.

First go-live. The bar here is the minimum production baseline and demonstrable operational readiness. Not every capability has to be complete, but the ones that are preconditions for running safely in production do. This is where the baseline, the recovery plan, and the release criteria have to be real.

First team onboarding. The bar shifts to whether the federated model actually works in practice. Can one real team deliver independently within the central guardrails, without quality, security, or consistency buckling under the first real use? This is a practice test, and it’s better, even, to let some things get concrete here rather than designing them fully in the abstract.

Scaling to many teams. Now the bar is repeatability. Anything that worked at one team through direct conversation now has to become standardised, documented, and reproducible: lifecycle policy, cost allocation, onboarding, support model, versioning, exception handling. Direct alignment doesn’t scale; product-steering does.

Naming which moment a given concern belongs to is half the battle. It stops you from demanding scale-grade rigour before first go-live, and from discovering at team five that nobody built the repeatable version.

Where this thinking gets over-applied

Consistent with the series, the honesty section. “Production baseline” thinking is right, but it can tip into paralysis.

Not everything has to be complete before first go-live. The three-moments split exists precisely so you don’t. Demanding full lifecycle policy, mature FinOps, and a complete federation model before a single use case runs is how a platform never ships. Match the rigour to the moment.

A baseline that only flags is a baseline that gets ignored. The whole point of the production baseline is that the platform enforces it. A pile of documented-but-unenforced standards manufactures the appearance of readiness without the substance, which is more dangerous than an honest gap, because it invites false confidence.

You can make a decision deliberately without making it central. Drawing the central-versus-decentral line carefully doesn’t mean pulling everything central. Sometimes the deliberate call is “this is team-owned,” and recording that reasoning is the point, not the direction.

The shape of it

For an integration architect, production-readiness isn’t a technical checkpoint; it’s the shift from a platform that’s built to one you can operate responsibly. Make the implicit explicit in a production baseline. Hunt the gap between what’s designed and what’s demonstrable. Answer the operational-readiness questions before go-live, not after. Draw the central-versus-decentral line deliberately, especially for shared components. And treat “ready” as three moments, not one. Do that, and the layers from this series stop being a good architecture on paper and become a platform you can actually run.

This is the lens that ties the series together. The Azure PaaS map has the layer-by-layer foundation; this post is the question you hold every layer up against before you put production load on it.

Azure Data Patterns for Integration Architects

In the Azure PaaS map post, the data layer got one paragraph and a rule: pick by access pattern, not by which service feels modern. That rule holds. But it’s also where most write-ups stop: SQL for relational integrity, Cosmos DB for scale, and Redis in front; for an integration architect, that’s the least interesting part of the story.

The interesting part is what the data layer has to do that’s specific to integration. Messages arrive twice. Workflows run for hours and need somewhere to keep their state. A write to your database and a publish to a queue have to succeed or fail together. So this post skips the service comparison and covers the patterns instead. Azure data patterns for integration are less about which store you pick and more about how you use it.

Why integration data is different

A typical application owns its data. It writes, it reads, it controls the whole path. Integration doesn’t work that way. Instead, integration sits between systems it doesn’t own, reacting to events it didn’t originate, and it has to stay correct when those systems misbehave.

That changes what the data layer is for. It’s no longer just persistence. It becomes the place where you enforce correctness that the messaging layer can’t guarantee on its own. Three patterns come up again and again. Let’s take them in turn.

Pattern 1: Idempotency stores

Here’s the problem. At-least-once delivery is the norm for most messaging systems, including Service Bus. So the same message can arrive twice after a retry, a redelivery, or a consumer crash-and-restart. Process it twice, and you’ve charged the card twice or created two orders. That’s not a rare edge case. In a busy integration platform, it’s a Tuesday.

The fix is an idempotency store. Before you process a message, you check whether you’ve seen its ID before. If you have, you skip it. If you haven’t, you record the ID and proceed. As a result, duplicate deliveries become harmless.

The design questions that matter:

  • Where does the key come from? Ideally, the source system supplies a stable business key, an order ID, and a transaction reference. Failing that, a hash of the message content works, though it’s more fragile.
  • Where do you store it? This is a high-frequency, low-latency lookup on a single key. Therefore Cosmos DB or Redis fit well, and a relational table works too if the volume is modest. The access pattern points at the store, exactly as the map post argued.
  • How long do you keep it? Retention has to outlast the longest possible redelivery window. Too short, and a late duplicate slips through. So set a TTL that comfortably exceeds your retry and dead-letter timelines, then expire old keys automatically.

The honest note: idempotency at the store isn’t the same as an idempotent operation. If the downstream side effect isn’t itself safe to repeat, the store only narrows the window; it doesn’t close it. Design the operation to tolerate retries wherever you can.

Pattern 2: The outbox pattern

This one solves the dual-write problem, and the dual-write problem is subtle enough that plenty of teams ship it broken.

Picture a handler that does two things. It writes a record to the database, and it publishes an event to a queue. Both must happen, or neither. But they’re two separate systems, so there’s no shared transaction. Write succeeds, publish fails; now the database and the downstream world disagree. Publish succeeds, write fails; now you’ve announced something that didn’t happen.

The outbox pattern closes the gap. Instead of publishing directly, you write the event into an “outbox” table in the same database transaction as your business record. Because they share one transaction, they commit together or not at all. Then a separate process reads the outbox and publishes the events, marking each one done as it goes.

A few things fall out of this design:

  • The database becomes the source of truth for what should be published. If the publisher crashes mid-run, it restarts and picks up where it left off. Nothing is lost, because nothing left the database until it was safely committed.
  • Publishing becomes at-least-once. The publisher might send an event, crash before marking it done, and send it again on restart. So the consumer on the other end needs, you guessed it, an idempotency store. The two patterns work together.
  • A change-feed makes it cleaner. Cosmos DB’s change feed, or a similar mechanism, lets the publisher tail committed changes rather than poll a table. That reduces latency and load, though a simple polling publisher is perfectly fine to start.

The trade-off is honest latency. The outbox adds a hop between commit and publish. For most integration workloads that’s a few seconds at most, and well worth it for the correctness guarantee. But if you need genuinely instant propagation, the outbox isn’t your pattern.

Pattern 3: State for long-running workflows

Synchronous request-response keeps its state in memory for the length of a call. Integration workflows don’t have that luxury. A process can span minutes, hours, or days while waiting for approval, a batch window, or an external callback. That state has to live somewhere durable, because the compute running it will scale, restart, and move underneath it.

So where does workflow state go? It depends on who’s orchestrating.

  • Logic Apps and Durable Functions manage their own state: Both persist workflow state for you; that’s a large part of why they exist. Durable Functions keeps it in a storage backend; Standard Logic Apps keeps it in its own runtime store. In these cases, you rarely touch the state directly, but you should know it’s there and know that it’s what makes the workflow survive a restart.
  • Hand-rolled orchestration needs an explicit store: When you’re coordinating steps in your own code rather than a workflow engine, you own the state. A document store like Cosmos DB fits well here: one document per workflow instance, updated as the process advances through its steps. The flexible schema helps, because a workflow’s state shape often evolves as you add steps.
  • Correlation is the piece people forget: Long-running workflows wait for things to come back, and when a callback arrives, you have to match it to the right in-flight instance. That means a correlation ID, stored with the instance and carried on every outbound call. Without it, you have durable state you can’t reconnect to the event that needs it.

Where these patterns are the wrong answer

Consistent with the rest of the series, the honesty section. Patterns solve problems, and applying them where the problem doesn’t exist adds cost.

  • Skip the idempotency store when the operation is naturally idempotent: Setting a status to “shipped” twice changes nothing. If every side effect is already safe to repeat, a dedup store is machinery you don’t need.
  • Skip the outbox when you don’t dual-write: If a handler only writes to the database, or only publishes, there’s no gap to close. The outbox earns its keep specifically when one commit must produce one publish.
  • Skip explicit state stores when a workflow engine already owns the state: Standing up your own Cosmos-backed state store next to Durable Functions duplicates what the runtime already gives you. Reach for the explicit store only when you’re orchestrating by hand.

The shape of it

For an integration architect, the data layer isn’t mainly a choice between SQL and Cosmos. That choice matters, but the access pattern usually makes it for you. The real work is the patterns that keep an integration platform correct when systems it doesn’t control misbehave. So an idempotency store absorbs duplicate deliveries. An outbox makes both a write and a publish succeed. A durable state store lets a workflow outlive the compute running it. Get those right, and the underlying store SQL, Cosmos, and Redis become implementation details rather than the headline.

Want the layer this sits inside? The Azure PaaS map puts data in context against compute, integration, and governance, and walks the five-question framework across all of them. And the messaging and orchestration post covers the delivery guarantees these patterns lean on.

Citadel APIM Gateway Policies Azure: A Deep Dive

The Citadel APIM gateway policies on Azure are doing the heavy lifting silently in every post in this series. We deployed the hub, connected a tool-calling agent, added conversation persistence, and demonstrated the kill switch. Throughout all of that, every chat completion request passed through these policies. They counted every token. They produced all usage telemetry. This post opens the hood and examines all five Citadel APIM gateway policy layers in Azure token rate limiting, semantic caching, content safety routing, cost attribution, and PII redaction with the actual policy XML, live demonstration results, and honest debugging sessions included.

Where the Citadel APIM Gateway Policies Live in Azure

The Citadel hub deploys two types of policies.

API-level policies apply to all operations on the Azure OpenAI API for every chat completion, embedding, and batch request. These contain the token-limiting, usage-tracking, and routing logic.

Policy fragments serve as reusable blocks that you include by reference. The hub uses fragments for AAD authorization (aad-auth), load balancing (openai-backend-pool), and dynamic throttling (dynamic-throttling-assignment).

In the portal, find them at apim-wpvlimv4ngkns → APIs → Azure OpenAI Service API → All operations → Policies.

The full policy XML is also in the repo at github.com/Azure-Samples/ai-hub-gateway-solution-accelerator under infra/modules/apim/policies/.

Citadel APIM Gateway Policy 1 — Token Rate Limiting

What It Does

APIM natively supports rate limiting on the number of requests per time window. The hub repurposes this to manage capacity based on tokens — the azure-openai-token-limit policy limits how many tokens per minute a subscription can consume, using a counter keyed to the APIM subscription.

The Policy XML

Token rate limiting — inbound section:

<azure-openai-token-limit
counter-key="@(context.Subscription.Id)"
tokens-per-minute="10000"
estimate-prompt-tokens="true"
tokens-consumed-variable-name="TotalConsumedTokens"
remaining-tokens-variable-name="RemainingTokens"
/>

Line by line:

  • counter-key=”@(context.Subscription.Id)” — the counter is per APIM subscription, so each spoke gets its own independent token budget.
  • tokens-per-minute=”10000″ — 10,000 TPM limit per subscription; adjust per spoke based on workload.
  • estimate-prompt-tokens=”true” — APIM estimates prompt tokens before the response arrives, enabling proactive rate limiting rather than post-hoc tracking.
  • tokens-consumed-variable-name=”TotalConsumedTokens” — stores the running count for use by downstream policies (cost attribution reads this variable).

Demonstration

The Citadel hub actually applies two independent token limit policies at different scopes, and tracing the real behaviour reveals an important lesson about how APIM evaluates them.

Scope 1 — subscription-level, per deployment. The product policy on oai-retail-assistant assigns a different tokens-per-minute value based on the targeted deployment.

<when condition="@((string)context.Variables["target-deployment"] == "chat")">
<azure-openai-token-limit
counter-key="@(context.Subscription.Id + "-" + context.Variables["target-deployment"])"
tokens-per-minute="50"
token-quota="10000"
token-quota-period="Weekly"
tokens-consumed-header-name="consumed-tokens"
remaining-tokens-header-name="remaining-tokens"
retry-after-header-name="retry-after"
/>
</when>

Scope 2 — product-level, across all deployments. A second, independent counter applies a higher ceiling across the entire product:

<azure-openai-token-limit
counter-key="@(context.Product?.Name?.ToString() ?? "Portal-Admin")"
tokens-per-minute="15000"
token-quota="150000"
token-quota-period="Monthly"
tokens-consumed-header-name="consumed-tokens"
remaining-tokens-header-name="remaining-tokens"
/>

Both policies execute on every request, each maintaining its own counter. Whichever limit you hit first governs the response, regardless of which one you configured.

Live test — three rapid requests against the chat deployment with the subscription-level limit set to 50 TPM:

$response1 = Invoke-WebRequest -Uri $uri -Method POST -Headers $headers -Body $body
Write-Host "Status: $($response1.StatusCode)"
Write-Host "Remaining-Tokens: $($response1.Headers['remaining-tokens'])"

Results:

REQUEST 1 — Status: 200, Remaining-Tokens: 14940, Consumed-Tokens: 15

REQUEST 2 — Status: 429, Body: “Token limit is exceeded. Try again in 51 seconds.”

REQUEST 3 — Status: 429, Body: “Token limit is exceeded. Try again in 51 seconds.”

Notice that Remaining-Tokens: 14940 on the first request comes from the product-level counter (15000 TPM, barely touched). The 429 on request 2, however, comes from the subscription-level counter for the chat deployment, which only allows 50 tokens per minute, exhausted after a single 15-token call. The visible remaining-tokens header reflects whichever counter last wrote to it, which can be misleading if you assume there is only one limit in play.

Pitfall: Multiple Token Limit Scopes Stack Independently

When multiple azure-openai-token-limit policy elements exist at the API level, product level, and per deployment in a choose block, they are all evaluated for each request. In addition, the most restrictive policy that triggers first decides the outcome. Furthermore, to debug rate limit issues, check all policy scopes: API-level, product-level, and deployment-specific branches. A Named Value in one scope doesn’t affect a hardcoded limit in another.

Citadel APIM Gateway Policy 2 — Semantic Caching

What It Does

Semantic caching intercepts requests before they reach Azure OpenAI and checks for previously answered semantically similar questions. If it finds a match above the configured similarity threshold, it returns the cached response immediately, using zero tokens and ensuring near-zero latency.

The Policy XML

The lookup and store directives belong in different policy sections — lookup runs on the inbound request, store runs on the outbound response after a successful call.

Semantic caching — inbound section:

<azure-openai-semantic-cache-lookup
score-threshold="0.8"
embeddings-backend-id="openai-backend-0"
embeddings-backend-auth="system-assigned"
ignore-system-messages="true"
max-message-count="5"
/>

Semantic caching — outbound section:

<azure-openai-semantic-cache-store duration="600" />

Line by line:

  • score-threshold=”0.8″ — similarity must be 80% or higher for a cache hit. Lower values increase hit rate but risk returning mismatched responses.
  • embeddings-backend-id=”openai-backend-0″ — points to the backend that hosts the embeddings deployment used for cache lookup. The embeddings model itself is configured on the backend, not as a policy attribute — embeddings-model is not a valid attribute on this policy element and will fail schema validation if added.
  • embeddings-backend-auth=”system-assigned” — the embeddings backend call is authenticated via the APIM instance’s system-assigned managed identity.
  • ignore-system-messages=”true” — only user messages are used for cache key generation, not system prompts.
  • max-message-count=”5″ — only the last 5 messages in a conversation are used for cache lookup.
  • duration=”600″ — cached responses expire after 10 minutes.

Demonstration

First request — cache miss:

python agent.py
# Question: What is the weather like in Stockholm right now?
# Response time: 1.2 seconds

Second request — cache hit:

python agent.py
# Question: What is the weather in Stockholm today?
# Response time: 45ms

The second question resembles the first semantically, but it’s not an exact match. The 0.8 threshold identifies it as a cache hit, allowing the system to return the response from the cache in 45ms without making an Azure OpenAI call or using any tokens. For a conversational agent that often encounters similar questions, semantic caching can lower token consumption by 20–40%.

Production Consideration

The cache shares its data across all subscribers to the same APIM product. If two spokes utilize the same APIM gateway, Spoke A’s cached response can serve Spoke B for a similar inquiry. To protect sensitive data, configure the cache key to be scoped per subscription by adding @(context.Subscription.Id).

Pitfall: Policy Section Placement and Schema Validation

When adding semantic caching for the first time, you may encounter two common schema errors. First, placing azure-openai-semantic-cache-store in the inbound section, along with the lookup policy, results in the error: “Policy is not allowed in this section.” Second, you’ll find that embeddings-model is not a declared attribute on azure-openai-semantic-cache-lookup. Instead of being specified directly in the policy, the embeddings deployment is retrieved from the backend referenced by embeddings-backend-id. You can quickly identify both errors when you save the policy in the portal, which provides the fastest validation of your XML before deployment.

Citadel APIM Gateway Policy 3 — Content Safety Routing

What It Does

The hub routes every request through Azure AI Content Safety before it reaches Azure OpenAI. It inspects both the user prompt and the model response for harmful content in four categories: hate, self-harm, sexual, and violence. The system blocks any requests or responses that exceed the configured severity thresholds.

The Policy XML

Content safety — inbound section:

<llm-content-safety backend-id="content-safety-backend" shield-prompt="true">
<categories output-type="FourSeverityLevels">
<category name="Hate" threshold="2" />
<category name="SelfHarm" threshold="2" />
<category name="Sexual" threshold="2" />
<category name="Violence" threshold="2" />
</categories>
</llm-content-safety>

Line by line:

  • backend-id=”content-safety-backend” — routes to the cog-consafety-wpvlimv4ngkns Azure AI Content Safety instance deployed in the hub.
  • shield-prompt=”true” — enables Prompt Shields, which additionally detects jailbreak attempts and prompt injection on top of standard content categories.
  • categories output-type=”FourSeverityLevels” — selects the four-level severity scale (0, 2, 4, 6) rather than the eight-level scale; each category child element sets its own threshold independently.
  • category name=”…” threshold=”2″ — one element per category (Hate, SelfHarm, Sexual, Violence), each can have a different threshold. A threshold of 2 blocks low severity and above; omitting a category leaves it unchecked.

You can reference custom Azure AI Content Safety blocklist IDs in an optional blocklists element to always block organization-specific terms, regardless of their severity scoring.

Pitfall: Element Name and Schema

The element is llm-content-safety, not azure-content-safety — using the wrong name produces “There is no policy matching element name” on save. The schema is also structural rather than attribute-based: categories are child category elements inside a categories block, not a flat comma-separated categories=”…” attribute. Both errors surface immediately in the portal policy editor, which validates the XML before allowing a save.

Demonstration

Normal request — content safety passes silently:

python agent.py
# Question: What is the weather like in Stockholm?
# Answer: The weather in Stockholm is overcast...

The Policy

The llm-content-safety policy does not add a confirmation header on a passing request — the absence of a block response is the only signal that the prompt and response cleared all four category thresholds. To confirm the policy actually ran, check Application Insights:

requests
| where timestamp > ago(10m)
| where resultCode == "200"
| project timestamp, name, resultCode, duration
| order by timestamp desc

A 200 with normal duration confirms the request passed through llm-content-safety without being blocked.

Harmful content

Blocked request — harmful content detected:

# Modify agent.py to send a harmful prompt, then run:
python agent.py
# openai.BadRequestError: Error code: 400
# 'Request failed content safety check.'

Requests block at the gateway before they reach Azure OpenAI, ensuring that these blocked requests consume no tokens. In Application Insights, you observe the block as a 400 response with near-zero duration, reflecting the same signature pattern seen with the kill switch layers mentioned in the previous post.

Citadel APIM Gateway Policy Policy 4 — Cost Attribution

What It Does

Every request that completes successfully generates a usage event sent to Azure Event Hub. A Logic App deployed in the hub consumes these events and writes structured documents to the Cosmos DB ai-usage-container. Each document contains token counts, model version, gateway region, APIM subscription name, and timestamp, giving you per-subscription cost attribution without any agent-side code changes.

The Policy XML

The hub deploys three named loggers, visible via az rest against the APIM management API: appinsights-logger for Application Insights telemetry, usage-eventhub-logger for the cost attribution pipeline described here, and a separate pii-usage-eventhub-logger for PII-specific event logging tied to the redaction policy described later in this post. The logger-id attribute on log-to-eventhub must match one of these exactly — using a placeholder or guessed name produces “Logger not found” when saving the policy.

Cost attribution — outbound section:

<log-to-eventhub logger-id="usage-eventhub-logger" partition-id="0">
@{
var response = context.Response;
var request = context.Request;
var usage = response.Body.As<JObject>(true)?["usage"];
return new JObject(
new JProperty("id", context.Response.Headers.GetValueOrDefault("x-request-id", Guid.NewGuid().ToString())),
new JProperty("timestamp", DateTime.UtcNow.ToString("o")),
new JProperty("subscriptionId", context.Subscription?.Id),
new JProperty("productName", context.Product?.Name),
new JProperty("targetService", "chat.completion"),
new JProperty("model", response.Body.As<JObject>(true)?["model"]?.ToString()),
new JProperty("gatewayName", context.Deployment.ServiceName),
new JProperty("gatewayRegion", context.Deployment.Region),
new JProperty("RequestIp", request.IpAddress),
new JProperty("promptTokens", usage?["prompt_tokens"]?.ToObject<int>() ?? 0),
new JProperty("responseTokens", usage?["completion_tokens"]?.ToObject<int>() ?? 0),
new JProperty("totalTokens", usage?["total_tokens"]?.ToObject<int>() ?? 0),
new JProperty("backendId", context.Variables.GetValueOrDefault<string>("backendId")),
new JProperty("deploymentName", context.Request.MatchedParameters["deployment-id"])
).ToString();
}
</log-to-eventhub>

Key fields:

  • context.Subscription?.Id and context.Product?.Name — the APIM subscription and product name used for the request. In a multi-spoke setup, each spoke has its own APIM product making cost attribution per initiative automatic.
  • usage?[“prompt_tokens”] / usage?[“completion_tokens”] — extracted directly from the Azure OpenAI response body.
  • context.Deployment.Region — the gateway region (Sweden Central) for data residency auditing.
  • context.Variables.GetValueOrDefault<string>(“backendId”) — which Azure OpenAI backend served the request, critical for multi-region deployments.

Demonstration

Run the agent:

python agent.py

Then query the hub Cosmos DB in the portal (cosmos-wpvlimv4ngkns → Data Explorer → ai-usage-container → Items):

SELECT TOP 5 c.timestamp, c.productName, c.model,
c.promptTokens, c.responseTokens, c.totalTokens,
c.gatewayRegion, c.deploymentName
FROM c ORDER BY c._ts DESC

A real document from the deployed hub looks like this:

{
"timestamp": "6/30/2026 11:26:49 AM",
"productName": "OAI-HR-Assistant",
"model": "gpt-4o-2024-11-20",
"promptTokens": 93,
"responseTokens": 56,
"totalTokens": 149,
"gatewayRegion": "Sweden Central",
"deploymentName": "chat"
}

Each agent run produces two documents, one for the tool decision call and one for the synthesis call. The totalTokens across both documents is the true per-conversation cost. The productName field maps directly to the APIM product the calling subscription belongs to, in this example OAI-HR-Assistant, distinct from any other product sharing the same hub.

FinOps in Practice

In production with multiple spokes, filter by productName to get per-initiative cost:

SELECT c.productName,
SUM(c.totalTokens) as totalTokens,
COUNT(1) as requestCount
FROM c
WHERE c.timestamp >= "2026-06-01T00:00:00Z"
GROUP BY c.productName

Run against the live hub, this returns a clean per-product summary:

[
{
"productName": "Portal-Admin",
"totalTokens": 3865,
"requestCount": 32
},
{
"productName": "OAI-HR-Assistant",
"totalTokens": 3035,
"requestCount": 31
}
]

Two distinct products, each with an independently aggregated token total and request count, no additional instrumentation required beyond the log-to-eventhub policy already in place. This is your direct FinOps input per AI initiative, per month, ready to feed into a PowerBI report or a monthly cost allocation process.

Citadel APIM Gateway Policy 5 — PII Redaction

What It Does

The hub detects personally identifiable information — names, email addresses, phone numbers, IBAN numbers, and other entity types — in conversation content and logs a redacted version to a dedicated Event Hub logger. The original request still reaches Azure OpenAI unmodified; only the logged version is clean.

There Is No Built-In Policy Element for This

The blog draft for this post originally referenced an azure-openai-pii-removal-logging policy element, on the assumption that APIM ships a built-in PII redaction policy the same way it ships azure-openai-token-limit and azure-openai-semantic-cache-lookup. It does not. Saving a policy referencing that element name fails immediately with “There is no policy matching element name,” the same class of error encountered earlier with azure-content-safety versus the correct llm-content-safety.

Unlike content safety, however, there is no equivalent built-in alternative for PII detection at the time of writing. The hub’s pii-usage-eventhub-logger, visible alongside usage-eventhub-logger and appinsights-logger when listing loggers via the APIM management API, exists as infrastructure for this purpose, but the policy that populates it has to be built explicitly using send-request to call Azure AI Language Service directly, then log-to-eventhub to write the result.

The Policy XML

This belongs entirely in outbound, immediately after the cost attribution log-to-eventhub block. PII detection runs on the response side rather than inbound because the goal is to log a redacted record of the conversation, not to block or alter the request itself, context.Request.Body remains accessible in the outbound pipeline, so the original user message can still be analysed at this stage.

PII detection — outbound section, after cost attribution:

<send-request mode="new" response-variable-name="piiDetectionResponse" timeout="10" ignore-error="true">
<set-url>@("https://" + "{{language-service-name}}" + ".cognitiveservices.azure.com/language/:analyze-text?api-version=2023-04-01")</set-url>
<set-method>POST</set-method>
<set-header name="Ocp-Apim-Subscription-Key" exists-action="override">
<value>{{language-service-key}}</value>
</set-header>
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
var requestBody = context.Request.Body.As<JObject>(true);
var userMessage = requestBody["messages"]?.Last?["content"]?.ToString() ?? "";
return new JObject(
new JProperty("kind", "PiiEntityRecognition"),
new JProperty("analysisInput", new JObject(
new JProperty("documents", new JArray(
new JObject(
new JProperty("id", "1"),
new JProperty("language", "en"),
new JProperty("text", userMessage)
)
))
))
).ToString();
}</set-body>
</send-request>
<log-to-eventhub logger-id="pii-usage-eventhub-logger" partition-id="0">
@{
var piiResult = ((IResponse)context.Variables["piiDetectionResponse"]).Body.As<JObject>(true);
var redactedText = piiResult?["results"]?["documents"]?[0]?["redactedText"]?.ToString() ?? "[pii-detection-unavailable]";
var entityCount = piiResult?["results"]?["documents"]?[0]?["entities"]?.Count() ?? 0;
return new JObject(
new JProperty("timestamp", DateTime.UtcNow.ToString("o")),
new JProperty("subscriptionId", context.Subscription?.Id),
new JProperty("productName", context.Product?.Name),
new JProperty("redactedText", redactedText),
new JProperty("piiEntitiesFound", entityCount)
).ToString();
}
</log-to-eventhub>

Line by line:

  • send-request mode=”new” — fires an independent outbound call to Azure AI Language Service rather than reusing the current request/response context. ignore-error=”true” means a Language Service outage does not fail the agent’s actual response, only the PII logging step is skipped.
  • requestBody[“messages”]?.Last?[“content”] — extracts the most recent user message from the original request body for analysis, since that is where PII is most likely to appear.
  • The Language Service PiiEntityRecognition endpoint returns both a redactedText field (PII replaced with asterisks) and an entities array listing every detected entity and its category.
  • log-to-eventhub logger-id=”pii-usage-eventhub-logger” — writes the redacted text and entity count to the dedicated PII logger, kept separate from the general usage logger so PII-related audit records can be access-controlled independently.

Two Named Values must exist before this policy validates:

az apim nv create \
--resource-group rg-ai-hub-gateway-dev \
--service-name apim-wpvlimv4ngkns \
--named-value-id language-service-name \
--display-name "language-service-name" \
--value "cog-language-wpvlimv4ngkns" \
--secret false
az apim nv create \
--resource-group rg-ai-hub-gateway-dev \
--service-name apim-wpvlimv4ngkns \
--named-value-id language-service-key \
--display-name "language-service-key" \
--value "<your-language-service-key>" \
--secret true

Retrieve the Language Service key:

az cognitiveservices account keys list \
--name cog-language-wpvlimv4ngkns \
--resource-group rg-ai-hub-gateway-dev \
--query key1 -o tsv

Demonstration

Request containing PII:

question = "What is the weather near Jan Janssen who lives at Keizersgracht 123 Amsterdam?"

First attempt, the policy ran but logged the wrong data. The send-request call to Azure AI Language Service fired correctly and returned 200 every time, confirmed via Application Insights dependency tracking:

dependencies
| where timestamp > ago(10m)
| where target contains "cognitiveservices"
| project timestamp, name, target, resultCode, duration
POST /language/:analyze-text → 200 → 68.62ms
POST /language/:analyze-text → 200 → 48.26ms
POST /language/:analyze-text → 200 → 106.96ms

Yet the documents landing in pii-usage-container showed no redactedText field at all, only promptTokens, gatewayName, backendId, and the rest of the cost attribution schema:

{
"id": "30db8c4b-ce45-4695-9078-e357405845bc",
"subscriptionId": "oai-hr-assistant-sub-01",
"productName": "OAI-HR-Assistant",
"model": "gpt-4o-2024-11-20",
"promptTokens": 109,
"responseTokens": 21,
"gatewayName": "apim-wpvlimv4ngkns.azure-api.net",
"backendId": "openai-backend-0"
}

The cause turned out to be a copy-paste error in the log-to-eventhub block itself. The comment above it correctly read “PII detection and redacted logging,” but the JObject construction inside was a verbatim duplicate of the cost attribution payload from usage-eventhub-logger, it never referenced context.Variables[“piiDetectionResponse”] at all. The Language Service call succeeded and its result sat in a context variable, completely unused, while the logger faithfully wrote the wrong document every time. Every dependency call returned 200; every Cosmos DB write succeeded; nothing in the telemetry indicated a problem. The only way to catch it was reading the document schema in Cosmos DB and noticing it matched the usage container rather than containing redacted text.

The fix was correcting the log-to-eventhub body to actually read the stored piiDetectionResponse variable:

<log-to-eventhub logger-id="pii-usage-eventhub-logger" partition-id="0">@{
var piiResult = ((IResponse)context.Variables["piiDetectionResponse"]).Body.As<JObject>(true);
var redactedText = piiResult?["results"]?["documents"]?[0]?["redactedText"]?.ToString() ?? "[pii-detection-unavailable]";
var entityCount = piiResult?["results"]?["documents"]?[0]?["entities"]?.Count() ?? 0;
return new JObject(
new JProperty("id", context.Response.Headers.GetValueOrDefault("x-request-id", Guid.NewGuid().ToString())),
new JProperty("timestamp", DateTime.UtcNow.ToString("o")),
new JProperty("subscriptionId", context.Subscription?.Id),
new JProperty("productName", context.Product?.Name),
new JProperty("redactedText", redactedText),
new JProperty("piiEntitiesFound", entityCount)
).ToString();
}</log-to-eventhub>

After the fix, the same question produced the correct redacted record:

{
"id": "419321ce-0544-4908-a2ac-9ce10f80aaba",
"timestamp": "2026-06-30T13:12:24.8989851Z",
"subscriptionId": "oai-hr-assistant-sub-01",
"productName": "OAI-HR-Assistant",
"redactedText": "What is the weather near *********** who lives at ***************************?",
"piiEntitiesFound": 2
}

Two entities detected and redacted, the person’s name and the street address, while the sentence structure remains intact for log readability. A second request, where the agent’s tool call itself failed to resolve the address, still produced a correctly redacted record of the error message:

{
"redactedText": "{\"error\": \"Location '***************************' not found.\"}",
"piiEntitiesFound": 1
}

This confirms PII redaction applies consistently regardless of whether the underlying tool call succeeds, the policy operates on the original user message, independent of how the agent’s downstream logic handles it.

In Cosmos DB usage documents, unaffected: the cost attribution document written by usage-eventhub-logger still contains only token counts and metadata, never request body content, so PII redaction applies exclusively to the dedicated pii-usage-container stream.

Pitfall: A Logger Existing Does Not Mean It Logs the Right Thing

The most instructive failure in this section was not a missing policy element or a schema validation error, it was a policy that validated, deployed, and executed successfully while silently logging the wrong payload. Every signal that normally indicates “this is working” was green: the send-request dependency call returned 200, the log-to-eventhub write succeeded, and documents appeared in Cosmos DB on schedule. The only way to catch the bug was to inspect the actual field names in the logged document and notice they matched a different policy’s output entirely. When wiring up custom logging policies, always verify the logged document shape directly in the data store, a successful HTTP status code on a dependency call says nothing about whether its result was ever used downstream.

Pitfall: Two send-request Round Trips Add Latency

Every request now makes an additional outbound call to Azure AI Language Service before the agent’s response is returned to the caller, since send-request blocks until it completes (or times out at 10 seconds with ignore-error=”true”). For latency-sensitive workloads, consider moving PII detection to an asynchronous pattern, log raw request IDs to Event Hub immediately, then run PII detection as a separate downstream process reading from the Event Hub stream, rather than inline in the request path.

The Complete Policy Execution Order

Understanding the order in which policies execute is critical for troubleshooting. APIM processes policies in this sequence.

Inbound, request processing, top to bottom:

  1. Kill switch check (Named Value flip)
  2. Agent approval header validation
  3. Agent ID blocklist check
  4. AAD authorization (aad-auth fragment)
  5. Token rate limiting (azure-openai-token-limit)
  6. Semantic cache lookup (azure-openai-semantic-cache-lookup)
  7. Content safety check (inbound prompt, llm-content-safety)
  8. Backend routing (load balancer)

Outbound, response processing, top to bottom:

  1. Usage event capture (cost attribution fragment)
  2. Semantic cache store (azure-openai-semantic-cache-store)
  3. PII detection request (send-request to Language Service)
  4. Cost attribution logging (log-to-eventhub, usage-eventhub-logger)
  5. PII redaction logging (log-to-eventhub, pii-usage-eventhub-logger)
  6. Response header enrichment

On-error:

  1. Error response formatting
  2. Retry logic (if configured)

This order means a request blocked by the kill switch never reaches token rate limiting, content safety, or Azure OpenAI. A request blocked by content safety never reaches cost attribution or PII logging, no usage document and no redacted-text document are created for blocked requests.

Validating All Five Policies in Application Insights

Use this KQL query to see the policy execution evidence in one view:

requests
| where timestamp > ago(24h)
| extend
cacheHit = tostring(customDimensions["x-cache"]),
tokensConsumed = toint(customDimensions["TotalConsumedTokens"]),
remainingTokens = toint(customDimensions["RemainingTokens"])
| project timestamp, resultCode, duration, cacheHit, tokensConsumed, remainingTokens
| order by timestamp desc

Each column corresponds to a policy layer.

  • resultCode — 200 (all policies passed, including content safety), 400 (content safety block), 429 (token rate limit), 403/401 (kill switch).
  • cacheHit — hit or miss from semantic cache.
  • tokensConsumed — running token count from rate limiter.
  • remainingTokens — remaining budget for this subscription.

There is no dedicated content safety column because llm-content-safety does not emit a custom telemetry property, its outcome is entirely reflected in resultCode. A 400 with near-zero duration is the signature of a content safety block, the same pattern used to identify kill switch activations in the previous post.

For PII detection specifically, dependency tracking shows whether the Language Service call fired:

dependencies
| where timestamp > ago(24h)
| where target contains "cognitiveservices" and name contains "analyze-text"
| project timestamp, name, target, resultCode, duration
| order by timestamp desc

A 200 here only confirms the call succeeded, it does not confirm the result was logged correctly downstream. Cross-check against the actual documents in pii-usage-container to verify the redactedText field is present and populated, not just that the dependency call returned successfully.

Pitfalls Summary

Token rate limiting doesn’t work for streaming. Fix: use non-streaming endpoints for accurate token counting.

Semantic cache returns stale weather data. Fix: reduce duration to 60 seconds for time-sensitive tool calls.

Content safety blocks valid medical terminology. Fix: raise threshold to 4 for healthcare-specific deployments and validate against your use case.

azure-content-safety element does not exist. Fix: use llm-content-safety with categories and category child elements, not flat attributes.

azure-openai-pii-removal-logging element does not exist. Fix: no built-in policy exists, implement via send-request to Language Service plus a custom log-to-eventhub.

The logger successfully writes but records incorrect data. To fix this, a 200 status on the send-request and a successful write to Event Hub do not guarantee that the result was actually used. Instead, verify the logged document schema directly in Cosmos DB.

The system misses redacting Dutch-language names. To fix this issue, optimize the analyze-text request by setting the language to “nl” and testing it with representative Dutch inputs, instead of using “en,” which is optimized for English.

Cost attribution missing for some requests. Fix: check Event Hub to Logic App pipeline; ingestion lag of 2 to 5 minutes is normal.

To ensure high compliance in production, always surface failures in content safety and PII detection instead of silently bypassing them with the on-error-action or ignore-error=”true” settings.

Conclusion

The five APIM policies in the Citadel hub, token rate limiting, semantic caching, content safety, cost attribution, and PII redaction, collectively implement enterprise AI governance at the gateway layer. None of them require changes to agent code. None of them require spoke involvement. All of them apply to every request from every agent that routes through the hub, regardless of which spoke deployed it.

Furthermore, they compose cleanly: a request that hits the semantic cache never reaches token rate limiting, content safety, or Azure OpenAI. As a result, cached responses consume zero tokens, zero content safety budget, and zero Azure OpenAI quota. Similarly, a request blocked by content safety produces no cost attribution event and no PII redaction record.

This composability is what makes the Citadel APIM hub a governance layer rather than just a proxy. The policies work together, in a defined order, to enforce the enterprise AI control plane pattern across every governed workload, though, as the PII redaction section makes clear, composability and correct execution are not the same thing. A policy chain can validate, deploy, and run green across every dependency call while still logging the wrong data. The only reliable verification is checking the actual data that lands in the store, not the status codes along the way.

Azure Messaging and Orchestration for Integration Architects

In the Azure PaaS map post, the integration layer got a single paragraph. It named four services: Logic Apps, API Management, Service Bus, and Event Grid, and moved on. This post takes Azure messaging and orchestration apart into the decisions underneath that paragraph.

I won’t tour features here. Two of these services already have their own deep series on this blog, so re-covering them would waste your time. Instead, I’ll stay at the decision layer. When do you reach for which? And why do teams so often reach wrong? Those are the questions that actually cost you in production.

Azure messaging and orchestration: two axes decide almost everything

Four services sound like four choices. In practice, though, only two questions matter, and they cut across the whole layer.

  • First: is this messaging or orchestration? Messaging moves events and data between systems. Orchestration coordinates a multi-step process toward an outcome. The two look similar on a whiteboard, but they fail differently, scale differently, and belong to different services. So separate them before anything else.
  • Second: what does failure cost, and what shape is the work? Once you know whether you’re moving messages or coordinating steps, the follow-up question splits the choice further. For messaging, the cost of a lost message decides it. For orchestration, the complexity of the flow and the team who owns it decide it.

Get those two axes clear, and the service almost picks itself. Skip them, and you end up with Event Grid where you needed guarantees, or a Logic App doing work that belonged in code.

Messaging: Service Bus vs Event Grid

Both move things between systems. That’s where the similarity ends.

  • Service Bus is the durable, ordered, transactional backbone. Reach for it when delivery has to be guaranteed. It gives you sessions for ordered processing, dead-lettering for messages that can’t be handled, and transactional handling across multiple operations. Topics and subscriptions add pub/sub without a separate broker. So Service Bus fits business messages: an order, a payment, a claim, where losing one is an incident.
  • Event Grid is a lightweight, high-volume router. It broadcasts events to whoever cares: resource state changes, custom application events, and telemetry. It’s built for throughput and fire-and-forget delivery, not guaranteed processing. Therefore, it fits notifications and reactive triggers, where a missed event is a shrug rather than a page.

Here’s the rule of thumb I give teams new to Azure messaging. If losing a message would be a business incident, it belongs on Service Bus. If losing it would just mean a missed notification, Event Grid is fine.

And often you use both. A common pattern pairs them: Event Grid fans out a notification, and a subscriber drops a durable message onto Service Bus for guaranteed processing. That way you get Event Grid’s reach and Service Bus’s reliability in one flow, each doing the job it’s good at.

The honest note, though, is that this is where teams get burned. Event Grid looks simpler, so teams default to it. Then, weeks later, they discover the workload actually needed ordering or delivery guarantees. Now they’re bolting reliability onto a service that was never designed for it. So decide on the message-loss cost first, before the “which feels easier” instinct takes over.

Orchestration: Logic Apps vs code

Messaging moves things. Orchestration coordinates them. The decision here isn’t about reliability; it’s about complexity and ownership.

  • Logic Apps is the designer-first route. It shines when you need enterprise connectors SAP, IBM MQ, mainframe hosts, the long tail of line-of-business systems without a modern REST API. Standard Logic Apps also closes the old gaps that made it hard in regulated environments: VNet integration, built-in state, per-workflow scaling. So for a workflow that a less code-heavy team will own and maintain, Logic Apps is often the right call even when a Function would be more elegant.
  • Code is the route once complexity climbs. Designer workflows are fast to build and easy to read at first. Past a certain size, though, they get hard to reason about and harder to code-review. In my experience, the practical ceiling sits around a dozen actions with a couple of branches. Beyond that, do one of two things. Either decompose the workflow into smaller ones, or move the logic into a Function where a proper language and real tests take over.

The deciding questions, then, are simple. Who maintains this: a low-code team or engineers? How complex is the flow really? And can you review it a year from now? For the deeper mechanics of building agentic workflows in Logic Apps, I covered that ground in the Logic Apps Agent Loop series so that I won’t repeat it here.

Where API Management fits

Azure API Management (APIM) isn’t messaging or orchestration. Instead, it’s the control point in front of both.

It sits between consumers and whatever does the real work: a Logic App, a Function, an App Service backend. From there, it enforces rate limits, authentication, transformation, and policy-based routing. So when multiple consumers hit a shared set of backend capabilities, APIM lets you change the implementation behind them without breaking anyone, and lets you enforce policy without touching application code.

That’s all I’ll say here, because APIM earns a series of its own. I went deep on it in the APIM for AI workloads series, including how it behaves as an AI gateway. For this layer, treat it as the front door that governs whatever messaging and orchestration sit behind it.

Where each is the wrong answer

Every service here has a failure mode when you reach for it by reflex. So, to keep this honest:

  • Service Bus is wrong for high-volume telemetry: If you’re routing millions of fire-and-forget events and none of them individually matter, Service Bus is expensive overkill. Use Event Grid.
  • Event Grid is wrong for anything needing order: The moment sequence or guaranteed delivery matters, Event Grid stops fitting. Move to Service Bus before the gap bites.
  • Logic Apps is wrong past its complexity ceiling: A workflow with thirty actions and nested branches is a maintenance liability in the designer. Decompose it, or move it to code.
  • Code is wrong for something a citizen developer should own: Not every integration belongs in a repo. If a low-code team can own and maintain a simple connector-driven flow, hand-writing it in a Function just centralizes work that didn’t need to be centralized.

The shape of it

Azure gives you four integration services, but you don’t choose between four things. You answer two questions. Is this messaging or orchestration? And then what does failure cost, and who owns the work? Answer those, and Service Bus, Event Grid, Logic Apps, or a Function each falls out naturally, with APIM governing the front.

In practice, real platforms use several together: APIM, fronting Logic Apps, and Functions, Event Grid fanning out to Service Bus for reliable processing. So the craft of Azure messaging and orchestration isn’t picking a winner. It’s drawing clean boundaries between them.

Want the layer above this one? The Azure PaaS map puts integration in context against compute, data, and governance, and walks the five-question framework for choosing across all of them.